How to properly insert values into the SQLite database using ContentProvider's insert() method through a CursorLoader?

后端 未结 2 850
清酒与你
清酒与你 2020-12-14 04:47

I was reading the doc, but I am still not too sure. Its says to use getContentResolver(), but then that really isn\'t using CursorLoader. So is there a way to d

2条回答
  •  盖世英雄少女心
    2020-12-14 05:20

    Convert Cursor to ContentValues for easy database insertion.

    Its says to use getContentResolver(), but then that really isn't using CursorLoader

    Besides what Alex said, there's nothing preventing you from iterating through the Cursor returned, putting them into ContentValues and then inserting that (say, to a different DB).

    Just an example from the top of my head (a simple Cursor of two String columns):

    @Override
    public void onLoadFinished(Loader loader, Cursor cursor) {
        if (cursor.moveToFirst()) {
            ArrayList values = new ArrayList();
            do {
                ContentValues row = new ContentValues();
                DatabaseUtils.cursorStringToContentValues(cursor, fieldFirstName, row);
                DatabaseUtils.cursorStringToContentValues(cursor, fieldLastName, row);
                values.add(row);
            } while (cursor.moveToNext());
            ContentValues[] cv = new ContentValues[values.size()];
            values.toArray(cv);
            getContentResolver().bulkInsert(CONTENT_NAMES, cv);
        }
    }
    

    There are probably more efficient ways to do that (and definitely some integrity checks), but that was my first thought...

提交回复
热议问题