Skip to content

Instantly share code, notes, and snippets.

@truedem
Last active July 31, 2016 16:35
Show Gist options
  • Save truedem/97f6f8005ea90232fa375fb1e39820a7 to your computer and use it in GitHub Desktop.
Save truedem/97f6f8005ea90232fa375fb1e39820a7 to your computer and use it in GitHub Desktop.
Common operations for Realm in Android
// check if Realm db exist
RealmConfiguration config = getConfig();
if (new File(config.getPath()).exists()) {
// exists
} else {
// don't exists
}
// check if Realm is closed
if(realm.isClosed()) {
// Do something
}
// delete classes within Realm:
Realm realm = Realm.getInstance(context);
realm.beginTransaction();
realm.clear(ThisClass.class);
realm.clear(ThatClass.class);
realm.commitTransaction();
realm.close();
// check if there is any data
Realm realm = Realm.getInstance(context);
realm.isEmpty();
// check if data exist - alt
ThisClass thisClass = realm.where(ThisClass.class).equalTo("someID", thisID).findFirst();
if (thisClass != null) {
// Exists
} else {
// Not exist
}
// add or update a note
public void storeItems( String id, String title ,String location) {
realm.beginTransaction();
ItemsRealmClass items = new ItemsRealmClass();
items.setobjectId(id);
items.setLocation(location);
items.setTitle(title);
if (realm.where(ItemsRealmClass.class).equalTo("objectID", id).count() == 0) {
// there are no object with this `Id`
realm.copyToRealmOrUpdate(items);
}
Toast.makeText(context, "Items Stored!", Toast.LENGTH_SHORT).show();
realm.commitTransaction();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment