我是android的新手我希望获取联系人并在列表视图中显示。这是我在asynctask中获取联系人的代码。请帮助我们在获取每个联系人后更新列表视图。
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);
}
答案 0 :(得分:6)
如何使用列表视图和适配器非常合适。
始终在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();
}
注意:在这种情况下,我实际上建议您保留适配器,listView和基础数据外部 AsyncTask的引用。您仍然可以使用这些引用,并且您还可以在需要时在外部类中使用它们(这很可能)
答案 1 :(得分:1)
将它放入onPostExecute(),就像这样
@Override
protected void onPostExecute(String... values) {
super.onPostExecute(result);
list=(ListView) findViewById(R.id.lvDisplay);
ArrayAdapter<String> adp=new ArrayAdapter<String>
(getBaseContext(),R.layout.list,R.id.label,li);
list.setAdapter(adp);
}
答案 2 :(得分:1)
更新:艾哈迈德修正了他的回答...... https://stackoverflow.com/a/15381932/1659588
<击> 根据Ahmed Aeon Axan的答案,这里有一个固定版本
ListView list;
ArrayAdapter<string> adapter;
@Override
protected void onPreExecute() {
list = (ListView) findViewById(R.id.lvDisplay);
ArrayAdapter<String> adapter = new ArrayAdapter<String>
(getBaseContext(),R.layout.list,R.id.label,li);
list.setAdapter(adp);
}
// doInBackground() ...
@Override
protected void onProgressUpdate(String... values) {
adapter.add(values[0]);
adapter.notifyDataSetChanged();
}
击> <击> 撞击>