为什么cursor.getString()行会使应用程序崩溃?

时间:2019-07-10 13:22:49

标签: java android sqliteopenhelper

只要到达执行cursor.getString()的行,应用程序就会崩溃。

我已经尝试了cursor.getString()和cursor.getString(cursor.getColumnIndex(“”)),但仍然崩溃

执行方法:

public void populateView(){
    Cursor data = myDb.getData();
    data.moveToFirst();
    String title = data.getString(data.getColumnIndex(1));
    newsList.add(new NewsItem(R.drawable.ic_home_black_24dp, title, "Description"));
    mAdapter = new NewsItemAdapter(newsList);
    mRecyclerView.setAdapter(mAdapter);
}

DatabaseHelper类中的方法:

public Cursor getData(){
    SQLiteDatabase db = this.getReadableDatabase();
    String query = "SELECT * FROM " + TABLE_NAME_REPORT;
    Cursor data = db.rawQuery(query, null);

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

    return data;
}

P.S。 NewsItem类接受以下参数:

public NewsItem(int imageResource, String title, String desc){
    mImageResource = imageResource;
    mTitle = title;
    mDescription = desc;
}

Process: com.example.reportingapplication, PID: 32448
java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteQuery: SELECT * FROM report_data
    at android.database.sqlite.SQLiteClosable.acquireReference(SQLiteClosable.java:55)
    at android.database.sqlite.SQLiteQuery.fillWindow(SQLiteQuery.java:58)
    at android.database.sqlite.SQLiteCursor.fillWindow(SQLiteCursor.java:151)
    at android.database.sqlite.SQLiteCursor.getCount(SQLiteCursor.java:139)
    at android.database.AbstractCursor.moveToPosition(AbstractCursor.java:220)
    at android.database.AbstractCursor.moveToFirst(AbstractCursor.java:265)
    at com.example.reportingapplication.Fragments.HomeFragment.populateView(HomeFragment.java:104)
    at com.example.reportingapplication.Fragments.HomeFragment$1.onClick(HomeFragment.java:58)
    at android.view.View.performClick(View.java:6608)
    at android.view.View.performClickInternal(View.java:6585)
    at android.view.View.access$3100(View.java:785)
    at android.view.View$PerformClick.run(View.java:25921)
    at android.os.Handler.handleCallback(Handler.java:873)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:201)
    at android.app.ActivityThread.main(ActivityThread.java:6810)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)

1 个答案:

答案 0 :(得分:0)

问题甚至在使用游标之前就将其关闭。感谢@Jordan在评论中指出了这一点。