Created
March 21, 2016 14:32
-
-
Save funkyidol/2d03845b66a29c6666c8 to your computer and use it in GitHub Desktop.
RealmHelper class to create a singular place for handling Realm instances
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class RealmHelper { | |
private static RealmConfiguration config; | |
private static Realm realmInstance; | |
public static Realm getWriteInstance(Context context) { | |
if (realmInstance == null || realmInstance.isClosed()) { | |
// TODO: 15/10/15 Update the code to use Realm.isClosed() | |
realmInstance = getInstance(context); | |
} | |
try { | |
realmInstance.beginTransaction(); | |
} catch (IllegalStateException e) { | |
Timber.e(e, "Realm already open for transaction"); | |
e.printStackTrace(); | |
} | |
return realmInstance; | |
} | |
public static void commitTransaction() { | |
if (realmInstance != null) { | |
realmInstance.commitTransaction(); | |
} | |
} | |
public static Realm getReadInstance(Context context) { | |
if (realmInstance == null || realmInstance.isClosed()) { | |
realmInstance = getInstance(context); | |
} | |
return realmInstance; | |
} | |
public static void closeRealm() { | |
if (realmInstance != null && !realmInstance.isClosed() && | |
!realmInstance.isInTransaction()) { | |
realmInstance.close(); | |
} | |
} | |
private static Realm getInstance(Context context) { | |
if (config == null) { | |
config = new RealmConfiguration.Builder(context).deleteRealmIfMigrationNeeded().build(); | |
} | |
return Realm.getInstance(config); | |
} | |
private RealmHelper() { | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment