Retrieving data from different SQLite tables in Android?
I was wondering if I have this situation:
- In our SQLite databse, there are some tables (let's say four). each table consists of two columns:
Title and Content
. - We retrieved the titles from all the four tables, and display them in one
ListView
The question is: How can we handle the onItemClickListener
so that we can retrieve the Content
of the selected item given that the items are from different tables?
I think I'll come across problem like that and I just want to know if it can be 开发者_Go百科handled or not.
Thanks.
I'd say use an ArrayAdapter
and wrap the data in a custom class that contains the table it came from (and ID etc if you need it), then you can get the ID and table by just knowing the index in the list.
The class could look something like this:
public static class ListItem {
public String title, table;
// Maybe include these as well?
public String content;
public int id;
@Override
public String toString() {
return title; // Or something else maybe?
}
}
Then simply build your data from the cursors into a ListItem[]
and create the adapter like this:
new ArrayAdapter<ListItem>(data);
One problem with this solution is that you need to load everything in memory, if there is a lot of data you can create a custom Cursor
which contains all four cursors and use a CursorAdapter
instead.
The solution Nicklas A. proposed will do the trick. But if you have identical items why do you keep them in 4 different tables? If you items are identical it's betten to keep them in signle table and just to add some additional column to identify them if needed. If your items are not identical create 4 model classes for each of them and handle onItemClicked in each model.
精彩评论