質問

I am using SimpleCursorAdapter and database table to populate a List. The list gets populated and I am able to click on list items to open the desired item(This starts a new activity). The problem is when I press the back key, I got Following error.

IllegalStateException: database already closed.

My code is as follows:

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

    }
}


}

Kindly tell me what mistake am I doing. Because I am not closing the database explicitly any where.

Regards, Waneya Iqbal.

役に立ちましたか?

解決

finally
{       
 lectures.close();
}

I think this line gives the exception, so put it in onDestroy().

他のヒント

You're closing the database as soon as you populate the list. You should move the

lectures.close() 

line from onStart() to onDestroy(), which will make sure your database gets closed when the activity is complete, rather than as soon as the list is populated.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top