I have a difficulty with my database connection. I have a DataManager which creates the Database connection etc. I also created an Application class which creates this DataManager so the UI Thread can get the data. Now the problem is that there is a background thread which also needs access to the database, and I am not exactly sure how to do this (currently I get an error when trying to create a new DataManager in the AsyncActivity because the database was not closed (and this is correct, as the UIThread has it open).
So I thought that (and this might not be the right way to do it as it is a different thread) I would get access to the Application and use the same DataManager on a new session. But how can I get access to the Application from an ‘ordinary’ class without Context or Activity (I have done it before I think, but cannot remember).
The code of the background task is:
public class SyncTask extends AsyncTask<String, Integer, String> {
private static final String TAG = "Sync";
/** application context. */
private Context context;
private ProgressDialog dialog;
public SyncTask(Context aContext) {
//this.activity = activity;
this.context = aContext;
dialog = new ProgressDialog(context);
}
protected void onPreExecute() {
this.dialog.setMessage("Loading...");
this.dialog.setMax(100);
this.dialog.setProgress(0);
this.dialog.show();
}
@Override
protected void onPostExecute(final String errMessage) {
if (dialog.isShowing()) {
dialog.dismiss();
}
if (errMessage == null) {
Toast.makeText(context, "Update completed", Toast.LENGTH_LONG).show();
} else {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Error...");
alertDialog.setMessage(errMessage);
alertDialog.show();
}
}
protected void onProgressUpdate(Integer... progress) {
Log.d(TAG, "Progress Update: " + progress[0].toString());
super.onProgressUpdate(progress[0]);
dialog.setProgress(progress[0]);
}
protected String doInBackground(final String... args) {
try{
publishProgress( new Float(50).intValue());
iDomsAndroidApp app = ((iDomsAndroidApp) ?? cannot remember ??);
DataManager manager = app.getDataManager();
manager.updateData();
return null;
} catch (Exception e){
Log.e(TAG, "error", e);
return e.getMessage();
}
}
}
You can use getApplicationContext() method of any Context instance you have and cast return to YouApplication. It is absolutelly eligible.