java - 使用 SimpleCursorAdapter + Sqlite 似乎不适用于 ListActivity

标签 java android sqlite

我刚刚开始为我的应用程序构建一个非常简单的得分屏幕,但似乎没有发生任何事情,我不明白为什么。

列表 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.

ListViewAdapter 必须有一个“Activity ”Cursor,否则它将无法工作。另外,关闭数据库并不总是一件好事,并且在某些情况下可能会产生不利影响(根据我的经验) - 我不确定这是否也会导致问题。

编辑:根据 Dave Newton 的评论并检查了我自己的一些代码,问题在于在 Cursor 上调用 close() 还有数据库。简而言之,删除以下行...

data.close();
db.close();

关于java - 使用 SimpleCursorAdapter + Sqlite 似乎不适用于 ListActivity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7923080/

相关文章:

java - 仅在滑动到时加载当前页面 - 使用 Android 页面查看器

java - 相互等待的线程

java - Mockito - 如何用自定义对象回答

android - 创建自定义监听器

Android OpenGLES 2.0 纹理映射不工作

python - SQLite - 计算移动平均值

java - 将对象添加到数组时出现 NullPointerException

android - 如何从 YQL 获取所有世界证券交易所的价格

sqlite - 如何在 UWP 项目中使用预先设计好的 SQLite?

excel - 将带有单元格锚定图像的电子表格导入 SQLite 数据库