Search code examples
androidsqliteandroid-sqliteandroid-contentprovidersimplecursoradapter

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[]{android.R.id.text1, android.R.id.text2};

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

    setListAdapter(adapter);
}

I followed this tutorial http://www.vogella.com/tutorials/AndroidSQLite/article.html#tutorial-sqlite-custom-contentprovider-and-loader to write an app similar to the app in the tutorial.

I have tried using a Cursor instead of null but I'm getting a java.lang.NullPointerException error because of the method .getWritableDatabase().


Solution

  • 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()
                .appendQueryParameter(customContentProvider.QUERY_PARAMETER_LIMIT,
                        String.valueOf(limit))
                .appendQueryParameter(customContentProvider.QUERY_PARAMETER_OFFSET,
                        String.valueOf(offset))
                .build();
    

    Reference:

    https://stackoverflow.com/a/24055457/6735035