0

I'm writing an android app that supports exporting the app database to various formats. I don't want to run out of memory, but I want to page the results easily without receiving updates when it changes. So I put it in a service, and came up with the following method of paging.

I use a limit clause in my query to limit the number of results returned and I'm sorting on the primary key. So it should be fast. I use a set of nested for loops to execute the series of queries until no results are returned, and walk through the given results, so that's linear. It's in a service, so it doesn't matter that I'm using immediate result things here.

I feel like I might be doing something bad here. Am I?

// page through all results
for (List<CountedEventType> typeEvents = dao.getEventTypesPaged2(0);
   typeEvents.size() > 0;
   typeEvents = dao.getEventTypesPaged2(typeEvents.get(typeEvents.size() - 1).uid)
) {
    for (CountedEventType type : typeEvents) {
      // Do something for every result. 
    }
}

Here's my dao method.

@Dao
interface ExportDao {
    @Query("SELECT * FROM CountedEventType WHERE uid > :lastUid ORDER BY uid ASC LIMIT 4")
    List<CountedEventType> getEventTypesPaged2(int lastUid);
}
HSchmale
  • 1,838
  • 2
  • 21
  • 48
  • 1
    Why not directly use the paging library? you can set it with or without observing data changes and it also natively supported by room – Mohammed Abdul Bari Feb 25 '21 at 22:57
  • 1
    Check it out here https://developer.android.com/topic/libraries/architecture/paging – Mohammed Abdul Bari Feb 25 '21 at 22:58
  • @MohammedAbdulBari I couldn't figure out how to use the paging library. It felt like too many layers of indirection for me. I know that's probably a bad reason, but I felt like I was going down the rabbit hole with every blog post I read about it. – HSchmale Feb 25 '21 at 23:00
  • My recommendation would be to check out the codelab and sample project because internal operations are optimized, and the best part is you avoid any inadvertent issues, it is worth putting in a little extra effort to understand how it works. If you get stuck on something stackoverflow community is here to help. Cheers – Mohammed Abdul Bari Feb 25 '21 at 23:05

0 Answers0