In my app android, I can access to my sqlite database from:
1) Service android, every 60 seconds.
2) After pressure of button (onclik)
If I press the button while my service is accessing the database an error occurs.
So I insert in the onclickListener, before access to database, a call to stopService()
but the conflict remains, because, even if I call stopService() before access to database, the service is stopped after this!
I tried, using :
private boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if ("com.example.MyService".equals(service.service.getClassName())) {
return true;
}
}
return false;
}
suggested in How to check if a service is running on Android?
I tried to call this method, before access to database, in this manner:
while(isMyServiceRunning())
{
// do nothing
}
// *** access to my database ***
What can I do in order to be sure that my service is stopped before accessing to database?
The error is:
10-30 21:05:43.360: E/SQLiteDatabase(13960): Failed to open the database. closing it.
10-30 21:05:43.360: E/SQLiteDatabase(13960): android.database.sqlite.SQLiteDatabaseLockedException: database is locked
10-30 21:05:43.360: E/SQLiteDatabase(13960): at android.database.sqlite.SQLiteDatabase.native_setLocale(Native Method)
10-30 21:05:43.360: E/SQLiteDatabase(13960): at android.database.sqlite.SQLiteDatabase.setLocale(SQLiteDatabase.java:2115)
10-30 21:05:43.360: E/SQLiteDatabase(13960): at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:984)
10-30 21:05:43.360: E/SQLiteDatabase(13960): at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:956)
10-30 21:05:43.360: E/SQLiteDatabase(13960): at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:1021)
10-30 21:05:43.360: E/SQLiteDatabase(13960): at android.app.ContextImpl.openOrCreateDatabase(ContextImpl.java:753)
10-30 21:05:43.360: E/SQLiteDatabase(13960): at android.content.ContextWrapper.openOrCreateDatabase(ContextWrapper.java:221)
10-30 21:05:43.360: E/SQLiteDatabase(13960): at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:149)
10-30 21:05:43.360: E/SQLiteDatabase(13960): at host.database.DB_DatabaseManager.open(DB_DatabaseManager.java:134)
You can override the
onDestroy()
event for the service and try to access the database on it: