Sup*_*eet 0 android android-listview android-asynctask
我是android的新手,我想获取联系人并在列表视图中显示.这是我在asynctask.please中获取联系人的代码,帮助我们在获取每个联系人后更新列表视图.
protected Void doInBackground(Void... params) {
ContentResolver cr = ReadContactsActivity.this.getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
String phone = pCur.getString(
pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
//li.add("Name:"+name+",Number:"+phone);
publishProgress("Name:"+name+",Number:"+phone);
}
pCur.close();
}
}
}
return null;
}
// A callback method executed on UI thread, invoked by the publishProgress()
// from doInBackground() method
@Override
protected void onProgressUpdate(String... values) {
list=(ListView) findViewById(R.id.lvDisplay);
ArrayAdapter<String> adp=new ArrayAdapter<String>
(getBaseContext(),R.layout.list,R.id.label,li);
list.setAdapter(adp);
}
Run Code Online (Sandbox Code Playgroud)
您如何使用列表视图和适配器非常合适.
总是做你的一次设置(获取listview的参考,初始化适配器等..)in OnPreExecute
ListView list;
List<String> names;
ArrayAdapter<string> adapter;
@Override
protected void onPreExecute() {
names = new ArrayList<String>();
list = (ListView) findViewById(R.id.lvDisplay);
ArrayAdapter<String> adapter = new ArrayAdapter<String>
(getBaseContext(),
R.layout.list,
R.id.label,
names);
list.setAdapter(adp);
}
// doInBackground() ...
@Override
protected void onProgressUpdate(String... values) {
names.add(values[0])
adapter.notifyDataSetChanged();
}
Run Code Online (Sandbox Code Playgroud)注意:在这种情况下,我实际上建议您保留适配器,listView和AsyncTask 之外的基础数据的引用.您仍然可以使用这些引用,并且还可以在需要时在外部类中使用它们(很可能)
| 归档时间: |
|
| 查看次数: |
2329 次 |
| 最近记录: |