我刚刚开始为我的应用程序构建一个非常简单的得分屏幕,但似乎没有发生任何事情,我不明白为什么。
列表 Activity :
public class HighScoresActivity extends ListActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.high_scores);
ScoresDatabase db = new ScoresDatabase(this);
Cursor data = db.getHighScores();
ListAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, data, new String[] { "level" }, new int[] { R.id.level_text });
setListAdapter(adapter);
data.close();
db.close();
}
}
high_scores.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:text="Text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/level_text"/>
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</LinearLayout>
没有任何错误消息,什么也没有发生。 也不是光标是空白的,当我测试adapter.getCount()方法时,它返回~30,这与预期完全一致。
我认为所有函数名称都非常直观,但如果您需要任何说明,请询问。
非常感谢任何帮助
最佳答案
data.close(); // DON'T DO THIS
来自 Cursor.close() 的文档...
Closes the Cursor, releasing all of its resources and making it completely invalid. Unlike deactivate() a call to requery() will not make the Cursor valid again.
ListView
的 Adapter
必须有一个“Activity ”Cursor
,否则它将无法工作。另外,关闭数据库并不总是一件好事,并且在某些情况下可能会产生不利影响(根据我的经验) - 我不确定这是否也会导致问题。
编辑:根据 Dave Newton 的评论并检查了我自己的一些代码,问题在于在 Cursor 上调用
还有数据库。简而言之,删除以下行...close()
data.close();
db.close();
关于java - 使用 SimpleCursorAdapter + Sqlite 似乎不适用于 ListActivity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7923080/