How for Android to load / read local Realm file? - android

I have a Test.realm file inside the asset folder. But I don't know how to load the Realm file inside an activity. I have tried this
RealmConfiguration config = new RealmConfiguration.Builder(this)
.name("Test.realm").build();
Realm realm = Realm.getInstance(config);
RealmResults<RealmTestClass0> results = realm.where(RealmTestClass0.class)
.findAll();
But it was crashing on setting config line (second line). From the log it says
Caused by: io.realm.exceptions.RealmMigrationNeededException: RealmMigration must be provided
So how is the right way to load Realm file?
Thanks in advance.

Realm.getInstance() is correct method for getting Realm's instance.
It looks that you change some of your Realm objects or add new one. Realm detected it and tells that you have new data schema and have to migrate (RealmMigrationNeededException).
If you are only developing now - delete application and install it again. It should start to work fine. If your application is in production - you should write some migration code (https://realm.io/docs/java/latest/#migrations)

Related

Rename Realm DB file name in Android

I have a Realm DB file, with name "abc.realm". How to change this name to something else? Should I just replace the file name using IO operations or can I do it with migrations? Not able to find any satisfactory answer neither on the web nor on StackOverflow.
Realm stores 2 files, the realm itself and a .lock file. So if you call your realm "abc.realm", then next to this file there is also "abc.realm.lock".
The way to go about renaming your realm file is,
Make sure you find the location of both files
Rename both files with the same name but keeping the ".lock" extension on the lock file
Modify the path to the realm that you pass to the RealmConfigurationBase inheritor
Clearly before doing any of this, make sure to backup your database, just in case.
I don't know what programming language you're writing your android application in, so I'll go with a skeleton in pseudocode
private void BackupRealmFile(string realmLocation, string saveLocation)
{
// make a copy of the file and store it somewhere
}
void YourMainMethod()
{
BackupRealmFile("some/path", "your/backup/path");
IOLib.RenameFile("some/path/abc.realm", "some/path/newName.realm");
IOLib.RenameFile("some/path/abc.realm.lock", "some/path/newName.realm.lock");
var config = new RealmConfiguration("some/path/newName.realm");
// maybe some more settings on your conf
var realm = Realm.GetInstance(config);
}
I hope this helps.

can we set different realm configuration for different module?

I have main android project that uses another android module. In main android project am getting real instance with some configuration like as.
realm = Realm.getInstance(someConfig());
Am initing Realm from main app Application class, as follows
Realm.init(Context);
In my module when I try to call following line it shows error.
Realm db = Realm.getDefaultInstance();
Error:
error Wrong key used to decrypt Realm.
W/System.err:
java.lang.IllegalArgumentException: Wrong key used to decrypt Realm.
1.) I genuinely think that a library that relies on having its own RealmConfiguration to be set as the "default configuration" is heavily intrusive. So library code should use Realm.getInstance(configuration).
2.) If you want the configurations to refer to different files, you might want to set a different name using new RealmConfiguration.Builder().name("somename.realm")/*...*/.
Add below code to parent class which extends Application/MutlidexApplication class or where ur intializing Realm:
Realm.init(Parent.this);
RealmConfiguration realmConfiguration = new RealmConfiguration.Builder()
.name(AppConstants.DATABASE_NAME)
.schemaVersion(2)
// .migration(new DBMigration())
// .migration(new Migration())
.deleteRealmIfMigrationNeeded()
.build();
Realm.setDefaultConfiguration(realmConfiguration);
Realm.getInstance(realmConfiguration);

How can I create a Realm database with initial data for my android app?

I am trying to create a database for my android application using Realm. I need to have data that is pre-populated when the app is installed. Setting a Realm Migration as part of the RealmConfiguration does not run when the version of the database is 0 (defaults to 0 initially). How can I add data the first time the application is setup?
Realm Java 0.89 introduced a method that allows for specifying a transaction to be run when a Realm database is created for the first time. This method, RealmConfiguration.Builder.initialData(Realm.Transaction transaction), is called as part of setting up the RealmConfiguration Builder.
For example
RealmConfiguration config = new RealmConfiguration.Builder(context)
.name("myrealm.realm")
.initialData(new MyInitialDataRealmTransaction()),
.build();
What I am doing right now that works is to check if this is the first time my app is installed and create a new object.
if (Preferences.freshInstall(getApplicationContext())) {
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
Category inbox = new Category("Inbox", "#445566");
realm.copyToRealm(inbox);
realm.commitTransaction();
Preferences.notNew(getApplicationContext());
}
There should be a better way to do this using Realm Migrations
The initial data transaction setup, as shown by #Benjamin in Realm Java works! I only wish that it was present in Realm Cocoa, as well.
I've created an issue for this, in the Github tracker here, #3877.

RealmMigrationNeededException when changing Realm model [duplicate]

This question already has answers here:
"realm migration needed", exception in android while retrieving values from realm db
(5 answers)
Closed 5 years ago.
Whenever I change the model like adding more fields, the app crash with io.realm.exceptions.RealmMigrationNeededException error. This can only be resolved when I uninstalled and reinstalled the app.
Any suggestion to do migration? I am using only the default instance.
If you don't have any problem in loosing your old data then you can delete Realm Configuration and create new one.
Realm realm = null;
try {
realm = Realm.getInstance(MainActivity.this);
} catch (RealmMigrationNeededException r) {
Realm.deleteRealmFile(MainActivity.this);
realm = Realm.getInstance(MainActivity.this);
}
OR
RealmConfiguration config2 = new RealmConfiguration.Builder(this)
.name("default2")
.schemaVersion(3)
.deleteRealmIfMigrationNeeded()
.build();
realm = Realm.getInstance(config2);
you have to do Migration if you don't want to loose your data please see this example here.
You should be able to find the information you need here:
https://realm.io/docs/java/latest/#migrations
Just changing your code to the new definition will work fine, if you
have no data stored on disk under the old database schema. But if you
do, there will be a mismatch between what Realm sees defined in code &
the data Realm sees on disk, so an exception will be thrown.
Realm migrations in 0.84.2 are changed quite a bit, the key points on making a realm (0.84.2) migration work for me were understanding that:
The schemaVersion is always 0 when your app has a realm db without
specifying the schemaVersion. Which is true in most cases since you
probably start using the schemaVersion in the configuration once you
need migrations & are already running a live release of your app.
The schemaVersion is automatically stored and when a fresh install of your app occurs and you are already on schemaVersion 3, realm
automatically checks if there are exceptions, if not it sets the
schemaVersion to 3 so your migrations aren't run when not needed.
This also meens you don't have to store anything anymore in
SharedPreferences.
In the migration you have to set all values of new columns when the type is not nullable, ...
Empty Strings can be inserted but only when setting convertColumnToNullable on the column

Where can I find the default Realm Database file

I started working on the logic for my migration, using this code:
https://github.com/realm/realm-java/blob/master/examples/migrationExample/src/main/java/io/realm/examples/realmmigrationexample/MigrationExampleActivity.java
And after writing the code, I get an error at this line:
String path3 = MigrationClass.copyBundledRealmFile(this, this.getResources().openRawResource(R.raw.default1), "default1");
It can't find the R.raw.default1 file, because until now, I used the default Realm like this:
Realm realm = Realm.getInstance(context);
My question is where can I get the file path for this realm file?
Realm just uses the Context to call getFilesDir() and the default Realm is called default.realm. So in your case you should use:
String realmPath = new File(context.getFilesDir(), "default.realm").getAbsolutePath();
Realm.migrateRealmAtPath(realmPath, new CustomMigration());
You can get the path of your realm file by calling the "getPath()" method:
Here an Example:
realm.getPath()

Categories

Resources