android.database.StaleDataException:访问关闭的游标

时间:2014-07-11 14:29:14

标签: android android-sqlite android-cursoradapter staledataexception

我有主要的Activity,一个SQLiteOpenHelper类和一个Fragment,我必须从数据库中获取一个带有数据的Cursor。

在我的主要活动中,我作为静态公共成员存储并启动数据库:

public class Main extends FragmentActivity {
    public static Main MainActivity;
    public static DBHelper Database;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        MainActivity = this;
        Database = new Database(getApplicationContext(), "db_test", null, 1);
    }
}

这就是我的数据库类的样子:

public class DBHelper extends SQLiteOpenHelper {
    public static final String MAIN_TABLE = "tbl_list";

    public DBHelper(Context c, String n, CursorFactory f, int v) {
        super(c, n, f, v);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(
            "CREATE TABLE IF NOT EXISTS " + MAIN_TABLE + " (" + 
            "_id INTEGER PRIMARY KEY AUTOINCREMENT, " + 
            "name VARCHAR (64) NOT NULL, " + 
            "status TEXT DEFAULT NULL " + 
            ")"
        );
    }

    @Override
    public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
    }
}

在我的片段中,我正在尝试检索包含所有记录的列表:

public class MyFrag extends Fragment {
    private DBHelper db;

    @Override
    public View onCreateView(LayoutInflater i, ViewGroup v, Bundle b) {
        db = Main.Database.getWritableDatabase();
    }

    private void showList() {
        ListView list_view= new ListView(Main.MainActivity);
        String[] data = { "_id", "name", "status" };
        Cursor c = db.query(Database.TASKS_TABLE, data, null, null, null, null, null);

        c.moveToFirst();

        if (c.getCount() > 0) {
            String[] columns = new String[] { "name", "status" };
            int[] views = new int[] { 
                R.id.item_name, 
                R.id.item_status
            };
            SimpleCursorAdapter adapter = new SimpleCursorAdapter(
                Main.MainActivity, 
                R.layout.mylist, 
                c, 
                columns, 
                views, 
                0
            );
            list_view.setAdapter(adapter);
        }
    }
}

当我运行应用程序时,我收到此错误:android.database.StaleDataException: Access closed cursor

1 个答案:

答案 0 :(得分:1)

您没有打开与数据库的连接,因此您无法访问它,您必须添加一个打开数据库的方法,并在完成操作后关闭它