somethingRandom somethingRandom - 4 months ago 37
Android Question

Limit number of items in SimpleCursorAdapter when using custom content provider

I'm trying to get used to using custom content providers. I've successfully managed to write a very simple application that on the press of a button adds a String to an sqlite database using a custom content provider. These database entries are then displayed in a ListView in the same activity.

I am trying to limit the number of items in the ListView to 5, but due to my lack in experience, I have no idea how to proceed.

This is what I'm using to fill the ListView

private void fillData() {

String[] from = new String[]{commentsTable.COLUMN_COMMENT, commentsTable.COLUMN_ID};
int[] to = new int[]{,};

getLoaderManager().initLoader(0, null, this);
adapter = new SimpleCursorAdapter(this, android.R.layout.two_line_list_item, null, from, to, 0);


I followed this tutorial to write an app similar to the app in the tutorial.

I have tried using a
instead of
but I'm getting a
error because of the method


After some research, I have managed to solve this and thought I would post an answer for anyone who stumbles across this question.

In my customContentProvider class I added the variables:

public static final String QUERY_PARAMETER_LIMIT = "limit";
public static final String QUERY_PARAMETER_OFFSET = "offset";

and then edited the query method to include:

public Cursor query(Uri uri, ...) {
    String limit = uri.getQueryParameter(QUERY_PARAMETER_LIMIT);
    String offset = uri.getQueryParameter(QUERY_PARAMETER_OFFSET);

    SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();

    // ...

    Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder, limitString);


    return c;

Then when getting a cursor simply use the Uri

Uri CONTENT_URI = customContentProvider.CONTENT_URI.buildUpon()