get deleted contacts returns null sometimes - android

I need to retrieve deleted contacts in android. Below is my code
String WHERE_MODIFIED = "( "+ ContactsContract.RawContacts.DELETED + "= 1 )";
Cursor c = getContentResolver().query(ContactsContract.RawContacts.CONTENT_URI,
null,
WHERE_MODIFIED,
null,
null);
if (c.getCount() > 0) {
c.moveToFirst();
do{
String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
Log.e(TAG,name);
}while (c.moveToNext());
}else {
Log.e(TAG,"cursor = null");
}
It works when I delete contact and fetch using above code but after sometime of deletion it returns null. How do I fix this?

Cursor cursor = createDeletedCursor(contactLastUpdatedTime);
private Cursor createDeletedCursor(long lastupdatedTime) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
return resolver.query(
ContactsContract.DeletedContacts.CONTENT_URI,
DELETED_PROJECTION,
String.format("%s >= %d", ContactsContract.DeletedContacts.CONTACT_DELETED_TIMESTAMP, lastupdatedTime),
null,
ContactsContract.DeletedContacts.CONTACT_ID
);
}

Related

Can't read phone contacts

I got this Exception
12-01 12:28:42.552: E/AndroidRuntime(25581): Caused by: java.lang.IllegalStateException: Couldn't read row 1, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
When I want to use below code to read phone(sim) contacts
Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
if(cursor.moveToFirst()&&cursor.getCount()>0&&cursor!=null){
while (cursor.moveToNext()) {
// String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phone = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
User user=new User();
user.setFirstname(name);
user.setPhoneNumber(phone);
listdata.add(user);
cla_contact.notifyDataSetChanged();
}
cursor.close();
}
What's [roblem and how to solve?
Replace your first line of code with the following it is working for me.
Cursor cursor =
getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null, null, null, null);
You better change the order of conditions in the 'if' loop to avoid null pointer exceptions (if in case cursor is null).
if(cursor!=null && cursor.getCount()>0 && cursor.moveToFirst()){
Please accept the answer if it works for you. Thank you.
Do like this
if (cursor.moveToFirst()) {
while (cursor.moveToNext()) {
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name= cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
System.out.println(contactID + " " + name);
}
}
it will move the cursor to the first row before reading the data.
Makr as right if it works for you. :)
Try this
Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
if(cursor.moveToFirst()){
while (cursor.moveToNext()) {
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
System.out.println(contactID + " " + name);
}
cursor.close();
}
and also make sure you have this in manifest
<uses-permission android:name="android.permission.READ_CONTACTS" />
try like this,
Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
if(cursor != null && cursor.getCount() > 0){
if (cursor.moveToFirst()) {
do {
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
System.out.println(contactID + " " + name);
} while (cursor.moveToNext());
}
cursor.close();

Android SQL cursor is NULL

In my sql.query, there are times when the cursoe should return a null value. For example in the below code, the cursor is seeking a username. If the User has a username, then the cursor will return it. If not then I assume it is null. My problem is that when a cursor does find a null value, then I get a crash with an "out of bounds" error. Basically means the cursor did not find anything.
public static String getUserName() {
int rowIncrement = 1;
Log.d(DATABASE, "Getting Username");
String[] usercolumns = new String[] { KEY_ROWID, KEY_NAME, KEY_PASSWORD };
Cursor c = myDatabase.query(USER_TABLE, usercolumns, KEY_ROWID + "="
+ rowIncrement, null, null, null, null);
if (c != null) {
c.moveToFirst();
String lUserName = c.getString(1);
Log.d("DATABASE", "Username = " + lUserName);
return lUserName;
}
return null;
}
What is wrong with this code that would cause a crash if the cursor does not find anything?
It seems because of c.moveToFirst() returns boolean. So you should change your code like this.
if (c != null && c.moveToFirst()) {
String lUserName = c.getString(1);
Log.d("DATABASE", "Username = " + lUserName);
return lUserName;
}
You can check this here http://developer.android.com/reference/android/database/Cursor.html

Contact photo not updating for a select few

I was recently playing around with some code that goes through my contacts and creates an identicon for any contact that does not have a photo set. For the most part this ended up working quite well but for some reason I have a handful of contacts that will not update. Log output says it is creating the photo. The update() returns 1 indicating 1 row was updated and stepping through the code for a contact that never seems to show the new photo looks good.
The fact that only a select few are not updating is what is really bugging me and I'm guessing there must be something I am doing wrong or missing here.
private void processContacts() {
Cursor cursor = getContacts();
Log.d(TAG, "Processing " + cursor.getCount() + " contacts");
while(cursor.moveToNext()) {
final long contactId = cursor.getLong(0);
final String name = cursor.getString(1);
if (!TextUtils.isEmpty(name)) {
final Uri contactUri = ContentUris.withAppendedId(
ContactsContract.Contacts.CONTENT_URI,
contactId);
if(ContactsContract.Contacts.openContactPhotoInputStream(getContentResolver(),
contactUri, true) == null) {
Log.d(TAG, String.format("Creating identicon for %s", name));
generateIdenticon(contactId, name);
} else {
Log.i(TAG, String.format("%s already has a contact photo", name));
}
}
}
cursor.close();
}
private Cursor getContacts() {
Uri uri = ContactsContract.Contacts.CONTENT_URI;
String[] projection = new String[] { ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME };
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME
+ " COLLATE LOCALIZED ASC";
return getContentResolver().query(uri, projection, null, null, sortOrder);
}
private void generateIdenticon(long contactId, String name) {
if (!TextUtils.isEmpty(name)) {
updateNotification(getString(R.string.identicons_creation_service_running_title),
String.format(getString(R.string.identicons_creation_service_contact_summary),
name));
final byte[] hash = Identicon.generateHash(name);
final byte[] identicon = Identicon.generateIdenticonByteArray(hash);
if (identicon == null) {
Log.e(TAG, "generateIdenticon() - identicon for " + name + " is null!");
} else {
if (!setContactPhoto(getContentResolver(), identicon, contactId)) {
Log.e(TAG, "Unable to save identicon for " + name);
}
}
}
}
private boolean setContactPhoto(ContentResolver resolver, byte[] bytes, long personId) {
ContentValues values = new ContentValues();
int photoRow = -1;
String where = ContactsContract.Data.RAW_CONTACT_ID + " == " +
String.valueOf(personId) + " AND " + ContactsContract.Data.MIMETYPE + "=='" +
ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE + "'";
Cursor cursor = resolver.query(
ContactsContract.Data.CONTENT_URI,
null,
where,
null,
null);
int idIdx = cursor.getColumnIndexOrThrow(ContactsContract.Data._ID);
if(cursor.moveToFirst()){
photoRow = cursor.getInt(idIdx);
}
cursor.close();
values.put(ContactsContract.Data.RAW_CONTACT_ID, personId);
values.put(ContactsContract.Data.IS_PRIMARY, 1);
values.put(ContactsContract.Data.IS_SUPER_PRIMARY, 1);
values.put(ContactsContract.CommonDataKinds.Photo.PHOTO, bytes);
values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE);
if (photoRow >= 0) {
final int rowsUpdated = resolver.update(ContactsContract.Data.CONTENT_URI,
values, ContactsContract.Data._ID + "=" + photoRow, null);
return rowsUpdated >= 1;
} else {
final Uri uri = resolver.insert(ContactsContract.Data.CONTENT_URI, values);
return uri != null && !TextUtils.isEmpty(uri.toString());
}
}
All this is being done inside a background service and all my contacts are synced via google. One last thing to note is that these select contacts always return null when I call ContactsContract.Contacts.openContactPhotoInputStream() to see if a photo is available (even after I've attempted to update the photo).
Any help or insight about what may be going on is greatly appreciated.

Display multiple rows in a textview Android

Hello guys I want to display records. However, I don't want to display them in listview but in textview. I have in my to do the new line feed \n to do the trick, but in my program, it just shows the first record.
This is what I've tried so far:
MainActivity.class
Bundle extras = getIntent().getExtras();
if (extras != null) {
dog_name = extras.getString("dog_name");
cursor = dbHelper.fetchbBreedByName(dog_name);
strID = cursor.getString(0);
strDesc = cursor.getString(cursor.getColumnIndexOrThrow("description"));
strDiet = cursor.getString(cursor.getColumnIndexOrThrow("diet"));
strShelter = cursor.getString(cursor.getColumnIndexOrThrow("shelter"));
strHygiene = cursor.getString(cursor.getColumnIndexOrThrow("hygiene"));
strMedication = cursor.getString(cursor.getColumnIndexOrThrow("medication"));
strBreed = cursor.getString(cursor.getColumnIndexOrThrow("breed"));
Log.d("Animal ID", "Animal ID is " + strID + " and breed is " + strBreed);
Log.d("Desc", "Desc " + strDesc);
Description.setText(strDesc);
Diet.setText(strDiet);
Shelter.setText(strShelter);
Hygene.setText(strHygiene);
Medication.setText(strMedication); }
DBHelper.class
public Cursor fetchbBreedByName(CharSequence inputText) throws SQLException {
Cursor mCursor = null;
if (inputText == null || inputText.length () == 0) {
mCursor = myDataBase.query(DB_TABLE, new String[] { KEY_ID, KEY_DESCRIPTION,
KEY_DIET, KEY_SHELTER, KEY_HYGIENE, KEY_MEDICATION, KEY_BREED },
null, null, null, null, null);
}
else {
String qry = "SELECT _id, description, diet, shelter, hygiene, medication, " +
"breed FROM tblAnimalInfo WHERE breed LIKE '%" + inputText + "%';";
mCursor = myDataBase.rawQuery(qry, null);
//mCursor = myDataBase.query(DB_TABLE, new String[] { KEY_ID, KEY_DESCRIPTION,
// KEY_DIET, KEY_SHELTER, KEY_HYGIENE, KEY_MEDICATION, KEY_BREED },
// KEY_BREED + " like '%" + inputText + "%'", null, null, null, null);
}
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
I don't know what's wrong. Please help me figure out what's missing in my code. Thanks in advance.
It seems that you are only loading the first row given by your Cursor. You have to use cursor.moveToNext(); to be able to get the rest of your data. Take a look to the example below:
// Getting All Contacts
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setPhoneNumber(cursor.getString(2));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
You are missing cursor.moveToNext() function to move to the next record, as mentioned earlier. Besides I would like to mention a few other issues in the coding style. You should not call moveToFirst() in the query function itself, use it where you are actually traversing through the records. Also make sure you close the cursor appropriately. So your code should look like:
cursor = dbHelper.fetchbBreedByName(dog_name);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
....
< access the record >
...
} while (cursor.moveToNext());
}
cursor.close(); // very important
}
And remove these lines from fetchbBreedByName()
if (mCursor != null) {
mCursor.moveToFirst();
}

How can i get the album art from MediaStore?

How can I get the album art from MediaStore? I try something like:
String[] projectionImages = new String[]{MediaStore.Audio.Albums.ALBUM_ART, MediaStore.Audio.Albums.ALBUM_KEY};
Cursor c = contentResolver.query(MediaStore.Audio.Albums.INTERNAL_CONTENT_URI, projectionImages, null, null, null);
if(c != null){
c.moveToFirst();
Log.e(TAG, "am gasit " + c.getString(0) + " " + c.getString(1));
}
else{
Log.e(TAG, "No image");
}
but is not working.. I retrive just null for every entry!
Thank you!
Does it iterate over the amount of entries you see in the directory or do the numbers not match up?
The following works for me when searching for images in teh MediaStore
if (cursor.moveToFirst()) {
do {
int col = cursor.getColumnIndex(Images.Media.DESCRIPTION);
String description = cursor.getString(col);
if (new Long(item).toString().equals(description)) {
imageId = cursor.getPosition();
int dataColumn = cursor.getColumnIndex(Images.Media.DATA);
filePath = cursor.getString(dataColumn);
return true;
}
} while (cursor.moveToNext());
Try this one
Cursor cursorAlbum = managedQuery(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
new String[]{MediaStore.Audio.Albums._ID, MediaStore.Audio.Albums.ALBUM_ART},MediaStore.Audio.Albums._ID+ "=" + album_id, null, null);
if(cursorAlbum != null && cursorAlbum.moveToFirst())
{
String uri = cursorAlbum.getString(cursorAlbum.getColumnIndex("album_art"));
cursorAlbum.close();
if(uri != null ) image.setImageURI(Uri.parse(uri));
}

Categories

Resources