Activity life cycle and database confusion
-
30-03-2021 - |
Question
I have an activity where I am opening an database by calling constructor of SQLiteOpenHelper.
dbHelper = new DBHelper(this); //DBHelper class extends SQLiteOpenHelper
Then on click of a button I am opening another activity and closing the dbHelper.
int cuisineId = HelperUtils.getCuisineIdByName(dbHelper,cuisine);
SingletonGlobalClass.getInstance().setCuisineId(cuisineId);
String restaurantNameSearchStr = restaurantName.getText().toString().trim();
Intent intent = new Intent();
intent.setComponent(new ComponentName("ctnxa.android", ctnxa.android.SearchResultActivity"));
intent.putExtra("searchStr", restaurantNameSearchStr);
intent.putExtra("option", R.string.restaurant);
startActivity(intent);
dbHelper.close();
Now when I am pressing back button it comes back to this activity. When I am trying to click the search button again it uses the dbHelper and works as usually without any error. My expectation is it should not work as the dbHelper has already been closed before and it can only be re-instantiated when activity onCreate() method is called which is not getting called in this case as I am only pressing back button (It should call onResume()). I am really confused. Could any body explain what is happening here.
Edit: This is how I have implemented dbHelper.close()
@Override
public synchronized void close() {
super.close();
}
Solution
When you start a new Activity
, the first Activity
may or may not go through the various 'exit' stages but there is no guarantee which ones it will go through. It depends entirely on the available resources and other factors on an individual device.
The first Activity
might simply pause and when you return it will resume. However, the first Activity could very likely be stopped or even destroyed. There is no guarantee what the Android OS will do with the first Activity
.
In your case it seems the first IS actually being destroyed and re-created when you return from the second Activity
.
The only way to verify this is to override all of the methods such as onPause
, onStop
and onDestroy
and have each of them use Log
to show which stages the first Activity
goes through.
OTHER TIPS
you can avoid a lot of this confusion by ensuring that there exists only one SQLiteOpenHelper throughout the Application's life-cycle. check out this answer for more info.