Reputation: 23516
I have the following problem: My app uses a function which executes all HTTP calls. As a quick fix I'd like to show the user a toast message whenever there is an ConnectionTimeout
.
The problem is that this executeHttp() is called from several AsyncTasks
and I can't figure out how to get the required context
.
I read something about runOnUiThread
but this also didn't seem to work for me...
Any ideas?
Thanks!
Update:
I'd like to have a solution which I can use in my executeHttp()
function because else I have do add this code in 100 different places... Is this possible?
Upvotes: 0
Views: 893
Reputation: 2843
First, implement a Method to show a Toast to your activity:
class MyActivity extends Activity {
// some stuff
public void showToast(String text, int duration) {
Toast toast = Toast.makeText(this.getBaseContext(), text, duration);
toast.show();
}
}
The let your AsyncTask hold a reference to the activty which can then be called in the onProgressUpdate Method:
class MyAsyncTask extends AsyncTask {
MyActivity activity;
public MyAsyncTask(MyActivity a)
this.activity = a;
}
@Override
protected Object doInBackground(String... params) {
try {
// do your stuff here
} catch (ConnectionTimeoutException e) {
publishProgress("timeout");
}
@Override
protected void onProgressUpdate(String... values) {
if(values[0].equals("timeout")
activity.showToast("Ups, we have a timeout!", Toast.LENGTH_LONG); }
}
}
}
If you want it in your executeHttp() method, you have to pass the Context to it in order to show a Toast:
public ReturnValue executeHttp(Context context) {
try {
// ...
} catch(ConnectionTimeoutException e) {
Toast t = Toast.makeToast(context, message, duration);
t.show();
}
}
summary: no available context -> no toast
Upvotes: 4