问题
I have an application that reads values from a Database table (Database is named SoftCopyDatabase) and populates a List with the values read from Database. On clicking an item from the list a New Activity Starts.
The problem is when I press the back key I got an error
IllegalStateException: database already closed
My code is as follows:
public class OpenClick extends ListActivity {
public static String subjectName;
private SoftCopyDatabase lectures;
private static int[] subTO = { R.id.subject };
private static String[] subFROM = { SUBJECT };
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
lectures = new SoftCopyDatabase(this);
}
public void onStart() {
super.onStart();
try {
Cursor cursor = getSubjects();
showSubjects(cursor);
} catch (Exception e) {
e.printStackTrace();
}
}
public void onRestart() {
super.onRestart();
lectures = new SoftCopyDatabase(this);
}
public void onStop() {
super.onStop();
lectures.close();
}
public void onDestroy() {
super.onDestroy();
lectures.close();
}
//remaining code....
}
One point I would like to mention is if I remove the onStop() Method the application is working properly. But I have to include onstop() because I want to control the opening and closing of Database.
回答1:
Here is a good article covering the topic:
http://awiden.wordpress.com/2010/03/26/database-mangement-and-the-activity-lifecycle/
回答2:
That's normal because both methods are executed... just do this on both methods (onDestroy
and onStop
):
if(lectures.isOpen()){
lectures.close();
}
Although I think you can just put a .close
invokation in one of them. Make sure to create the isOpen
method in your SoftCopyDatabase
class which must call the SqliteDatabase
object's isOpen
method.
来源:https://stackoverflow.com/questions/7125755/activity-life-cycle-and-database