ProgressDialog inside AsyncTask not showing progress [duplicate] - android

This question already has answers here:
ProgressDialog in AsyncTask
(7 answers)
Closed 6 years ago.
Though I have checked many references online, I still can't find the problem.
It seems the ProgressDialog appears fine but whenever I want to update the progress, in onProgressUpdate its instance is always null.
This is my AsyncTask:
package com.async_tasks;
public class UploadTask extends AsyncTask<Void,Integer,Void> implements Serializable {
private static final String TAG = UploadTask.class.getSimpleName();
private ConnectionToServer _connectionToServer;
private TransferDetails _td;
private Activity _activity;
private ProgressDialog _progDialog;
private UploadTask _taskInstance;
public UploadTask(Activity activity, ConnectionToServer connectionToServer, TransferDetails td) {
_activity = activity;
_connectionToServer = connectionToServer;
_td = td;
_taskInstance = this;
}
#Override
protected void onPreExecute() {
_progDialog = new ProgressDialog(_activity);
String cancel = _context.getResources().getString(R.string.cancel);
_progDialog.setCancelable(false);
_progDialog.setTitle(_context.getResources().getString(R.string.uploading));
_progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
_progDialog.setProgress(0);
_progDialog.setMax(100);
_progDialog.setButton(DialogInterface.BUTTON_NEGATIVE, cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
_taskInstance.cancel(true);
}
});
_progDialog.show();
}
#Override
protected Void doInBackground(Void... voids) {
//uploading file ...
float percent = (float) (fileSize - bytesToRead) / fileSize * 100;
publishProgress((int)percent);
}
}
catch (IOException e) {
// Handling exception
} finally {
if(bis!=null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
clearMembers();
}
}
return null;
}
#Override
protected void onProgressUpdate(Integer... progress) {
if(_progDialog!=null) { // <<------------ I suspect for some reason this is always false, as _progDialog is always null - But why?!
_progDialog.incrementProgressBy(progress[0]);
}
}
#Override
protected void onPostExecute(Void result) {
//The task is complete, clear members
clearMembers();
}
private void clearMembers() {
_activity = null;
if(_progDialog!=null) {
_progDialog.dismiss();
_progDialog = null;
}
}
}
And this is the call from MainActivity:
TransferDetails td = (TransferDetails) report.data();
ConnectionToServer conn = StorageServerProxyService.getConn();
UploadTask uploadTask = new UploadTask(MainActivity.this, conn, td);
uploadTask.execute();

Modify the onPreExecute() method as below :
#Override
protected void onPreExecute() {
progDialog = new ProgressDialog(ActivityName.this);
String cancel = _context.getResources().getString(R.string.cancel);
_progDialog.setCancelable(false);
_progDialog.setTitle(_context.getResources().getString(R.string.uploading));
_progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
_progDialog.setProgress(0);
_progDialog.setMax(100);
_progDialog.setButton(DialogInterface.BUTTON_NEGATIVE, cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
_taskInstance.cancel(true);
}
});
_progDialog.show();
}

Related

get value from asynctask

I found many subject about but I can't get a solution, I'm doing a soap request in doInBackground method of asyncTask, and I want to get an Integer to know if the process is done, here I call my asyncTask:
Simulation.AsyncSoapCall task = new Simulation.AsyncSoapCall();
try {
Integer taskResult = task.execute().get();
} catch (Exception e) {
e.printStackTrace();
}
My AsyncTask class:
private class AsyncSoapCall extends AsyncTask<Void, Void, Integer> {
Integer result;
Boolean isInternetPresent = false;
Boolean isUrlAvailable = false;
ConnectionDetector cd;
AsyncSoapCall(){
}
#Override
protected Integer doInBackground(Void... params) {
cd = new ConnectionDetector(getActivity().getApplicationContext());
// get Internet status
isInternetPresent = cd.isConnectingToInternet();
// check for Internet status
if (isInternetPresent) {
String namespace = getResources().getString(R.string.NAMESPACE);
String url = getResources().getString(R.string.URL);
String soapaction = getResources().getString(R.string.SOAP_ACTION);
String login = getResources().getString(R.string.login);
String mdp = getResources().getString(R.string.mdp);
isUrlAvailable = cd.isUrlAvailable();
// check for Internet status
if (isUrlAvailable) {
String idApplication = Installation.id(getActivity());
SOAPContact soapContact = new SOAPContact(namespace, url, soapaction, login, mdp);
soapContact.saveParams(getResources().getString(R.string.origine), db);
result = 1;
} else {
result = 2;
}
} else {
result = 3;
}
return result;
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
Log.i(TAG, "onPreExecute");
}
#Override
protected void onProgressUpdate(Void... values) {
Log.i(TAG, "onProgressUpdate");
}
}
I don't get error my app crasha at this line:
Integer taskResult = task.execute().get();
try to get the value from onPostExecute like
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
int yourNum = result;
}
that's it
Did you read the doc?
https://developer.android.com/reference/android/os/AsyncTask.html
AsyncTask has no "get" method.
You need to define a OnPostExecute method which will be called when your task is over with your Integer as a parameter.
public class MyActivity extends Activity
{
private Integer myInteger;
private void blabla(){
Simulation.AsyncSoapCall task = new Simulation.AsyncSoapCall() {
#Override
protected void onPostExecute(Integer result) {
//... Your code here ...
MyActivity.this.myInteger = result;
MyActivity.this.myMethod(result);
}
}
try {
task.execute();
} catch (Exception e) {
e.printStackTrace();
}
}
protected void myMethod(Integer integer){
}
}
Here is one method with the help of interfaces,
MainActivity.java
public class MainActivity extends AppCompatActivity {
static String TAG=MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AsyncSoapCall request = new AsyncSoapCall(new AsyncSoapCall.AsyncSoapInterface() {
#Override
public void callBack(String callBackValue) {
Log.d(TAG,callBackValue);
}
});
request.execute();
}
}
AsyncSoapCall.java
public class AsyncSoapCall extends AsyncTask<Void,Void,Void> {
interface AsyncSoapInterface{
void callBack(String callBackValue);
}
AsyncSoapInterface callbackObj;
AsyncSoapCall(AsyncSoapInterface callbackObj)
{
callbackObj = callbackObj;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
callbackObj.callBack("Your value");
}
}

Android progress bar for method

I have a custom method of my class that (on my Android phone) takes 2-3 second to finish, and I would like to surround it with a progress bar.
Here is my method:
public void getQuestionsForSelectedCategory(){
ArrayList<Question> temp = (ArrayList<Question>) this.clone();
ArrayList<Question> tempGroup;
this.clear();
for(int i=0;i<2;i++){
tempGroup = new ArrayList<Question>();
for(int j=0;j<temp.size();j++)
if((temp.get(j).getGroup()==i+1)&&(temp.get(j).getCategory().contains(category)||temp.get(j).getCategory().equals("*")))
tempGroup.add(temp.get(j));
getQuestionsForSelectedGroup(tempGroup, numbersByGroup[i], pointsByGroup[i]);
}
tempGroup = new ArrayList<Question>();
for(int i=0;i<temp.size();i++){
int a = temp.get(i).getGroup();
if((a==3||a==4||a==5||a==6||a==7))
if(temp.get(i).getCategory().contains(category)||temp.get(i).getCategory().equals("*"))
tempGroup.add(temp.get(i));
}
Collections.shuffle(tempGroup);
getQuestionsForSelectedGroup(tempGroup, numbersByGroup[2], pointsByGroup[2]);
if(category.equals("C")){
tempGroup = new ArrayList<Question>();
for(int i=0;i<temp.size();i++)
if(temp.get(i).getCategory().equals(category))
tempGroup.add(temp.get(i));
getQuestionsForSelectedGroup(tempGroup, 10, 30);
}
}
And here is what I try to do:
barProgressDialog = new ProgressDialog(this);
barProgressDialog.setTitle("Preparing Test");
barProgressDialog.setMessage("Preparing Test");
barProgressDialog.setProgressStyle(barProgressDialog.STYLE_HORIZONTAL);
barProgressDialog.setProgress(0);
barProgressDialog.setMax(100);
barProgressDialog.show();
new Thread(new Runnable() {
#Override
public void run() {
try {
getQuestionsForSelectedCategory();
while (barProgressDialog.getProgress() <= barProgressDialog.getMax()) {
updateBarHandler.post(new Runnable() {
public void run() {
barProgressDialog.incrementProgressBy(2);
}
});
if (barProgressDialog.getProgress() == barProgressDialog.getMax()) {
barProgressDialog.dismiss();
}
}
} catch (Exception e) {
}
}
}).start();
}
For the current code the progress bar fills up to 100 but it does nothing.
You could use an AsyncTask to achieve this, whilst publishing your progress during the task.
AsyncTask<Void, Integer, Void> task = new AsyncTask<Void, Integer, Void>() {
#Override
protected Void doInBackground(Void... voids) {
getQuestionsForSelectedCategory();
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
barProgressDialog.setProgress(values[0]);
}
#Override
protected void onPostExecute(Void aVoid) {
barProgressDialog.dismiss();
}
}
task.execute();
Ensure your getQuestionsForSelectedCategory and getQuestionsForSelectedGroup methods are inside the AsyncTask and within the loops you can call publishProgress(int progress) to update the progress dialog.

How to read Alert Dialog in separate thread in android?

I have an AlertDialog builder in class. I am setting some message into it which comes from reading a file. Earlier as file text wasn't too large it use to load easily, now since the text has grown more it takes a time to load dialog and blocks UI. How can i run this in thread ?
Edited code :
public class Eula TaskCompleteListner{ {
static interface OnEulaAgreedTo {
void onEulaAgreedTo();
}
public static boolean show(final Activity activity,final Context context,final Boolean flag) {
final Preferences prefs = Preferences.getInstance();
Log.d(TAG, "insideEula");
if (!prefs.getEulaStatus(context)) {
final AlertDialog.Builder builder = new AlertDialog.Builder(
activity);
Log.d(TAG, "insideEulaLaunch");
builder.setTitle(R.string.eula_title);
builder.setCancelable(true);
builder.setPositiveButton(R.string.eula_accept,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
prefs.setEulaStatus(context, true);
if (activity instanceof OnEulaAgreedTo) {
((OnEulaAgreedTo) activity).onEulaAgreedTo();
}
}
});
builder.setNegativeButton(R.string.eula_refuse,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
refuse(activity);
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
refuse(activity);
}
});
MyAsync async= new MyAsync(activity, new TaskCompleteListner() {
public boolean onComplete(String result) {
builder.setMessage(data);
builder.create().show();
return false;
}
}) ;
MyAsync async= new MyAsync(this, activity) ;
async.excecute();
//builder.setMessage(readEula(activity)); //READING FILE AND SETTING HERE
//builder.create().show();
return false;
}
return true;
}
private static void refuse(Activity activity) {
activity.finish();
}
#Override
public boolean onComplete(String result) {
// TODO Auto-generated method stub
builder.setMessage(readEula(activity)); //READING FILE AND SETTING HERE
builder.create().show();
return false;
}
Async Task Class
public class MyAsync extends AsyncTask<Void, Void, String>{
public static final String ASSET_EULA = "EULA";
TaskCompleteListner taskCompleteListner;
Activity activity;
public interface TaskCompleteListner{
public boolean onComplete(String result);
}
public MyAsync(TaskCompleteListner taskCompleteListner,Activity activity) {
this.taskCompleteListner = taskCompleteListner;
this.activity=activity;
}
#Override
protected String doInBackground(Void... params) {
String data=(String)readEula(activity);
return data;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
taskCompleteListner.onComplete(result);
}
private static CharSequence readEula(Activity activity) { //READING FILE HERE
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(activity.getAssets().open(ASSET_EULA)));
String line;
StringBuilder buffer = new StringBuilder();
while ((line = in.readLine()) != null)
buffer.append(line).append('\n');
byte[] latin1 = buffer.toString().getBytes("ISO-8859-1");
return new String(latin1);
//return buffer;
} catch (IOException e) {
return "";
} finally {
closeStream(in);
}
}
private static void closeStream(Closeable stream) {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
// Ignore
}
}
}
}
You can use AsyncTask class, where you read your data in doInBackground() return the CharSequence and do the dialog.show() in onPostExecute().
EDIT:
heres what you can do,
create a class
private static class MyAsyncClass extends AsyncTask<Void,Void,CharSequence > {
Activity activity;
ProgressDialog dialog
public MyAsyncClass(Activity activity){
this.activity = activity;
}
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(activity);
dialog.setMessage("Reading data");
dialog.setCancelable(false);
dialog.show();
}
#Override
protected CharSequence doInBackground(Void... params) {
return readEula(activity);
}
protected void onPostExecute(CharSequence data) {
if(dialog!=null && dialog.isShowing())
dialog.dismiss();
final AlertDialog.Builder builder = new AlertDialog.Builder(
activity);
Log.d(TAG, "insideEulaLaunch");
builder.setTitle(R.string.eula_title);
builder.setCancelable(true);
builder.setPositiveButton(R.string.eula_accept,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
prefs.setEulaStatus(context, true);
if (activity instanceof OnEulaAgreedTo) {
((OnEulaAgreedTo) activity).onEulaAgreedTo();
}
}
});
builder.setNegativeButton(R.string.eula_refuse,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
refuse(activity);
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
refuse(activity);
}
});
builder.setMessage(data);
builder.create().show();
}
}
then call this class as,
if (!prefs.getEulaStatus(context)) {
MyAsyncClass myAsyncClass = new MyAsyncClass(activity);
myAsyncClass.execute();
}
Correction to your Edit:
in your Eula class,
change this,
MyAsync async= new MyAsync(activity, new TaskCompleteListner() {
public boolean onComplete(String result) {
builder.setMessage(data);
builder.create().show();
return false;
}
}) ;
MyAsync async= new MyAsync(this, activity) ;
async.excecute();
to this,
MyAsync async= new MyAsync(activity, new TaskCompleteListner() {
public boolean onComplete(String result) {
builder.setMessage(data);
builder.create().show();
return false;
}
}) ;
async.excecute();
in your Async class,
change your constructor to,
public MyAsync(Activity activity, TaskCompleteListner taskCompleteListner) {
this.taskCompleteListner = taskCompleteListner;
this.activity=activity;
}
Use this Async Class to get the text
public class MyAsync extends AsyncTask<Void, Void, String>{
TaskCompleteListner taskCompleteListner;
Activity activity;
public interface TaskCompleteListner{
public boolean onComplete(String result);
}
public MyAsync(TaskCompleteListner taskCompleteListner,Activity activity) {
this.taskCompleteListner = taskCompleteListner;
this.activity=activity;
}
#Override
protected String doInBackground(Void... params) {
String data=(String) readEula(activity);
return data;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
taskCompleteListner.onComplete(result);
}
private static CharSequence readEula(Activity activity) { //READING FILE HERE
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(activity.getAssets().open(ASSET_EULA)));
String line;
StringBuilder buffer = new StringBuilder();
while ((line = in.readLine()) != null)
buffer.append(line).append('\n');
byte[] latin1 = buffer.toString().getBytes("ISO-8859-1");
return new String(latin1);
//return buffer;
} catch (IOException e) {
return "";
} finally {
closeStream(in);
}
}
private static void closeStream(Closeable stream) {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
// Ignore
}
}
}
}
You can use this in your Eula class as follows:
if (!prefs.getEulaStatus(context)) {
MyAsync async= new MyAsync(activity,new TaskCompleteListner() {
#Override
public boolean onComplete(String result) {
//TODO show your alert dialog here. Result has the string needed
return false;
}
}) ;
}
Hope this helps.
If its just a dialog u need to show, you can use the Activity's following method:
public final void runOnUiThread (Runnable action)
AsyncTask would be a cleaner approach. However, this will save you the trouble of extra code if you are looking for a quick switch onto the main thread.
Async task will be the better approach.
1. Do your background operation (readEula(Activity activity)) in doInBackGround and
2. show dialog in onPostExecute method.
In another approach create thread and do your operation (readEula(act)) in it and use handler to communicate to this thread and show alert dialog in you activity only.

show progress dialog while loading data

I want to show a progress dialog while loading some data from remote server :
I'm using the following thread in order to get the data and it's working, but i'm not able to show the progress bar on the activity:
public class Request {
public String text ;
public boolean downloadText(String urlStr) {
final String url = urlStr;
new Thread () {
public void run() {
int BUFFER_SIZE = 2000;
InputStream in = null;
Message msg = Message.obtain();
msg.what=2;
try {
in = openHttpConnection(url);
InputStreamReader isr = new InputStreamReader(in);
int charRead;
text = "";
char[] inputBuffer = new char[BUFFER_SIZE];
while ((charRead = isr.read(inputBuffer))>0)
{
//---convert the chars to a String---
String readString =
String.copyValueOf(inputBuffer, 0, charRead);
text += readString;
inputBuffer = new char[BUFFER_SIZE];
}
Bundle b = new Bundle();
b.putString("text", text);
msg.setData(b);
in.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
would you please tell me how can i do it !!
create the class as below and just call the object of this class.
class MyTask extends AsyncTask<Void, Void, Void> {
ProgressDialog Asycdialog = new ProgressDialog(ActivityName.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
Asycdialog.setMessage("Loading...");
Asycdialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// do the task you want to do. This will be executed in background.
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Asycdialog.dismiss();
}
}
Use progressDialog
final ProgressDialog progress=ProgressDialog.show(youractivity.this,"","message");
new Thread()
{
public void run()
{
try{
youractivity.this.runOnUiThread(new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
// your code
}
});
}
catch(Exception e)
{
}
progress.dismiss();
}
}.start()
Also, note that if you want to use Toast, you should use runOnUiThread
If you do not want to change the structure of your code, you can use runOnUiThread or an Handler to show and dissmiss the progress dialog. Show it when the firs line of the run method is excuted and dismiss it in the finally block.
public void run() {
runOnUiThread(new Runnable() {
public void run(){
// show progress dialog
}
});
/// your code here
try {
} catch (IOException e) {
} finally {
runOnUiThread(new Runnable() {
public void run(){
// dismiss progress dialog
}
});
}
}
Create Progress Dialog in AsyncTask
private class YourAsyncTask extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... args) {
// do background work here
return null;
}
protected void onPostExecute(Void result) {
// do UI work here
}
}
pDialog = ProgressDialog.show(context, null, "Loading...", true);
pDialog.setCancelable(false);
new Thread() {
public void run() {
// handle the exception somehow, or do nothing
// run code on the UI thread
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
// do yor ui part here
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}.start();

Cancel asynctask download on backbutton press

This is my download class in which I used Asynctask.Everything works fine, when the file is downloaded fully,it shows 'file downloaded' and on 'ok' press goes back to previous activity.Now I wanted to cancel the asynctask(pls not that 'cancel asynctask' and not only the 'loading' dialogue)on back button press and go back to previous activity.How to do that?someone please help.Thanks in advance
public class Download extends Activity {
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private ProgressDialog mProgressDialog;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.down);
startDownload();
}
private void startDownload() {
String url = data.proj;
new DownloadFileAsync().execute(url);
}
private void showMsg() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Document is downloaded")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
//do things
Download.this.finish();
}
});
AlertDialog alert = builder.create();
alert.show();
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Downloading file..");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
class DownloadFileAsync extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected String doInBackground(String... aurl) {
int count;
try {
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
String fname;
fname = data.proj.substring( data.proj.lastIndexOf('/')+1, data.proj.length() );
InputStream input = new BufferedInputStream(url.openStream());
String path=Environment.getExternalStorageDirectory()
.toString() + File.separator;
OutputStream output = new FileOutputStream(path+fname);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress(""+(int)((total*100)/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {}
return null;
}
#Override
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC",progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
showMsg();
}
}}
Really old question, but it seems many people still face an issue in cancelling AsyncTasks. So, here goes...
You will need a field in your AsyncTask class (DownloadFileAsync) to store the View which is being used to cancel the task (a ProgressDialog here).
For ProgressDialog, when creating the dialog, pass true to setCancelable()
mProgressDialog.setCancelable(true);
To pass the view, change the call to the Task as follows:
new DownloadFileAsync(mProgressDialog).execute(url);
and inside our AsyncTask class, create a constructor which saves this value to a field and register an OnCancelListener to call cancel method of AsyncTask:
ProgressDialog mProgressDialog;
DownloadFileAsync(ProgressDialog progressDialog) {
mProgressDialog = progressDialog;
mprogressDialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
cancel(true);
}
});
}
In your while loop in doInBackground, add the following code inside the loop:
if (isCancelled()) {
outputStream.flush();
outputStream.close();
inputStream.close();
return null;
}
This way we are checking whether the task was cancelled, every once in a while, and if yes, we close open streams and stop running the task with return (return will be of type given for result of Task). Next, in onCancelled
#Override
protected void onCancelled (Integer fileSize) {
super.onCancelled(fileSize);
Log.d("TASK TAG", "Cancelled.");
//anything else you want to do after the task was cancelled, maybe delete the incomplete download.
}
this is how i did
public class downloadAllFeeds extends AsyncTask<Void, Void, Void>
implements OnCancelListener{
protected void onPreExecute() {
pDialog2.setCancelable(true);
pDialog2.setOnCancelListener(this);
}
#Override
public void onCancel(DialogInterface dialog) {
// TODO Auto-generated method stub
downloadAllFeeds.this.cancel(true);
Log.d("on click cancel true","true");
}
#Override
protected Void doInBackground(Void... params) {
if(isCancelled()==true){
//cancel true stop async
Log.d("cancel true","true");
}else{
//perform your task
}
}
this worked for me, i know this is very old question but it didnt have a answer so i thought i should share what i just now could implement :)

Categories

Resources