How to Clear Database in Realm in Android - android

I want to clear whole database when a user press logout button and loads a new data when another user login.I tried many solutions like
try {
Realm.deleteRealm(realmConfiguration);
} catch (Exception ex){
throw ex;
}
Also
try {
Realm.deleteRealmFile(getActivity());
//Realm file has been deleted.
} catch (Exception ex){
ex.printStackTrace();
//No Realm file to remove.
}
But neither of the code works.
Thanks in advance.

When you call Realm.deleteRealm(), you have to make sure all the Realm instances are closed, otherwise an exception will be thrown without deleting anything. By calling this method, all Realm files are deleted, which means all objects & schemas are gone. Catching all exceptions is a bad practise for any general cases.
Or you can call Realm.delelteAll() in a transaction block. This doesn't require all Realm instances closed. It will just delete all the objects in the Realm without clearing the schemas. And again, don't catch all exceptions.

If you are sure there are not any other databases you want to save, you can delete all the other data also. you can follow this answer
Clear Application's Data Programmatically

Related

How to solve greenDAO "No such table exists error" when doing an InsertOrReplace?

I am using greenDAO and I have successfully generated all necessary classes and entities and I can see that my table has been created, however after putting breakpoints on the line to replace, I get an error telling me "No such table exists error".
try {
appTimeUsageDao.insertOrReplace(appStats);
//} catch (DaoException e) {
} catch (Exception e) {
Log.e("Error", "Some exception occurred", e);
Log.e("APP_TAG", Log.getStackTraceString(e));
}
For me this issue was related to this allowBackup flag in the manifest.
This functionality was added from api 23 onwards and the effect of it is to restore the device database even when the app has been uninstalled, so if you're trying to clear the database by uninstalling it wont work as Android restores it, similar to how iCloud works.
I could be missing somewhere in the documentation that explains this error but it isn't clear to me that this could be an issue in GreenDao 3. Additionally as many users will set up a test entity and not consider handling the upgrade path as they have no desire to retain the test table, which results in the scenario of a single table restored and the new tables not being created.
So essentially if you're just testing set the flag to false otherwise handle the upgrade flow. (the flag defaults to true!)
https://developer.android.com/guide/topics/data/autobackup.html
I followed this guide and was having the same problem. I had the database name wrong, for some reason. Check that they are named the same in the AndroidManifest.xml file:
<meta-data
android:name="DATABASE"
android:value="notes.db"/>
And in your class that extends Application:
DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "notes.db");
Have you did this?
mSQLiteDatabase = mOpenHelper.getWritableDatabase();
mDaoMaster = new DaoMaster(mSQLiteDatabase);
mDaoSession = mDaoMaster.newSession();
appTimeUsageDao = mDaoSession.getAppTimeUsageDaoDao();

Resolving nested transactions when using realm and pagination

I'm using realm for persistence in my app.
At the moment, I have a list of items in a simple pagination fashion.
Make a server request
Get items back
Update the UI
Save list to realm
User scrolls to the end of the list, get the next set of elements and repeat
above
Realm code:
try {
mDbManager.beginTransaction();
mDbManager.copyToRealm(list);
mDbManager.commitTransaction();
Logger.v("Realm ", "Copied list to realm");
} catch (Exception e) {
Logger.e("Realm Something went wrong ", e);
}
I get the error because of this pagination loop:
java.lang.IllegalStateException: Nested transactions are not allowed. Use commitTransaction() after each beginTransaction().
I also tried closing the database after each commit but that didn't help.
How can I achieve this storage and resolve the nested transactions?
Or can anyone suggest a better design structure for this?
Thanks
Just make sure that while you catch the exception , you closes the transaction by mDbManager.closetransaction
You can use Realm.isInTransaction() to check if you have an open transaction.
Try to aviod this :
beginTransaction
beginTransaction
commitTransaction
commitTransaction
you should do something like this :
beginTransaction
commitTransaction
beginTransaction
commitTransaction
I think there're beginTransaction() before your code try to close it.

Correct try/catch usage

Can someone please explain to me the proper usage of try/catch when accessing an Android database? Android Studio forces you to use it whenever you are opening a database for writing. I understanding the purpose of using it but my question is would it better do include all of my database work in the try clause like this?
try {
db.open();
db.delete(item);
db.add(item);
/////......
} catch (SQLException e) {
e.printStackTrace();
}
db.close()
Or is it better to use it like this?
try {
db.open();
} catch (SQLException e) {
e.printStackTrace();
}
db.delete(item);
db.add(item);
/////......
db.close()
Is there an important difference? Is one way more efficient or safer than the other?
Thanks in advance for your responses!
Look at the documentation and only use try / catch on methods that throw exceptions
You use the catch block to actually catch exceptions which can be thrown from your code (during runtime). So every call which can throw an exception should be tried/catched, because it helps you differentiating, what went wrong with your code.
So: Wrap a try catch around every function call which can throw an exception
in your second example, if your delete query is malformed, you won't know, the program will continue to run thinking it's been successful.
A try catch, tries something, then catches any errors which may arise.

Transactions in GreenDao

I'm using GreenDao to store a lot of data, coming from a REST service.
A lot of my entities are connected with relations.
Everything works great, but tomorrow I have to implement a rocksolid workflow.
When I load my data I have to check if an error occurs.
If so, I have to make sure nothing is stored in the SQLite DB.
Normally I would work with transactions and rollback in case of an exception,
otherwise commit to the db.
For now I just use insertordelete to save an entity, everytime I created an object.
What would be the way to implement this?
On inserts and updates Greendao checks if there is a ongoing transaction. If that is the case greendao will not start a new transaction.
So the only thing to do is to start a transaction on your database and commit/rollback after your work is done or you notice an error. All inserts and updates will be in the same transaction which has benefits concerning data consistency and also on performance, since greendao will start new transactions with commit/rollback for every insert and update operation.
Summarized you can use code like this:
SQLiteDatabase db = dao.getDatabase();
db.beginTransaction();
try {
// do all your inserts and so on here.
db.setTransactionSuccessful();
} catch (Exception ex) {
} finally {
db.endTransaction();
}
I also tweaked my greendao a bit so that it doesn't cache inserted objects to get further performance and memoryusage benefits (since I insert a lot of data once and I only use very few data during runtime depending on user input). See this post.

How to handle SQLiteException in Android activity?

I am looking at how to handle exceptions in Android.
In the update() function in the sample code for the Notepad Content Provider, it calls getWriteableDatabase(), which can potentially throw an SQLiteException.
I notice that the NoteEditor Activity saveNote() function has the following code:
// Commit all of our changes to persistent storage. When the update completes
// the content provider will notify the cursor of the change, which will
// cause the UI to be updated.
try {
getContentResolver().update(mUri, values, null, null);
} catch (NullPointerException e) {
Log.e(TAG, e.getMessage());
}
What happens if an SQLiteException occurs?. I want to be able to catch this exception in the Activity and display an appropriate message to the user (via a toast or something similar).
I thought I could do by adding an extra catch for SQLiteException. However, I read the following info in the Google docs:
"Remember that the Android system must be able to communicate the Exception across process boundaries. Android can do this for the following exceptions that may be useful in >handling query errors:
IllegalArgumentException (You may choose to throw this if your provider receives an >invalid content URI)
NullPointerException"
So I am now confused - can I catch the SQLiteException or not?
Whenever possible, you should catch the Exception in the class or component in which the Exception occurred. Use some sort of broadcast mechanism or return value semantics to report errors across processes.
It's admittedly a tricky situation. Some people say that if an SQLite (or other Exception) occurs in a ContentProvider, the provider should propagate the exception upwards instead of returning null in the Cursor. However, this generally won't work across processes! On the other hand, returning null doesn't give you a lot of information.
A limited set of Exceptions do traverse process boundaries, but SQLiteException isn't among them - still they might be useful/appropriate.

Categories

Resources