我有以下代码用于从本地数据库中获取联系人详细信息并将名称和号码分配给自定义 ListView
public class Rabtaye extends Activity {
ListView msgList;
ArrayList<MessageDetails> details;
AdapterView.AdapterContextMenuInfo info;
Cursor cursor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_main);
msgList = (ListView) findViewById(R.id.MessageList);
details = new ArrayList<MessageDetails>();
MessageDetails Detail = new MessageDetails();
// String info[] = { Phone.DISPLAY_NAME, Phone.NUMBER, Phone._ID };
String number = null;
String name = null;
try {
Cursor cursor = getContentResolver().query(
ContactsContract.Contacts.CONTENT_URI, null, null, null,
null);
while (cursor.moveToNext()) {
String contactId = cursor.getString(cursor
.getColumnIndex(ContactsContract.Contacts._ID));
String hasPhone = cursor
.getString(cursor
.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (hasPhone.equals("1")) {
// You know it has a number so now query it like this
Cursor phones = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = " + contactId, null, null);
while (phones.moveToNext()) {
number = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
name = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
System.out.println(number);
}
Detail.setName(name);
Detail.setNumber(number);
details.add(Detail);
msgList.setAdapter(new CustomAdapter(details, this));
phones.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
// Detail.setName(name);
// Detail.setNumber(number);
// details.add(Detail);
msgList.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
TextView s = (TextView) arg1.findViewById(R.id.name);
String abc = s.getText().toString();
Toast.makeText(Rabtaye.this, abc, Toast.LENGTH_LONG).show();
}
});
}
}
CustomAdapter 被传递给 ListAdapter。我也尝试在 while 循环中添加名称和编号,但每次只有一个名称和编号填充到 ListView 中。我对此有点困惑。请帮忙!