android IllegalStateException,数据库已经关闭

时间:2011-08-18 17:13:04

标签: android sqlite illegalstateexception

我正在使用SimpleCursorAdapter和数据库表来填充List。列表将被填充,我可以单击列表项以打开所需的项目(这将启动一个新活动)。问题是当我按后退键时,我得到了以下错误。

IllegalStateException:数据库已关闭。

我的代码如下:

public class populatingLectures extends ListActivity{

private static String[] FROM = {SUBJECT, TOPIC, LECTURENUMBER, DATE };
private static int[] TO = {R.id.subject, R.id.topic,
        R.id.lecturenumber, R.id.date };
private static String[] data = { SUBJECT, TOPIC, LECTURENUMBER, _DATA };
private static String ORDER_BY = DATE + " DESC";
private SoftCopyDatabase lectures;  
String gotId;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    SoftCopyDatabase lectures = new SoftCopyDatabase(this);
    try {
        Cursor cursor = getLectures();
        showLectures(cursor);
    } finally {
        lectures.close();
    }
}

public void onStart() {
    super.onStart();
    lectures = new SoftCopyDatabase(this);
    try {
        Cursor cursor = getLectures();
        showLectures(cursor);
    } finally {
        lectures.close();
    }
}

private Cursor getLectures() {

    SQLiteDatabase db = lectures.getReadableDatabase();

    Cursor cursor = db.query(TABLE_NAME,null, "subject=?", new String[] {OpenClick.subjectName}, null, null,
            ORDER_BY);
    startManagingCursor(cursor);
    return cursor;
}


private void showLectures(Cursor cursor) {

    SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
            R.layout.item_lectures, cursor, FROM, TO);
    setListAdapter(adapter);
}

private Cursor getFileName(String ID) {

    SQLiteDatabase db = lectures.getReadableDatabase();
    Cursor cursor = db.query(TABLE_NAME, data, "_ID=?",
            new String[] { ID }, null, null, null);
    startManagingCursor(cursor);
    return cursor;
}


@Override
protected void onListItemClick(ListView listView, View view, int position,
        long id) {
    super.onListItemClick(listView, view, position, id);

             //...CODE TO START NEW ACTIVITY

    }
}


}

请告诉我,我在做什么错。因为我没有明确地关闭数据库。

此致 Waneya Iqbal。

2 个答案:

答案 0 :(得分:4)

finally
{       
 lectures.close();
}

我认为这一行给出了异常,所以把它放在onDestroy()中。

答案 1 :(得分:0)

填充列表后,您将立即关闭数据库。你应该移动

lectures.close() 

从onStart()到onDestroy(),这将确保您的数据库在活动完成时关闭,而不是在填充列表后立即关闭。