I am kinda new to android and stuck in a situation, where I don't know how to handle it.
Here is what I am trying to do:
From Activity I start some tasks and show Progress-Dialog while the task completes in background. If the task successfully completes I close the Activity and start new Activity.
But if in background I caught an exception I want to go back to the activity and close the Progress-Dialog and show a Toast maybe that some exception has occurred.
From Activity:
@Override
public void onCreate(Bundle savedInstanceState)
{
// my code
// start Progress Dialog
showProgressDialog();
}
public void showProgressDialog()
{
PD = new ProgressDialog(getActivity());
PD.setMessage("Downloading.....");
PD.show();
}
@Override
public void onDestroy()
{
super.onDestroy();
if (PD != null)
{
PD.dismiss();
PD = null;
}
}
and in background:
try
{
// perform some db tasks
// using AsyncTask
}
catch (Exception e)
{
if(e.getErrorCode() == 34)
{
// From here I want go back to Activity and close the Progress dialog
// and shows what error has occurred.
}
}
So if exception occurred how I am suppose to go back to the activity and close that Progress-dialog, or is there any other way to doing this?
As I know ProgressDialog is in your UI thread and you don't access to that in the background thread. Why don't you use AsyncTask instead ? It's easy to use and you can handle it much easier. Example:
class TestAsync extends AsyncTask<Void, Void, Void> {
private ProgressDialog mDialog;
private Boolean error = false;
@Override
protected void onPreExecute() {
mDialog = new ProgressDialog(TestActivity.this);
mDialog.setCancelable(false);
mDialog.show();
}
@Override
protected Void doInBackground(Void... arg0) {
try {
// whatever you would like to do in background
} catch (Exception e) {
error = true;
}
return null;
}
protected void onPostExecute(Void... arg0) {
mDialog.dismiss();
if (error) {
Toast.makeText(getApplicationContext(),
R.string.error, Toast.LENGTH_SHORT).show();
return;
} else {
// whatever you would like to do after background
}
}
}