I tried to implement realm-java with ContentProvider.
Realm with ContentProviderRealm meetup #2
View Slide
About me4 Լ ܟ߂ (@androhi)4 גࣜձࣾZaim (AndroidΞϓϦ୲)4 DroidKaigiͰൃද͠·͢4 JellyBeanͱKitKatͰ࣮ݱ͢ΔϚςϦΞϧσβΠϯ
TriedContentProviderͰΞΫηε͢ΔDBΛɺRealmʹͯ͠Έ·ͨ͠ReasonAndroidͷSyncAdapterΛͬͨࣗಈಉظͷΈͰɺόοΫάϥϯυͰಉظॲཧΛ͢ΔࡍʹContentProviderΛ༻͍Δͱ͍͏ϧʔϧ͕͋ΔͨΊ
Extend ContentProvider1. Queryϝιουͷ࣮ (+ ಠࣗCursorͷੜ)2. Insertϝιουͷ࣮3. Updateϝιουͷ࣮4. Deleteϝιουͷ࣮5. BulkInsertϝιουͷ࣮
This time1. Queryϝιουͷ࣮ (+ ಠࣗCursorͷੜ)2. Insertϝιουͷ࣮3. Updateϝιουͷ࣮4. Deleteϝιουͷ࣮5. BulkInsertϝιουͷ࣮
1-1. Create cursorstatic final String[] sColumns = new String[] {"_id", "name", "price"};RealmQuery query = mRealm.where(Item.class);RealmResults results = query.findAll();MatrixCursor matrixCursor = new MatrixCursor(sColumns);for (Item item : results) {Object[] rowData =new Object[]{item.get_id(), item.getName(), item.getPrice()};matrixCursor.addRow(rowData);}
1-2. Implement query@Overridepublic Cursor query(Uri uri, String[] projection, String selection,String[] selectionArgs, String sortOrder) {...RealmQuery query = mRealm.where(Item.class);RealmResults results = query.findAll();MatrixCursor matrixCursor = new MatrixCursor(sColumns);for (Item item : results) {Object[] rowData =new Object[]{item.get_id(), item.getName(), item.getPrice()};matrixCursor.addRow(rowData);}return matrixCursor;}
2. Implement insert@Overridepublic Uri insert(Uri uri, ContentValues contentValues) {...mRealm.beginTransaction();Item item = mRealm.createObject(Item.class);item.set_id(++count);item.setName(contentValues.getAsString(sColumns[1]));item.setPrice(contentValues.getAsLong(sColumns[2]));mRealm.commitTransaction();return Uri.withAppendedPath(uri, String.valueOf(item.get_id()));}
5. Implement bulkInsert@Overridepublic int bulkInsert(Uri uri, ContentValues[] values) {...mRealm.beginTransaction();try {for (ContentValues value : values) {Item item = mRealm.createObject(Item.class);item.set_id(value.getAsLong(sColumns[0]));item.setName(value.getAsString(sColumns[1]));item.setPrice(value.getAsLong(sColumns[2]));}} finally {mRealm.commitTransaction();}return values.length;}
compare with SQLiteQuery/Insert -> 10,000݅Xperia Z1f (Android 4.4.2)
SQLite withContentProvider4 Insertɺ͔ͳΓ͍4 Query͕ૣ͍
Realm withContentProvider4 Insert͕ɺͦΜͳʹ͘ͳ͍4 Query͕SQLiteʹൺΔͱ͍ʢCursorੜͷӨڹʣ4 BulkInsertޓ֯ʁ
Summary4 ύϑΥʔϚϯεམͪΔʢʁʣ͚ͲContentProviderͰ͑Δ4 Queryϝιουվળͷ༨͕͋Γͦ͏4 ࣗಈಉظ͚ͩContentProviderܦ༝ʹ͠ɺΞϓϦຊମRealmΛͦͷ··͏ͷ͕ྑͦ͞͏