I have an application which shows recent contacts of phone. so i used the below code to fetch recent contacts but when i tried to run it gives me following error.
java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
Here is my recent contacts fetching code:
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);
}
}