Hick
Hick

Reputation: 36384

How to handle database locking error in Android?

So, after having gone through many other such questions, I decided to use one instance of my SqlLiteDataHandler through out the app, in all the activities that I require it.

How I do it is, when the Splash screen loads, I create a public Static instance of the SqlLiteDataHandler.

I then use that handler everywhere, though I never close it or make it null, as I understand that the app will lose its reference once the app is closed.

But the problem still persists. I still get a database locked problem when I try to get out and get into the app multiple times. (Thus, going through the splash screen multiple times.)

Where am I going wrong?

My instance creation is as simple as this:

DbStaticClass.sqlDataHandler = new LinkDataHandler(SplashScreen.this);

and I use DbStaticClass.sqlDataHandler throughout the app.

Upvotes: 0

Views: 175

Answers (1)

dst
dst

Reputation: 3337

You should not create your LinkDataHandler from the splash screen, as there are multiple execution paths not involving your splash screen or calling it multiple times, some examples:

  • Android kills your application while it is in background due to low memory, and re-creates only the visible Activity when the user comes back to it
  • You have a Service started without entering the splash screen first
  • Your application handles an external Intent
  • Services or other stuff could cause your application not to be restarted if the user enters your application through the splash screen again, causing it to get executed multiple times.

While the last ones might not be the case in your application, you cannot escapt the first one; you have multiple sqlDataHandlers created and thus multiple connections to the database are opened, which could collide due to multiple reasons.

To implement a singleton based on the application context properly, use the Application class and its onCreate, as explained in another answer.


This Answer is based on assumptions:

  • DbStaticClass.sqlDataHandler gets initialized only in an Activity's onCreate method (SplashScreen)
  • You access DbStaticClass.sqlDataHandler outside of SplashScreen.
  • LinkDataHandler creates your Database handler stuff.

Upvotes: 1

Related Questions