In one of my activities I\'m using AsyncTask
. In doInBackground()
I\'m making calls to various methods. In one of these methods I\'m getting an exc
Create a handler object and execute all your Toast messages using that.
@Override
protected Void doInBackground(Void... params) {
Handler handler=new handler();
handler= new Handler(context.getMainLooper());
handler.post( new Runnable(){
public void run(){
Toast.makeText(context, "Created a server socket",Toast.LENGTH_LONG).show();
}
});
}
try this code
void showError(final String err) {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(downloadprogress.this, err + "error in download", Toast.LENGTH_LONG)
.show();
}
});
}
If you have to declare anything related to Thread, then it must be outside the runOnUiThread() method, then only it is going to execute,
@Override
protected String doInBackground(String... strings) {
for(int i=0; i<10; i++) {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Example for Toast "+i, Toast.LENGTH_SHORT).show();
}
});
try {
Thread.sleep(10);
} catch (Exception e) {}
}
return "";
}
Write the following code where you have to show toast in doInBackground()
method
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Example for Toast", Toast.LENGTH_SHORT).show();
}
});
Fragments
, you need to call runOnUiThread(...)
through your activity:getActivity().runOnUiThread(...)
You could wrap the Toast in runOnUIThread() but this isn't the best solution.
You should set a boolean flag in the catch block when an error occurs, then display an appropriate Toast in onProgressUpdate()
, onPostExecute()
, or any of the other methods with UI access whenever the flag is true
.
You can display it in a method, that has access to the UI thread like onPreExecute()
, onProgressUpdate()
and onPostExecute()