【发布时间】:2011-01-21 07:43:11
【问题描述】:
我想编写一个 ListAdapter 来提供来自数据库的数据,如下所示:
CREATE TABLE notes (_id integer primary key,
content text);
CREATE TABLE tags (_id integer primary key,
name text,
pos integer
noteid integer,
foreign key(noteid) references notes(_id));
我使用这个数据库来存储笔记及其相关标签。 ListAdapter 的一项要求是,如果基础数据发生更改,它必须能够更新 ListView 内容。我可以用这个查询查询数据库中的所有笔记:
select notes._id as id, notes.content, tags.pos, tags.name
from notes left join tags on id = tags.noteid
order by id, tags.pos;
这将使我得到如下所示的结果(为清楚起见显示空值):
0|foo bar baz|0|x
1|hello world|null|null
2|one more nn|0|yy
2|one more nn|1|y
如您所见,带有多个标签的便笺将位于结果中的多行上。这意味着我不能看光标大小来确定音符的数量,我需要遍历整个 Cursor 才能得到计数。我不想那样做。
到目前为止,我想出的解决方案是使用两个游标:一个用于上面提到的查询,另一个用于包含 notes 表中行数的查询 (select count(*) from notes)。在构造函数中我调用intializeCursors():
private void initializeCursors() {
notesCursor.moveToFirst();
countCursor.moveToFirst();
count = countCursor.getInt(0);
}
我已经像这样实现了 getItem():
public Note getItem(int position) {
// notes is a List of notes that we have already read.
if (position < notes.size()) {
return notes.get(position);
}
int cursorPosition = notes.size();
while (cursorPosition <= position) {
// Creates a note by reading the correct number of rows.
Note note = NotesDb.noteFrom(notesCursor);
notes.add(note);
++cursorPosition;
}
return notes.get(position);
}
适配器假定游标是由某个调用了startManagingCursor() 的活动管理的。
到目前为止一切都很好,我猜。现在的问题是如何处理被请求的游标。由于我有两个游标,我需要为它们注册监听器,当我收到它们的onChange() 时,我可以initializeCursors() 并通知注册到我的ListAdapter 的任何监听器其数据发生变化。
这是我迄今为止最好的。我想与这个小组一起检查这种方法的合理性。 :-) 这种方式复杂吗?也许我错过了 API 的某些部分可以很好地解决这个问题?
提前致谢!
【问题讨论】:
标签: android listadapter