1

I am trying to populate a ListView in a separate class with data taken from a SQLite database held in another class. What would be the easiest way to do so?

Thanks

jcrowson
  • 4,290
  • 12
  • 54
  • 77

1 Answers1

3

Return a Cursor eg: getList() from your other class to the current ListView class.

objItem = new Contacts(this);

this.cur = objItem.getList();
this.startManagingCursor(this.cur);

ListAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, cur,
        new String[] { ContactsContract.Contacts.DISPLAY_NAME}, new int[] { android.R.id.text1});

setListAdapter(adapter);

in class you have a method returning Cursor

public Cursor getList() {
        // Get the base URI for the People table in the Contacts content
        // provider.
        Uri contacts = ContactsContract.Contacts.CONTENT_URI;
        // Make the query.
        ContentResolver cr = ctx.getContentResolver();
        // Form an array specifying which columns to return.
        String[] projection = new String[] { ContactsContract.Contacts._ID,
                ContactsContract.Contacts.DISPLAY_NAME };

        Cursor managedCursor = cr.query(contacts, projection, null, null,
                ContactsContract.Contacts.DISPLAY_NAME
                        + " COLLATE LOCALIZED ASC");
        return managedCursor;
    }
Pentium10
  • 204,586
  • 122
  • 423
  • 502
  • Thanks again Pentium10, would I be able to use this code even if I have not implemented a Content Provider? – jcrowson Mar 25 '10 at 13:33
  • I've just copy pasted this. You use a `Cursor cur=db.query(...)` method and return the Cursor variable. – Pentium10 Mar 25 '10 at 13:49
  • @Pentium10 can you solve this problem i need help http://stackoverflow.com/questions/38435531/android-setting-sqlite-database-values-in-an-listview – Addi.Star Jul 18 '16 at 12:20