Rishi
Rishi

Reputation: 3549

Issues with a MatrixCursor

I have to create a ListView with multiple rows for the same contact if contact has multiple numbers. So a contact having 3 numbers will show as 3 separate rows in the ListView. For that I have created a MatrixCursor for adding separate rows and then adding this cursor in my ListView.

    private static final String[] arr = { "_id", "name", "type_int", "value" };
    final String[] projection = new String[] { Phone.NUMBER, Phone.TYPE, };
    add_cursor = new MatrixCursor(arr);
    String[] values = { "", "", "", "" };

    Cursor cursor = argcontext.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, buffer == null ? null : buffer.toString(), args, ContactsContract.Contacts.DISPLAY_NAME + " ASC ");

    if (cursor != null && cursor.moveToFirst()) {
        int i = 0;
        do {
            String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            cursor.getCount());
            Cursor phone = argcontext.getContentResolver().query(Phone.CONTENT_URI, projection, Data.CONTACT_ID + "=?", new String[] { contactId }, null);
            if (phone != null && phone.moveToFirst()) {
                do {
                    number = phone.getString(phone.getColumnIndex(Phone.NUMBER));
                    final int type = phone.getInt(phone.getColumnIndex(Phone.TYPE));
                    values[0] = String.valueOf(i);
                    values[1] = String.valueOf(name);
                    values[2] = String.valueOf(type);
                    values[3] = String.valueOf(number);
                    add_cursor.addRow(values);
                    i++;
                } while (phone.moveToNext());
                phone.close();
            }
        }
    }

It's working perfectly but my issue is when data has changed in the background I need to call this code again, but for that first I need to clear this cursor values or remove all the rows in it and then keep on adding new rows and I don't know how to do it. There is no:

cursor.removeRow()

function so if contacts data changed I have to again call this function and if I keep on creating:

new MatrixCursor(); 

for every requery then it creates a large memory footprint for the application. This causes the application to crash, say if there are 3000 contacts then this cursor needs a lot of memory which causes a crash for the application. Is there any other way to show this kind of list?

Upvotes: 3

Views: 1993

Answers (1)

Reaz Murshed
Reaz Murshed

Reputation: 24251

From documentaion, mCursor.close(); Closes the Cursor, releasing all of its resources and making it completely invalid. You've to reallocate the memory, using new to use it again. That worked for me.

Upvotes: 0

Related Questions