public class RetrieveDataActivity extends Activity { private String[] columns={ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.CONTACT_ID}; public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView tv=(TextView) findViewById(R.id.result); tv.setText(getQueryData()); } private String getQueryData(){ StringBuilder sb=new StringBuilder(); ContentResolver resolver=getContentResolver(); Cursor cursor=resolver.query(ContactsContract.Contacts.CONTENT_URI,null,null,null,null); while (cursor.moveToNext()){ int idIndex=cursor.getColumnIndex(columns[0]); int displayNameIndex= cursor.getColumnIndex(columns[1]); int id=cursor.getInt(idIndex); String displayName=cursor.getString(displayNameIndex); Cursor phone= resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,columns[3]+"="+id,null,null); while(phone.moveToNext()){ int phoneNumberIndex=phone.getColumnIndex(columns[2]); String phoneNumber=phone.getString(phoneNumberIndex); sb.append(displayName+":"+phoneNumber+"\n"); cursor.close(); } }
时间: 2024-02-11 12:09:01 浏览: 136
android-SQLITE.rar_android_android sqlite_sqlite
根据你提供的代码,我发现在第二个while循环中,没有关闭`phone`游标。这可能是导致无法查询出通讯录内容的原因之一。
另外,`cursor.close()`应该在第一个while循环的末尾处调用,而不是在第二个while循环的末尾处调用。因为第二个while循环是在第一个while循环的内部执行的,如果在第二个while循环中关闭了游标,那么第一个while循环将无法正常执行。
此外,我还注意到在查询电话号码时,`columns[3]`应该是`ContactsContract.CommonDataKinds.Phone.CONTACT_ID`,而不是`ContactsContract.CommonDataKinds.Phone.NUMBER`,因为`columns[3]`对应的是通讯录ID,而不是电话号码。
修改后的代码如下:
```
public class RetrieveDataActivity extends Activity {
private String[] columns = {ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.CONTACT_ID};
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv = (TextView) findViewById(R.id.result);
tv.setText(getQueryData());
}
private String getQueryData() {
StringBuilder sb = new StringBuilder();
ContentResolver resolver = getContentResolver();
Cursor cursor = resolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
while (cursor.moveToNext()) {
int idIndex = cursor.getColumnIndex(columns[0]);
int displayNameIndex = cursor.getColumnIndex(columns[1]);
int id = cursor.getInt(idIndex);
String displayName = cursor.getString(displayNameIndex);
Cursor phone = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, columns[3] + "=" + id, null, null);
while (phone.moveToNext()) {
int phoneNumberIndex = phone.getColumnIndex(columns[2]);
String phoneNumber = phone.getString(phoneNumberIndex);
sb.append(displayName + ":" + phoneNumber + "\n");
}
phone.close();
}
cursor.close();
return sb.toString();
}
}
```
希望这可以帮到你。
阅读全文