How to add an item to SimpleCursorAdapter?

只谈情不闲聊 提交于 2019-12-06 07:25:21

You could create an object out of your id and title and build a list of these objects with the cursor. Then insert your artificial entry at the top top of that list.

Then when you construct your Adapter pass in this list.

Alternatively you could put a dummy value into your database, although that would be weird and maybe not possible depending on your query and data. The ArrayAdapter is much more sensible

How to Do This With SimpleCursorAdapter

This method:

  • Is Efficient
  • Works with standard CursorLoader and SimpleCursorAdapter idioms
  • Great with ContentProvider data

I create the item i want to insert into the cursor as a static MatrixCursor

private static final MatrixCursor PLATFORM_HEADER_CURSOR = new MatrixCursor(
        //These are the names of the columns in my other cursor
        new String[]{ 
                DataContract.ReflashPackage._ID,
                DataContract.ReflashPackage.COLUMN_PLATFORM
        });
static {
    PLATFORM_HEADER_CURSOR.addRow(new String[]{
            "0",
            "Select a Platform")
    });
}

Here is my implementation of onLoadFinished which merges the cursor and passes it to the adapter.

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    switch (loader.getId()) {
        case PLATFORM_CURSOR_LOADER_ID:
            Cursor mergedCursor = addPlatformHeaderToCursor(data);
            mPlatformAdapter.swapCursor(mergedCursor);
            break;
    }
}

@NonNull
private static Cursor addPlatformHeaderToCursor(Cursor platforms) {
    Cursor[] cursorToMerge = new Cursor[2];
    cursorToMerge[0] = PLATFORM_HEADER_CURSOR;
    cursorToMerge[1] = platforms;
    return new MergeCursor(cursorToMerge);
}

One technique that I use often is I will define an object (such as EntryObject) that has the variables I am going to need from the cursor to display. Once I have this I can iterate through the cursor and place the information into those EntryObjects and place them in an ArrayList or an array.

Then you can build a customer ArrayAdapter that will work with your new object to pull as much data as you need and display it how you want to.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!