Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Realm with ContentProvider

Realm with ContentProvider

I tried to implement realm-java with ContentProvider.

Takahiro Shimokawa

April 23, 2015
Tweet

More Decks by Takahiro Shimokawa

Other Decks in Programming

Transcript

  1. About me 4 Լ઒ ܟ߂ (@androhi) 4 גࣜձࣾZaim (AndroidΞϓϦ୲౰) 4

    DroidKaigiͰൃද͠·͢ 4 JellyBeanͱKitKatͰ࣮ݱ͢ΔϚςϦΞϧσβΠϯ
  2. 1-1. Create cursor static final String[] sColumns = new String[]

    {"_id", "name", "price"}; RealmQuery<Item> query = mRealm.where(Item.class); RealmResults<Item> 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); }
  3. 1-2. Implement query @Override public Cursor query(Uri uri, String[] projection,

    String selection, String[] selectionArgs, String sortOrder) { ... RealmQuery<Item> query = mRealm.where(Item.class); RealmResults<Item> 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; }
  4. 2. Implement insert @Override public 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. 5. Implement bulkInsert @Override public 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; }