Cancel asynctask download on backbutton press - android

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 :)

Related

ProgressDialog inside AsyncTask not showing progress [duplicate]

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();
}

How to do a progress bar to show progress download of a big file with AndroidAnnotations?

I have an Android App and I want to download a big file.
REST API implementation is made with AndroidAnnotations. I need to show a progressbar with the download of a big file using this REST Client (made by AndroidAnnotations).
How I to do that?
Regards
Hello Its to late for answering this question but this will be helpful who are still finding ans with Android-annotation
You can check your image progress by little bit manipulation of code and here is what i have created my
Custom converter Class:-
public class CustomConverter extends FormHttpMessageConverter {
OnProgressListener mOnProgressListener;
public CustomConverter() {
super();
List<HttpMessageConverter<?>> partConverters = new ArrayList<HttpMessageConverter<?>>();
partConverters.add(new ByteArrayHttpMessageConverter());
StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter();
stringHttpMessageConverter.setWriteAcceptCharset(false);
partConverters.add(stringHttpMessageConverter);
partConverters.add(new ProgressResourceHttpMessageConverter());
setPartConverters(partConverters);
}
// public ProgressFormHttpMessageConverter setOnProgressListener(OnProgressListener listener) {
// mOnProgressListener = listener;
// return this;
// }
class ProgressResourceHttpMessageConverter extends ResourceHttpMessageConverter {
#Override
protected void writeInternal(Resource resource, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
InputStream inputStream = resource.getInputStream();
OutputStream outputStream = outputMessage.getBody();
byte[] buffer = new byte[2048];
long contentLength = resource.contentLength();
int byteCount = 0;
int bytesRead = -1;
Log.d("<3 <3 <3", "called");
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
byteCount += bytesRead;
Log.d("<3 <3 <3 ** ", "progress" + String.valueOf((byteCount * 100) / contentLength));
if(mOnProgressListener != null) {
mOnProgressListener.onProgress(resource, byteCount, (int) contentLength);
}
}
outputStream.flush();
}
}
public interface OnProgressListener {
void onProgress(Resource resource, int downloaded, int downloadSize);
}
}
--> you can check your progress with log :)
Code Usage
-> Your rest class will be as follow:-
#Rest(rootUrl = CommonUtils.BASE_URL, converters = {ByteArrayHttpMessageConverter.class,
CustomConverter.class, StringHttpMessageConverter.class})
public interface CustomRest extends RestClientErrorHandling {
#Post(pUrlSignUp)
String _SignUp(MultiValueMap<String, Object> multiValueMap);
}
Of course, you will have to use AsyncTask for downloading purpose:
You can use its methods onPreExecute and onPostExecute for showing and dismissing the ProgressDialog respectively.
Example:
public class DownloadTask extends AsyncTask<String, Integer, String>
{
ProgressDialog pDialog;
Activity activity; //pass your activity reference while initialize this.
public DownloadTask (Activity activity){
this.activity = activity;
}
#Override
protected void onPreExecute()
{
pDialog = new ProgressDialog(activity);
pDialog.setMessage("Downloading file...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... args)
{
//download file's code here
}
#Override
protected void onPostExecute(String result)
{
pDialog.dismiss();
}
}
Hope this helps.
> use AsyncTask method "on progressupdate " to show progress
public class download extends Activity {
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private Button startBtn;
private ProgressDialog mProgressDialog;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startBtn = (Button)findViewById(R.id.startBtn);
startBtn.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
startDownload();
}
});
}
private void startDownload() {
String url = "http://farm1.static.flickr.com/114/298125983_0e4bf66782_b.jpg";
new DownloadFileAsync().execute(url);
}
#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 {
#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);
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/some_photo_from_gdansk_poland.jpg");
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;
}
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);
}
}
}
With AndroidAnnotations, you can use background threads and publishing progress easily:
#EActivity
public class MyActivity extends Activity {
public void onCreate(Bundle icicle) {
super.onCreate(icicle)
doSomeStuffInBackground();
}
#Background
void doSomeStuffInBackground() { // will run on a background thread
publishProgress(0);
// Do some stuff
publishProgress(10);
// Do some stuff
publishProgress(100);
}
#UiThread
void publishProgress(int progress) { // will run on the UI thread
// Update progress views
}
}
Now you can only have to figure out how you can get progress events. This answer can give a great inspiration. Unfortunetaly AFAIK there is no built-in callback for that in Spring Android Rest Template.
I was looking to solve this same problem, its being two months now. Finally found a good example, I cant believe everybody copy paste the same in AndroidAnnotations docs, if that were enough, we wouldnt be here seeking for help.
Here is the link where you can see the example
I made some modifications my self, for the moment its working with some toasts, but I hope to comeback with an actual loading animation to share:
/*This background handles my main thread in UI and the progress publish*/
#Background
void thisGETJSON() {
publishProgress(0);
publishProgress(50);
publishProgress(100);
showJSONInUI();
}
/*Here the progress is published and the main UI thread is also called*/
#UiThread
void publishProgress(int progress) {
if (progress == 0) {
Toast toast = Toast.makeText(getApplicationContext(), "Just a sec please", Toast.LENGTH_SHORT);
toast.show();
} else if (progress == 50) {
Toast toast = Toast.makeText(getApplicationContext(), "Loading", Toast.LENGTH_SHORT);
toast.show();
} else if (progress == 100) {
Toast toast = Toast.makeText(getApplicationContext(), "Thanks for waiting", Toast.LENGTH_SHORT);
toast.show();
}
/*This is the main UI thread here I do cool stuff with the JSON objects*/
#UiThread
Void showJSONInUI(); {
//Here I do something with the objects in the JSON
}

Progress Dialog only shows up when the job is already done

I have a problem which I don't understand. I want to show a simple Progress Dialog in Android. So I created an AsyncTask and create the dialog in the constructor. I use the methods onPreExceution to initialise the dialog and the onPostExecute method I destory the dialog. So until now this looks total correct for me. But when I start the App on my Nexus 7 the dialog doesn't show up till the job is done. So it shows up for a half of a second at the end of the job... What am I doing wrong?
Thank you for your help ;)
public class ParseHTMLCodeNew extends AsyncTask<String, Void, String> {
ProgressDialog dialog;
public ParseHTMLCodeNew(Context context) {
dialog = new ProgressDialog(context);
}
#Override
protected void onPreExecute() {
//einrichten des Wartedialogs
dialog.setTitle("Bitte warten!");
dialog.setMessage("Die Kommentare werden vom Server geladen.");
dialog.show();
}
#Override
protected String doInBackground(String params) {
InputStream is = null;
String data = "";
try
{
URL url = new URL( params[0] );
is = url.openStream();
data = new Scanner(is).useDelimiter("//html//").next();
}
catch ( Exception e ) {
e.printStackTrace();
}
return data;
}
#Override
protected void onPostExecute(String result) {
//Dialog beenden RSS Feed ist fertig geparst
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
}
}
UPDATE
This is my new AsyncTask:
public class ParseHTMLCodeNew extends AsyncTask<String, String, String> {
ProgressDialog dialog;
private final OnCompleteTaskListener onCompleteTaskListener;
public interface OnCompleteTaskListener {
void onComplete(String data);
}
public ParseHTMLCodeNew(Context context, OnCompleteTaskListener taskListener) {
onCompleteTaskListener = taskListener;
dialog = new ProgressDialog(context);
}
#Override
protected void onPreExecute() {
//einrichten des Wartedialogs
dialog.setTitle("Bitte warten!");
dialog.setMessage("Die Kommentare werden vom Server geladen.");
dialog.show();
}
#Override
protected String doInBackground(String... params) {
InputStream is = null;
String data = "";
try
{
URL url = new URL( params[0] );
is = url.openStream();
data = new Scanner(is).useDelimiter("//html//").next();
}
catch ( Exception e ) {
e.printStackTrace();
}
return data;
}
#Override
protected void onPostExecute(String result){
onCompleteTaskListener.onComplete(result);
//Dialog beenden RSS Feed ist fertig geparst
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
}
}
And i am calling it this way:
new ParseHTMLCodeNew(this,new OnCompleteTaskListener() {
#Override
public void onComplete(String data) {
gData = data;
}
}).execute(url);
As i commented on your post, data has no value.
If you calling this code so:
String data = new ParseHTMLCodeNew(CommentActivity.this).execute(url).get();
Then you do not really see your dialogue because there is a blocking UI.
Method get() waits if necessary for the computation to complete, and then retrieves its result.
Call so:
new ParseHTMLCodeNew(CommentActivity.this).execute(url);
and the result of the work is handled directly in the AsyncTask.
If you need to transfer the data to the main thread, you should tell him that the task was completed.
Wat is the simple code, I just added OnCompleteTaskListener interface
public class ParseHTMLCodeNew extends AsyncTask<String, Void, String> {
private final OnCompleteTaskListener onCompleteTaskListener;
private ProgressDialog dialog;
public interface OnCompleteTaskListener {
void onComplete(String data);
}
public ParseHTMLCodeNew(Context context, OnCompleteTaskListener taskListener) {
onCompleteTaskListener = taskListener;
dialog = new ProgressDialog(context);
}
#Override
protected void onPreExecute() {
// einrichten des Wartedialogs
dialog.setTitle("Bitte warten!");
dialog.setMessage("Die Kommentare werden vom Server geladen.");
dialog.show();
}
#Override
protected String doInBackground(String... params) {
StringBuilder sb = new StringBuilder();
// your code here
try {
for (int i = 0; i < 100; i++) {
Thread.sleep(100);
sb.append(i);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
return sb.toString();
}
#Override
protected void onPostExecute(String result) {
// Dialog beenden RSS Feed ist fertig geparst
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
onCompleteTaskListener.onComplete(result);
}
}
And the example of a call
new ParseHTMLCodeNew(this,new OnCompleteTaskListener() {
#Override
public void onComplete(String data) {
Toast.makeText(CommentActivity.this, data, Toast.LENGTH_LONG).show();
}
}).execute("your_url");
Be careful, this code can produce errors when you rotate your Phone.
When Activity destroyed but task is performed:
- progress dialog will close and will not open again
- local variable to dialog or context is incorrect.
If the operation is performed for a long time can make it through the of the services?
I've wrote a code that get data from online database and populate that data in lisview here is the part of my code hope that help !
class LoadMyData extends AsyncTask<String, String, String> {
//Before starting background thread Show Progress Dialog
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getParent());
pDialog.setMessage("Loading. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
//Your code here
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting the data
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
// In my case use my adapter to display the data in a listview
adapter = new MyAdaper();
list.setAdapter(adapter);
}
});
}
}
Progress dialog should be shown from UI thread
runOnUiThread(new Runnable() {
public void run() {
dialog.setTitle("Bitte warten!");
dialog.setMessage("Die Kommentare werden vom Server geladen.");
dialog.show();
}});

How can I add a progress dialog in AsyncTask with minimum loading time (2sec)

When user clicks button, will go to Activity B from Activity A.
However, since in Activity B, data will be downloaded from Internet, I would like to add a progress dialog.
Sometimes, the connection will be very fast, less than one second and sometimes will be more than 5 seconds.
If the progress dialog shows <1 sec, I think it is very bad for user experience.
So, I would like to add a minimum loading time, for example, 2 seconds.
That means even the loading time is less than 2 seconds, the progress dialog will also at least show 2 seconds.
Is there any ways to do so?
you can use Below Code. Pass Time and Object of your Dialog here.
public void timerDelayRemoveDialog(long time, final Dialog d){
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
d.dismiss();
}
}, time);
}
EDITED
you can Use this Sample Code :
class LoginProgressTask extends AsyncTask<String, Integer, Boolean> {
#Override
protected Boolean doInBackground(String... params) {
try {
Thread.sleep(4000); // Do your real work here
} catch (InterruptedException e) {
e.printStackTrace();
}
return Boolean.TRUE; // Return your real result here
}
#Override
protected void onPreExecute() {
showDialog(AUTHORIZING_DIALOG);
}
#Override
protected void onPostExecute(Boolean result) {
// result is the value returned from doInBackground
removeDialog(AUTHORIZING_DIALOG);
Intent i = new Intent(HelloAndroid.this, LandingActivity.class);
startActivity(i);
}
}
My solution (worked well):
private class ProgressTask extends AsyncTask<Void, Void, Void> {
ProgressDialog dialog;
long timestamp1;
long timestamp2;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(YOUR_CONTEXT);
dialog.setCancelable(false);
dialog.setMessage("Please wait...");
dialog.show();
timestamp1 = System.currentTimeMillis();
}
#Override
protected Void doInBackground(Void... params) {
//doSomething ...
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
//doSomething ...
timestamp2 = System.currentTimeMillis();
long timeDifference = timestamp2 - timestamp1;
if (timeDifference >= 2000) {
dialog.dismiss();
} else {
Handler h = new Handler();
h.postDelayed(new Runnable() {
public void run() {
dialog.dismiss();
}
}, 2000 - timeDifference);
}
}
}
Here is another version. Using SystemClock does not require try catch block.
ParentActivity.this is the context where Task is executed.
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.SystemClock;
protected class Task extends AsyncTask< String, Void, String >
{
private ProgressDialog mDialog = new ProgressDialog( ParentActivity.this );
private long mTaskStartTimeMills;
protected void onPreExecute()
{
mTaskStartTimeMills = System.currentTimeMillis();
mDialog.setMessage( "Loading.." );
mDialog.show();
}
protected String doInBackground( String... arg )
{
// TODO
return null;
}
protected void onPostExecute( String json )
{
final long timeToWait = 1000 - ( System.currentTimeMillis() - mTaskStartTimeMills );
if ( timeToWait > 0 )
{
SystemClock.sleep( timeToWait );
}
mDialog.dismiss();
}
}
this may helps you
new AsyncTask<Void, Void, Void>() {
ProgressDialog mDialog;
ArrayList<String> files;
#Override
protected void onPreExecute() {
mDialog = new ProgressDialog(MyMainAct.this);
mDialog.setMessage("Loading");
mDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
// do your work here
Log.i("Share Media MyMainAct", " newFiles is called path is - " + path +"/" + spndirectory.getSelectedItem().toString());
files = getFiles(path + "/" + spndirectory.getSelectedItem().toString());
return null;
}
#Override
protected void onPostExecute(Void result){
if (mDialog != null && mDialog.isShowing()){
mDialog.dismiss();
}
setFileAdapter(files);
}
}.execute();

Android async task download failed err

I've developed an application that takes content from the internet and shows it accordingly on the device's screen . The program works just fine , a little bit slow . It takes about 3-4 seconds to load and display the content . I would like to put my code that does all the work ( grabbing web content and displaying it) in a background thread . Also , I'd like to show a progress dialog .
public class Activity1 extends Activity
{
private ProgressDialog progressDialog;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new AsyncTask<Integer, Integer, Boolean>()
{
ProgressDialog progressDialog;
#Override
protected void onPreExecute()
{
/*
* This is executed on UI thread before doInBackground(). It is
* the perfect place to show the progress dialog.
*/
progressDialog = ProgressDialog.show(Activity1.this, "",
"Loading...");
}
#Override
protected Boolean doInBackground(Integer... params)
{
if (params == null)
{
return false;
}
try
{
/*
* This is run on a background thread, so we can sleep here
* or do whatever we want without blocking UI thread. A more
* advanced use would download chunks of fixed size and call
* publishProgress();
*/
Thread.sleep(params[0]);
// HERE I'VE PUT ALL THE FUNCTIONS THAT WORK FOR ME
}
catch (Exception e)
{
Log.e("tag", e.getMessage());
/*
* The task failed
*/
return false;
}
/*
* The task succeeded
*/
return true;
}
#Override
protected void onPostExecute(Boolean result)
{
progressDialog.dismiss();
/*
* Update here your view objects with content from download. It
* is save to dismiss dialogs, update views, etc., since we are
* working on UI thread.
*/
AlertDialog.Builder b = new AlertDialog.Builder(Activity1.this);
b.setTitle(android.R.string.dialog_alert_title);
if (result)
{
b.setMessage("Download succeeded");
}
else
{
b.setMessage("Download failed");
}
b.setPositiveButton(getString(android.R.string.ok),
new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dlg, int arg1)
{
dlg.dismiss();
}
});
b.create().show();
}
}.execute(2000);
/* new Thread()
{
#Override
public void run()
{
// dismiss the progressdialog
progressDialog.dismiss();
}
}.start();
}*/
}
If I run the application with this code , I get this : download failed . On the other hand , if I keep the final thread , the app crashes , NullPointerException . I really don't know what to do anymore .
I would really appreaciate if you could give me an alternative to this code , not just some hints because I'm new to android and I really don't know much . Thanks.
UPDATE :
I don't want to display the progress of the download , I want to display the progress dialog until the app is ready to display the full content.
The best approach to do this is by using the AsyncTask class, as it will allow you to execute some background process and update the UI at the same time (in your case, it's a progress bar).
This is an example code:
ProgressDialog mProgressDialog = new ProgressDialog(YourActivity.this);
mProgressDialog.setMessage("A message");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
DownloadFile downloadFile = new DownloadFile();
downloadFile.execute("the url to the file you want to download");
The AsyncTask will look like this:
private class DownloadFile extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... url) {
int count;
try {
URL url = new URL(url[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
// this will be useful so that you can show a tipical 0-100% progress bar
int lenghtOfFile = conexion.getContentLength();
// downlod the file
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/somewhere/nameofthefile.ext");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
publishProgress((int)(total*100/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {}
return null;
}
The method above (doInBackground) runs always on a background thread. You shouldn't do any UI tasks there. On the other hand, the onProgressUpdate runs on the UI thread, so there you will change the progress bar:
#Override
public void onProgressUpdate(String... args){
// here you will have to update the progressbar
// with something like
mProgressDialog.setProgress(args[0]);
}
}
You will also want to override the onPostExecute method if you want to execute some code once the file has been downloaded completely.
You should create an inner class for AsyncTask like this :
private class YourTask extends AsyncTask<Context, Void, Void>
{
ProgressDialog dialog = new ProgressDialog(mContext);
protected void onPreExecute()
{
dialog.setMessage("loading..");
dialog.show();
}
protected Void doInBackground(Context... params)
{
// ...
return null;
}
protected void onPostExecute(final Void unused)
{
dialog.dismiss();
}
}
and in onCreate() put :
new YourTask().execute();
and for more detail you should check this once:
http://developer.android.com/reference/android/os/AsyncTask.html
When you use the new thread, your app crashes because the progress dialog is not initialized there
Inside your new thread use:
`progressDialog = ProgressDialog.show(Activity1.this, "","Loading...");
and about that alert dialog: Basically either params is null or the logic is throwing some exception. It's not returning true
so check the ddms logs and post them here.
`

Categories

Resources