我目前正在研究一款短信應用程序,它與股票短信應用程序非常相似。Android - 如何使一個活動加載更快?
但問題是我的應用程序加載比股票(內置)應用程序慢得多。
這裏是我的應用程序的代碼: -
public class ThreadData extends ListActivity
{
private static final Uri SMS_URI = Uri.parse("content://sms");
ArrayList<String> bodies = new ArrayList<String>();
MySMSAdapter adapter;
String name;
public void onCreate(Bundle bundle)
{
super.onCreate(bundle);
setContentView(R.layout.threadlist);
Bundle extras = getIntent().getExtras();
if(extras != null)
{
name = extras.getString("address");
}
Cursor cursor = getContentResolver().query(SMS_URI, null, null, null, "date ASC");
startManagingCursor(cursor);
while (cursor.moveToNext())
{
String Id = cursor.getString(cursor.getColumnIndex("_id"));
String address = cursor.getString(cursor.getColumnIndex("address"));
String body = cursor.getString(cursor.getColumnIndexOrThrow("body"));
String personName = getPersonName(Id, address);
if(personName.equals(name))
{
bodies.add(body);
}
}
//adapter = new MySMSAdapter(this, bodies);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.sms_inbox, R.id.row, bodies);
ListView listView = getListView();
listView.setAdapter(adapter);
}
public String getPersonName(String id, String address)
{
if(id==null)
{
if(address != null)
{
return PhoneNumberUtils.formatNumber(address);
}
else
{
return null;
}
}
Cursor c = this.getContentResolver().query(Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, address),
new String[] { ContactsContract.PhoneLookup.DISPLAY_NAME }, null, null, null);
if(c != null)
{
try
{
if(c.getCount() > 0)
{
c.moveToFirst();
return c.getString(0);
}
}
finally
{
c.close();
}
}
if(address != null)
{
return PhoneNumberUtils.formatNumber(address);
}
return null;
}
}
我的自定義適配器: -
public class MySMSAdapter extends BaseAdapter
{
private Activity activity;
private ArrayList<String> data;
LayoutInflater inflater;
public MySMSAdapter(Activity a, ArrayList<String> arrayList)
{
activity = a;
data = arrayList;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount()
{
return data.size(); //To change body of implemented methods use File | Settings | File Templates.
}
public Object getItem(int i)
{
return data.get(i); //To change body of implemented methods use File | Settings | File Templates.
}
public long getItemId(int i)
{
return i;
}
public static class ViewHolder
{
public TextView textView;
}
public View getView(final int i, View view, ViewGroup viewGroup)
{
View row = view;
final ViewHolder holder;
if(view==null)
{
row = inflater.inflate(R.layout.sms_inbox, viewGroup, false);
holder = new ViewHolder();
holder.textView = (TextView)row.findViewById(R.id.row);
row.setTag(holder);
}
else
{
holder = (ViewHolder)row.getTag();
}
holder.textView.setText(data.get(i));
return row;
}
}
在我的課堂我試圖加載與這兩個選項(自定義適配器以及ArrayAdapter)名單,但在這兩種情況下我的應用程序加載非常緩慢。如何加載速度更快?我可能更喜歡我的自定義適配器的解決方案,因爲將來我可能需要添加一些東西來添加我的佈局,如照片和其他東西。
謝謝。請幫忙!!
在AsyncTask中加載數據 – pawelzieba 2011-05-26 09:26:11