Skip to content

Instantly share code, notes, and snippets.

@cmelchior
Created March 17, 2017 10:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cmelchior/34224e6ecf8dfb6e08fa47b43731b536 to your computer and use it in GitHub Desktop.
Save cmelchior/34224e6ecf8dfb6e08fa47b43731b536 to your computer and use it in GitHub Desktop.
Load new Realm file from assets when a migration is required
public Realm loadAssetFileOnMigration() {
// TODO Don't re-create this every time
RealmConfiguration config = new RealmConfiguration.Builder()
.schemaVersion(2) // Bumping the schema because new app
.build();
Realm realm;
try {
realm = Realm.getInstance(config);
} catch (RealmMigrationNeededException e) {
// A migration was required. Delete the old file and load a
// new from the asset folder.
Realm.deleteRealm(config);
copyAssetFile(getContext(), "assetFileName", config);
realm = Realm.getInstance(config); // This should now succeed
}
return realm;
}
// Modified copy of https://github.com/realm/realm-java/blob/master/realm/realm-library/src/main/java/io/realm/RealmCache.java#L340
private void copyAssetFile(Context context, String assetFileName, RealmConfiguration configuration) {
IOException exceptionWhenClose = null;
File realmFile = new File(configuration.getRealmDirectory(), configuration.getRealmFileName());
InputStream inputStream = null;
FileOutputStream outputStream = null;
try {
inputStream = context.getAssets().open(assetFileName);
if (inputStream == null) {
throw new IOException("Could not open asset file: " + assetFileName);
}
outputStream = new FileOutputStream(realmFile);
byte[] buf = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buf)) > -1) {
outputStream.write(buf, 0, bytesRead);
}
} catch (IOException e) {
// Handle IO exceptions somehow
throw new RuntimeException(e);
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
exceptionWhenClose = e;
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
// Ignores this one if there was an exception when close inputStream.
if (exceptionWhenClose == null) {
exceptionWhenClose = e;
}
}
}
}
// No other exception has been thrown, only the exception when close. So, throw it.
if (exceptionWhenClose != null) {
throw new RuntimeException(exceptionWhenClose);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment