In my application I have a sqlite database that looks like this:
CREATE TABLE notes (_id integer primary key,
content text);
CREATE TABLE tags (_id integer primary key,
name text,
noteid integer,
foreign key(noteid) references notes(_id));
I’m storing text that can have some tags associated with it. Now I want to show this text and the tags in a ListView. However I can’t figure out how to do this with a SimpleCursorAdapter. Is it even possible? My data might look like this:
sqlite> select * from notes;
1|foo bar baz
sqlite> select * from tags;
1|x|1
2|y|1
The query to get all notes and the data it returns looks like this:
sqlite> select notes._id, notes.content, tags.name from notes, tags where notes._id = tags.noteid;
1|foo bar baz|x
1|foo bar baz|y
Now, if I want to bind this data to the ListView in some way, how to do it? I would be happy if each row int the ListView contained two lines, one line with the content and one line with all the tags. Am I correct in guessing that the SimpleCursorAdapter won’t help me here? What should I do instead?
SimpleCursorAdapteralone can’t help you here.If your goal is that you want one row to be one note + all its tags, you can try overriding
bindView()inSimpleCursorAdapterand pouring in the tags that way. That would imply that you have already built up some sort ofHashMapof note->tags and therefore can quickly determine the tags to go in the row.To build up the
HashMap, you have two choices that I see:Build them on the fly by looking up the note in the
HashMap, then doing a query to get the tags for that note if they’re not found, caching them in theHashMapfor later reuse (e.g., scrolling). The catch here is that you’re doing a bunch of little queries (bad) and doing them on the main application thread while the user is scrolling (really bad).Do one big query using an
INclause to get all tags for all notes, and convert the resultingCursorinto a fully-populatedHashMap. Then, your per-row lookups will all succeed. This works well if you only have a modest number of rows; otherwise, this query may take longer than the user has patience for.If your schema is flexible, you might consider whether you are better served with some amount of denormalization, such as having the tags in a single column of the notes table via a comma-delimited list or something. Even if that complicates write operations (e.g., putting tags in two places), if your reads greatly outnumber your writes, it may be worth it.