Activity Life Cycle and Database

I have an application that reads values โ€‹โ€‹from a database table (the database is called SoftCopyDatabase) and populates the list with values โ€‹โ€‹read from the database. When you click on an item from the list, a new activity begins.

The problem is that when I press the back key, I got an error

IllegalStateException: database already closed 

My code is as follows:

The OpenClick public class 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 that I would like to mention is to remove the onStop () method, which the application is working correctly. But I have to enable onstop () because I want to control the opening and closing of the database.

0
source share
2 answers

This is normal because both methods are executed ... just do it for both methods ( onDestroy and onStop ):

 if(lectures.isOpen()){ lectures.close(); } 

Although I think you can just insert .close invokation into one of them. Remember to create the isOpen method in the SoftCopyDatabase class, which should call the SqliteDatabase object isOpen .

+1
source

Source: https://habr.com/ru/post/1499328/


All Articles