我有一个应用程序,显示最近的电话联系人。 所以我使用下面的代码来获取最近的联系人,但是当我试图运行它时,我发现了以下错误。
java.lang.IllegalStateException:无法从中读取第0行,第1行 CursorWindow。确保之前正确初始化了Cursor 从中访问数据。
以下是我最近的联系人提取代码:
ContentResolver cr = getActivity().getContentResolver();
String[] projection = new String[] {ContactsContract.Contacts._ID}; // you can add more fields you need here
int oneDay = ( 1000 *3600 * 24);
long last24h = (System.currentTimeMillis() - oneDay);
Cursor cur=cr.query(CallLog.Calls.CONTENT_URI,null,null,null,null);
String phone = null;
String emailContact = null;
String image_uri;
Bitmap bitmap;
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));
image_uri = cur
.getString(cur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));
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())
{
phone = pCur
.getString(pCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
// contactid=pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
/* phonenumber.add(pCur
.getString(pCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));`*/
}
pCur.close();
Cursor emailCur = cr.query
(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID
+ " = ?", new String[]{id}, null);
while (emailCur.moveToNext())
{
emailContact = emailCur
.getString(emailCur
.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
if(TextUtils.isEmpty(emailContact)||emailContact.equalsIgnoreCase(null)||emailContact.equalsIgnoreCase(""))
{
emailContact="";
}
else
{
}
/* emailType = emailCur
.getString(emailCur
.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));*/
}
emailCur.close();
}
if (image_uri != null)
{
System.out.println(Uri.parse(image_uri));
try
{
bitmap = MediaStore.Images.Media
.getBitmap(getActivity().getContentResolver(),
Uri.parse(image_uri));
System.out.println(bitmap);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
recent_list.add(new Contacts(name, phone, image_uri,emailContact));
emailContact="";
phone="";
}
cur.close();
}
else
{
noContact.setVisibility(View.VISIBLE);
search_layout.setVisibility(View.GONE);
}
}
答案 0 :(得分:0)
您尝试访问光标中未在投影中指定的字段,这是不可能的。
投影需要包含您需要的所有字段。
但是,您无法从“呼叫记录”表中访问“联系人”字段。
就像我最近在这里回答了您的其他问题:How to fetch recent and favourite contacts in android?