我想获取Android联系人详细信息,例如:
[
{
"id" : "1",
"name" : "name1",
"mobile":"1234567891"
},
{
"id" : "2",
"name" : "name2",
"mobile":"2222222222"
}
]
所以我有代码这个代码
Contact.java
public class Contact {
private String id;
private String name;
private String mobile;
//setters & getters
//constructors
}
AsyncTask
执行后台任务然后显示列表
private class MyAsync extends AsyncTask<String, Void, String> {
@SuppressWarnings("unused")
@Override
protected String doInBackground(String... params) {
String serverResponse = "";
try {
serverResponse =contactDetail.fetchContacts1();
Contact contact1= new Contact();
contact1 = new Gson().fromJson(serverResponse, Contact.class);
Log.i("serverResponse", serverResponse);
} catch (Exception e) {
e.printStackTrace();
}
return serverResponse;
}
@Override
protected void onPostExecute(String serverResponse) {
outputText.setText(serverResponse);
}
}
这是获取联系方式的方法:
@SuppressWarnings({ "unchecked", "rawtypes" })
public String fetchContacts1() {
Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(CONTENT_URI, null,null, null, null);
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex( HAS_PHONE_NUMBER )));
if (hasPhoneNumber > 0) {
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones.moveToNext()) {
id = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.RAW_CONTACT_ID));
name1 = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
mobile1 = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contact = new Contact(id,name1,mobile1);
dataToSend = new HashMap<>();
dataToSend.put("contact", new Gson().toJson(contact));
l1 = new LinkedList();
l1.add(dataToSend);
Log.i("Preeit", l1.toString());
}
phones.close();
}
}
}
return dataToSend.toString();
}
执行此代码后,在日志中我将获得所有联系人,如下所示:
[{
"id" : "1",
"name" : "name1",
"mobile":"1234567891"
}]
...
.....
[{
"id" : "2",
"name" : "name2",
"mobile":"2222222222"
}]
但是,在显示屏上我只收到一个号码细节,而不是所有的电话号码细节。
[{ "id" : "1","name" : "name1", "mobile":"1234567891" } ]
我的代码有什么问题?