3

I was using room in my android project, everything was working fine until one day I found Room doesn't insert data in db immediately.

How I reproduced it

When I run command appdatabase.getUserDao().insert(user) and after 2 seconds when i remove my battery from my phone and export db after that What I found is data is not inserted in db. that is 100% sure because my team has reproduced it multiple times. it seems instead of directly store into db it caches data for some time.

Is there any solution for it Where data will directly store in db instead it caches?

2
  • @zjmo is correct, I think unless you close db it might be possible that it remains on cached db. But you shouldn't worry about that because it would always provide data from db anyway. Commented Oct 30, 2020 at 14:14
  • @JeelVankhede , db open and close during every transaction is very heavy. I was also thinking earlier that it is providing data from db but after this issue I found data is fetched from cached, it doesn't store instantly in db. because after restart of device it didn't fetch the same data. Commented Nov 2, 2020 at 4:35

2 Answers 2

2

Yes, close the database before exporting:

RoomDatabase.close()

Make sure it is the

Room.databaseBuilder()

and not

Room.inMemoryDatabaseBuilder()

Check if the thread is executing properly and that you are not interrupting a @Transaction insert

Sign up to request clarification or add additional context in comments.

8 Comments

I can't close db in real world as phone is switched off due to external factors, like battery detached / battery low / out of memory
Once you insert the Entity, cache or not, it is in the database. The app will be able to use the db normally after battery get recharged... restart the phone, close the database before exporting, the data will be there
@zono , this is the main problem when we inserted into db , battery was low then phone was shutdown immediately and after reboot when we fetched data from db, didn't get the value
Or make sure that your background thread executes the insert before you turn off the phone
I dont know. I edited the answer for correlated search
|
0

I got an answer for this issue. Room db writes data to .wal cache file first, then writes to the database afterward. To write directly, please setJournalMode TRUNCATE.

Refer link: https://developer.android.com/reference/androidx/room/RoomDatabase.JournalMode

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.