I have a main activity with 3 tabs, each tab containing a fragment. Each fragment does an async task in which database insertions or updations may occur. The problem is, if i press the back button while the async task is executing, the app closes and a database leak occurs. I want the database connection to be closed before closing the app. Since fragments dont have the onBackPressed method, how do i handle the database in this situation?
This is a sample of what happens inside my async task:
@Override
protected String doInBackground(String... args) {
SQLiteDatabase db = getActivity().openOrCreateDatabase("myDataBase", SQLiteDatabase.CREATE_IF_NECESSARY, null);
JSONObject json = jParser.makeHttpRequest(NewsFeedURL, "POST", params);
if (json != null) {
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
jsonNfArray = json.getJSONArray(TAG_NEWSFEED);
for (int i = 0; i < jsonNfArray.length(); i++) {
JSONObject nf = jsonNfArray.getJSONObject(i);
ContentValues con_val = new ContentValues();
con_val.put("nid", nf.getString("nid"));
con_val.put("headlines", nf.getString("headlines"));
con_val.put("news", nf.getString("news"));
con_val.put("date", nf.getString("date"));
con_val.put("imgurl", nf.getString("images"));
db.insert("newsfeed_tbl", null, con_val);
newsfeed_success = true;
}
db.close();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}