Issue
i have an asynctask but if i implement a Thread.Sleep , then my app crashes , i dont know why, in onPreExecute i can see my first message and then after two secs it appears the other one i put in doInBackground , but its not working
private class sendMail extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
dialog.setMessage("Please wait...");
dialog.show();
}
// automatically done on worker thread (separate from UI thread)
@Override
protected Void doInBackground(Void... voids) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
dialog.setMessage("Downloading files...");
new BackgroundTask().execute();
//MY DOWNLOADING METHODS STUFF
And then i dismiss this dialog somewhere else
Log
An error occurred while executing doInBackground()
Solution
You cannot access the UI elements from a background thread you can update the progressbar in onProgressUpdate
, most importantly you need to publishProgress(value)
in doInBackground and update using onProgressUpdate
. Read more about the AsyncTask here.
Example code:
class MyTask extends AsyncTask<Integer, Integer, String> {
@Override
protected String doInBackground(Integer... params) {
for (; count <= params[0]; count++) {
try {
Thread.sleep(1000);
publishProgress(count);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return "Task Completed.";
}
@Override
protected void onPostExecute(String result) {
progressBar.setVisibility(View.GONE);
txt.setText(result);
btn.setText("Restart");
}
@Override
protected void onPreExecute() {
txt.setText("Task Starting...");
}
@Override
protected void onProgressUpdate(Integer... values) {
txt.setText("Running..."+ values[0]);
progressBar.setMessage("Downloading files...");
progressBar.setProgress(values[0]);
}
}
Answered By - Sai
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.