Search code examples
androidmysqliandroid-contentprovider

How can I get every row from a Content Provider?


How can I get every row from a content provider ? I tried to do this using Cursor c = getContentResolver().query(uri, null, null, null, null) and then

String s;
if (c != null && c.moveToFirst()) 

        while (c.moveToNext()) 
                 s = c.getString(c.getColumnIndexOrThrow("string"));

c.close();

but it didn't work.Instead of taking all the rows, it was taking only the last one, repeatedly, as many times as the rows-1 of my db.


Solution

  • You are getting "rows-1" because your use of moveToFirst() followed by moveToNext() as the loop control causes you to skip the first row.

    If you are seeing all rows of the DB with the same value for column "string", there is either a problem with the code that shows you "s" (which you didn't post) or your DB contains the same value for every row, or you have not implemented query() correctly in your ContentProvider.

    You can also use Cursor.getCount() to get the number of rows in the cursor.

    This code works for me when run against a content provider backed by a DB:

            Cursor c = getContentResolver().query(uri, null, null, null, null);
            if (c != null) {
                while (c.moveToNext()) {
                    String s = c.getString(c.getColumnIndexOrThrow("name"));
                    Log.i("Demo", s);
                }
                c.close();
            }