我从手机databese获取数据。但是光标总是得到null
。我也有权限阅读联系人。有人能帮助我吗?
//for get number and name from contacts
c = getContentResolver().query(uri, new String[]{
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.TYPE },
null, null, null);
我的所有代码都在这里:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
Uri uri = data.getData();
if (uri != null) {
Cursor c = null;
try {
c = getContentResolver().query(uri, new String[]{
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.TYPE },
null, null, null);
if (c != null && c.moveToFirst()) {
String number = c.getString(0);
int type = c.getInt(1);
Toast.makeText(this, type + ": " + number, Toast.LENGTH_LONG).show();
}
} finally {
if (c != null) {
c.close();
}
}
}
来自logcat的Exception
:
12-16 12:59:33.962: E/AndroidRuntime(20650): Caused by: java.lang.IllegalArgumentException: Invalid column data1
12-16 12:59:33.962: E/AndroidRuntime(20650): at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:167)
答案 0 :(得分:1)
我使用以下代码获取phoneNumber
,使用:
Cursor contact = getContentResolver().query(
ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if (contact.getCount() > 0) {
contact.moveToFirst();
do
{
String contactId = contact.getString(contact
.getColumnIndex(ContactsContract.Contacts._ID));
log.d("contactId is", contactId);
Cursor pCur = getContentResolver()
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?",
new String[] { contactId }, null);
if (pCur.getCount() > 0){
pCur.moveToFirst();
do {
String number = pCur
.getString(pCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
log.d("number is",number);
} while (pCur.moveToNext());
}
}
while(contact.moveToNext());
}