I am creating an app which downloads data from a particular source and stores them in a Realm database. According to my understanding, I should be able to access that database every time, I need that data, after that.
So I tried following process: Initialize the database. Download data and fetch database that data. Print data on terminal. -> As far as this, everything is going well.
So now according to my understanding, I closed the app and restarted it. Now I tried to print out the data, but there was no reaction. Does that mean, that the database is just alive for the period, in which my app is active?
Is there a way to store a Realm database on an android device for offline use? That means, in case that my user has no access to the internet and needs to use the downloaded database.
My Code:
@Override
protected void onCreate(Bundle savedInstanceState) {
final MainActivity act = this;
initRealm();
setRights();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Button for updating database
Button btn = findViewById(R.id.getData);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Connects to database
ConnectToDatabase c = new ConnectToDatabase(act);
c.doInBackground();
values = c.getValues();
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
int i = 0;
for (List<Object> rows : values) {
entry e = realm.createObject(entry.class, String.valueOf((++i) + 1));
//e.setEntry();
e.setNachname((String) rows.get(1));
}
realm.commitTransaction();
realm.close();
//showResults();
}
});
Button btn2 = findViewById(R.id.qr_scanner);
btn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v){
showResults();
}
});
}
//Show current Realm results
public void showResults(){
Realm realm = Realm.getDefaultInstance();
RealmQuery<entry> query = realm.where(entry.class);
RealmResults<entry> listEntries = query.findAll();
for (entry x : listEntries){
System.out.println(x.getId());
}
realm.close();
}
//Initialisation for Realm
private void initRealm() {
Realm.init(this);
String root = Environment.getExternalStorageDirectory().getAbsolutePath();
RealmConfiguration realmConfig = new RealmConfiguration.Builder()
.name("management.database")
.directory(new File(this.getFilesDir().getAbsolutePath() + "/realm/"))
.build();
Realm.deleteRealm(realmConfig);
Realm.setDefaultConfiguration(realmConfig);
}
private void setRights() {
StrictMode.ThreadPolicy policy = new
StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
In your initRealm()
method, you include the following command:
Realm.deleteRealm(realmConfig);
In a nutshell, you delete your realm everytime you initialize it. This is why you get no results back. You don't need an internet connection to access your Realm. It is stored locally. You should just avoid deleting it.