1

Is it best practice to close your database when the activity is paused? Or is it safe to leave the database open regardless of the state of the activity?

Curious to know because if i close my database in onPause() then try to reopen it in onResume() it throws a null pointer exception and says trying to re query a database from an already closed cursor. . .

3 Answers3

3

Closing it in onDestroy() is imho the best way.

Thommy
  • 5,070
  • 2
  • 28
  • 51
  • okay so if I leave it open for the onPause() that is fine unless of course it is called with onDestroy() ? –  Mar 06 '12 at 15:52
  • Exactly. onPause() is called when the Activity is in background. And onDestroy() is called before the Activity is gone. So after onDestroy() is through the next time the Activity will be displayed, onCreate() must be called again. – Thommy Mar 06 '12 at 15:56
0

I never close my database and I open it in the onCreate of my custom Application class implementation.

There is a onTerminate method but the documentation says that it never will be executed, so there is no real way to find out when the application will be terminated.

I never experienced any problems with the never close database pattern.

WarrenFaith
  • 57,492
  • 25
  • 134
  • 150
0

Can you post the error? I usually close database in onPause method and open it in onResume. Because I've read that onDestroy is not always called. But in your case the problem is, I think, in a Cursor that is not closed. But I'm not sure that's why I ask you to post logcat and your code.

Yury
  • 20,618
  • 7
  • 58
  • 86
  • Here is the discussion about onDestroy http://stackoverflow.com/questions/8667019/android-activity-ondestroy-is-not-called-when-dalvik-kills-this-activity – Yury Mar 06 '12 at 16:00
  • Please, edit your post and insert an error into your question. It'll be better for other users. – Yury Mar 06 '12 at 16:02
  • yeah here is the error 03-06 10:40:01.931: E/AndroidRuntime(895): java.lang.RuntimeException: Unable to resume activity {com.test.learnandroid/com.test.learnandroid.EditActivity}: java.lang.NullPointerException –  Mar 06 '12 at 16:02
  • Post all logcat as a part in your question. – Yury Mar 06 '12 at 16:14