-2

How can I get all records without using a loop.Loop is not a good way to get 1000+ records.

For example:

public List<Contact> getAllContacts() {
    List<Contact> contactList = new ArrayList<Contact>();
    String selectQuery = "SELECT  * FROM " + TABLE_CONTACTS;

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);
    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 contactList;

But this is not a best way to do so.Think you have 5000+ record.How much time does it take to complete this task!

How do you think ?

Regards,

Mobin Ranjbar
  • 1,320
  • 1
  • 14
  • 24
  • use CursorAdapter for your ListView (instead ArrayAdapter) and do not load data to POJO ... than list should be quicker(a lot) – Selvin Mar 15 '13 at 09:08

3 Answers3

1
Select * from table;

thats all...

in Android:

Cursor cursor = database.query(SQLiteHelper.TABLE_YOURTABLE,
    allColumns, null, null, null, null, null);

I think a clearer way to iterate over the result:

cursor.moveToFirst();
while (!cursor.isAfterLast()) {
  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);
}
nano_nano
  • 12,351
  • 8
  • 55
  • 83
0

The only way to avoid loading thousands of records is to load less. (You won't be able to fit thousands of entries onto the screen anyway.)

You probably want to implement some form of lazy loading for your list.

Community
  • 1
  • 1
CL.
  • 173,858
  • 17
  • 217
  • 259
0

The Cursor itself represents the "list" of items. That's why I have asked you what do you need to do with the data after retrieving from database...

If you only need to splash it on a ListView, then use CursorAdapter. And even if you need to parse the "list" and send some items on the network or something other than displaying in a ListView, you still don't need an actual list. Just extract the items you need directly from the Cursor and send them away.

With the drawback of repeating myself, I should point out again: it really depends on what you want to do with the data.

Bogdan Zurac
  • 6,348
  • 11
  • 48
  • 96