Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve data from child table using CursorLoader which loads data from main table?

My app is using CursorLoader to load data from main table. The data will be displayed in ListView with the help of CursorAdapter. The view displayed in ListView also requires data from child table. The relationship of the tables is one-to-many.

  • If I join both tables during the query, the combined records will be as many as child records, thus in ListView, it will display multiple item for one single record in the main table.

  • If I don't join the table, I am not sure what the best way to retrieve child records after the CursorLoader has delivered the data via the cursor. Anyone able to help me out?

like image 478
bitbybit Avatar asked Sep 28 '11 16:09

bitbybit


1 Answers

If the child table data doesn't need to be queried separately then you could put that data into the main table using something like JSON notation and then parse it out inside of the bindView method for the CursorAdapter. This might have performance problems depending on the complexity of the data in the child table. But that would allow you to use a single cursor.

Another approach you could take is to make a DAO object that ran the raw query as a join (so you get multiple rows) and then processes the cursor it to a List where Foo is a POJO representing the data. (or run n+1 queries - the main query and then a sub query for each row). Then make a Loader that calls the DAO to return a List and use a ListAdapter from that. Your custom loader could still register for the data change notifications and do the reloading. I've used CursorLoader as a pattern to make my own loaders that reload when I didn't want to mess with the Cursor in the ListView and it works well.

like image 175
harmanjd Avatar answered Sep 19 '22 00:09

harmanjd