0

The app has two fragments in the same activity. Fragment A have a button then press the button will start a parallel task, that will insert or update a lot of records in the database. Fragment B included a ViewPager, the ViewPager is using FragmentStatePagerAdapter and held Fragment C, and each page will query and display a record from the database.

Fragment B will work properly, until press the button in Fragment A. After that, random pages in ViewPager will not work properly. Some pages will query a null record when the record exists. And there have two situations.

The first situation, Fragment A will have insert and update operations. That is the worst case, some specify records will get a null result in Fragment C, even though slide the ViewPager to reopen the specified page, the record is still null until the parallel task in Fragment A is completed and reopen the Fragment B, then Fragment C can work properly again.

The second situation, Fragment A will have insert and query operations, without update operation. This case will not get a null result, but some specify records will get stuck until the parallel task in Fragment A is completed.

What causes these problems? Thank you in advance.

vimalDev
  • 412
  • 1
  • 4
  • 25
KpSt
  • 43
  • 8

1 Answers1

1

I am not sure but, I think you need to use Transaction Handling for database operations in Fragment A. When you insert or update data in the database from Fragment A, you need to use following methods:

database.beginTransaction();
database.setTransactionSuccessful();
database.endTransaction();

Please check this link to get detail description about this methods and uses. http://www.tothenew.com/blog/sqlite-locking-and-transaction-handling-in-android/

Jaypal Rana
  • 277
  • 1
  • 10
  • Thank you for your answer. Because of I am using `SqlBrite` with `ContentResolver`, therefore I can’t use transaction directly. I can use `ContentResolver.bulkInsert()` or `ContentResolver.applyBatch()` to insert data, I choose `ContentResolver.bulkInsert()` to insert a bulk of data. But I can’t use `ContentResolver.applyBatch()` to update data, because I need to use update or query operator to check the record whether exist, use the result to decide the record whether need to insert to database. Although I am used `ContentResolver.bulkInsert()`, the problem is still exist. – KpSt Apr 09 '18 at 16:39