Confusion with background threads - android

I have two AsyncTasks, one is used to download xml file (DownloadTask), another is for parsing the file (ParseXMLTask).
There are two cases of using this tasks:
1) File doesn't exists > execute DownloadTask, onPostExecute > ParseXMLTask
2) File exists > execute only ParseXMLTask.
Everything is working, but the thing is, while performing the second case, there is a blocking the ui about 3 sec (black screen) that surely would make a user annoyed. This is absolutely confusing me, because the job in the second case seems to be easier.
So when I am testing my app, a situation is like that: I click on the button for the first time, file is being downloaded, saved on the sd card, parsed and finally opened. Then I go back and click on the button again. Now I see that lag while switching between activities.
Code:
Executing the tasks
private void downloadPack() {
if (packDownloaded) {
parseXML();
} else {
download = new DownloadFile(fileName, this, loadingBar);
download.execute(serverURL + fileName + ".xml");
}
}
private void parseXML() {
ParseXMLTask parseTask = new ParseXMLTask(this, this);
parseTask.execute(PATH + fileName + ".xml");
}
public void postDownload(File result) {
parseXML();
}
public void postParse() {
Intent packIntent = new Intent(this, PackActivity.class);
startActivity(packIntent);
}
ParseXMLTask.java
public class ParseXMLTask extends AsyncTask<String, Integer, Void> {
private Context context;
private XmlPullParser xpp;
private IPostParse iPostParse;
public ParseXMLTask(Context context, IPostParse iPostParse) {
this.context = context;
this.iPostParse = iPostParse;
}
#Override
protected Void doInBackground(String... params) {
File file = new File(params[0]);
/* doing the job */
}
#Override
protected void onPostExecute(Intent result) {
iPostParse.postParse(result);
}
}
DownloadFile.java
public class DownloadFile extends AsyncTask<String, Integer, File> {
private static final String PATH = Environment
.getExternalStorageDirectory().getPath() + "/.chgkgame/";;
private File dir;
private ProgressBar progressBar;
private String fileName;
private IPostDownload postDownload;
private boolean download;
public DownloadFile(String name, IPostDownload pDownload, ProgressBar pBar) {
progressBar = pBar;
fileName = name;
postDownload = pDownload;
}
#Override
protected File doInBackground(String... sUrl) {
URL url;
try {
url = new URL(sUrl[0]);
URLConnection urlConnection = url.openConnection();
urlConnection.connect();
int fileLength = urlConnection.getContentLength();
dir = new File(PATH + fileName + ".xml");
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(dir);
byte[] data = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return dir;
}
#Override
protected void onPostExecute(File result) {
if (postDownload != null) postDownload.postDownload(result);
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
if (progressBar != null) {
progressBar.setProgress(values[0]);
}
}
}

There is nothing wrong with the above.
The parsing is pretty fast that is why you only see the layout for a split second.
The black screen will be the PackActivity loading, check this activity for what is blocking the UI thread.
You could have also put LogCat messages in to show that the parsing has finished and onCreate of the next Activity is called.

Related

How to fix "download file store on google drive" error in android

I've made an app for downloading a pdf file from direct link to internal storage. When I try to download a direct link of google drive link it works fine, if the file is less than 3MB. But if the file is more than 3MB, it is not downloaded. Here is my code below:
public class MainActivity extends AppCompatActivity {
private final String Pdf_LINK =
("https://drive.google.com/uc?export=download&id=13mE9gCyTGmLrFOZqu6Lz-yz0mcfjGoJc");
private final String My_PDF ="my100.pdf";
private AppCompatSeekBar seekBar;
private PDFView pdfView;
private TextView txtView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pdfView = findViewById(R.id.pdfView);
txtView = findViewById(R.id.txtView);
initSeekar();
downloadpdf(My_PDF);
}
private void initSeekar(){
seekBar = findViewById(R.id.seeBar);
seekBar.getProgressDrawable().setColorFilter(Color.RED, PorterDuff.Mode.SRC_IN);
seekBar.getThumb().setColorFilter(Color.RED,PorterDuff.Mode.SRC_IN);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
int val = (progress * (seekBar.getWidth() - 3 * seekBar.getThumbOffset())) / seekBar.getMax();
txtView.setText("" + progress);
txtView.setX(seekBar.getX() + val + seekBar.getThumbOffset() / 2);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
private void downloadpdf(final String fileName) {
new AsyncTask<Void, Integer, Boolean>() {
#Override
protected Boolean doInBackground(Void... params) {return downloadpdf();}
#Nullable
private Boolean downloadpdf() {
try {
File file = getFileStreamPath(fileName);
if (file.exists())
return true;
try {
FileOutputStream fileOutputStream = openFileOutput(fileName, Context.MODE_PRIVATE);
URL u = new URL(Pdf_LINK);
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
InputStream input = new BufferedInputStream(u.openStream());
byte data[] = new byte[contentLength];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int) ((total * 100) / contentLength));
fileOutputStream.write(data, 0, count);
}
fileOutputStream.flush();
fileOutputStream.close();
input.close();
return true;
} catch (final Exception e) {
e.printStackTrace();
return false;
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
seekBar.setProgress(values[0]);
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
if (aBoolean) {
openPdf(fileName);
} else {
Toast.makeText(MainActivity.this, "Unable to download this file", Toast.LENGTH_SHORT).show();
}
}
}.execute();
}
private void openPdf(String fileName) {
try {
File file = getFileStreamPath(fileName);
Log.e("file", "file: " + file.getAbsolutePath());
seekBar.setVisibility(View.GONE);
pdfView.setVisibility(View.VISIBLE);
pdfView.fromFile(file)
.enableSwipe(true)
.swipeHorizontal(false)
.load();
} catch (Exception e) {
e.printStackTrace();
}
}
}
What is the error in this code? How can I solve this? If I try to download a pdf file from another site, it works well. But the problem is only, when trying to download from google drive. please help me.
I was able to download large public shareable files from google drive.
Use the URL:
https://drive.google.com/uc?id=<FILE_ID>&export=download
Replace <FILE_ID> with your shareable file ID.
I used the code in 'private class DownloadTask'
in this solution:
Download a file with Android, and showing the progress in a ProgressDialog
The code inside the doInBackground function works, I modified it for my own needs, used ProgressBar instead. I am not posting my code since it's too long.
Hope you can solve your problem.

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
}

Will AsyncTask crash if I call it over 100 times in a loop?

I am getting a list of files from a web service and then using AsyncTask to handle the download of all files. Each task is created in a loop:
for(int i = 0; i < arraySize; i++) {
//Omitted all code except for the portion that fires the asynctask
//Download the PDF
DownloadHandler dhpdf = new DownloadHandler(cleanLink, fileName, p1, DownloadPosters.this, "pdf");
dhpdf.startDownload();
//Download the PNG
DownloadHandler dhpng = new DownloadHandler(cleanLink, fileName, p1, DownloadPosters.this, "png");
dhpng.startDownload();
}
The Download class
public class DownloadHandler extends Activity {
private Context mContext;
//File ======================
public String filename;
private String remotePath;
private File file;
private String ext;
//Progress bar ==============
private ProgressBar progressBar;
private int progressStatus = 0;
//private Handler handler = new Handler();
private TextView mTextView;
//ProgressDialog ============
ProgressDialog mProgress;
private int mProgressDialog=0;
public DownloadHandler(String rp, String f, ProgressBar progressBar, Context c, String extension, TextView textview) throws Exception {
mContext = c;
remotePath = rp;
filename = f;
file = new File(mContext.getFilesDir(), filename+"."+extension);
ext = extension;
this.progressBar = progressBar;
mTextView = textview;
}
//our method
public void startDownload() {
String url = "http://examplesite.com/"+remotePath+"/"+filename+"."+ext;
new DownloadFileAsync().execute(url);
}
class DownloadFileAsync extends AsyncTask<String, Integer, String> {
#Override
public void onPreExecute() {
}
#Override
protected void onProgressUpdate(Integer... values) {
progressBar.setProgress(values[0]);
mTextView.setText("Downloading: "+ext);
}
#Override
protected String doInBackground(String... aurl) {
int count;
try {
URL url = new URL(aurl[0]);
URLConnection conection = url.openConnection();
conection.connect();
// Get Music file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(),10*1024);
// Output stream to write file in internal storage
OutputStream output = new BufferedOutputStream(new FileOutputStream(file));
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// Publish the progress which triggers onProgressUpdate method
publishProgress((int) ((total * 100) / lenghtOfFile));
// Write data to file
output.write(data, 0, count);
}
// Flush output
output.flush();
// Close streams
output.close();
input.close();
} catch (Exception e) {mTextView.setText("ERROR:"+e.toString());}
return null;
}
#Override
protected void onPostExecute(String unused) {
mTextView.setText("Complete");
}
}
Right now I am only able to test about 6 files and it seems to be working well.
My question is if this is the proper way to que up multiple downloads and can this handle 100+ files at a time without crashing?
Why not using an Android Download Manager ? You can queue all of your download requests, and it's a service, it will work in the background. It also checks your connection, resumes downloads when the connection is gone and re established.
For more information and a quick start, check this tutorial. It should help. Vogella Blog
No 100 should not be a problem, but you should also not be doing 100 paralel uploads - that's not going to work too well (technically it shall work but in terms of performance it's wrong approach). I'd queue them and push one by one.
Please note that depending on Android version, AsyncTask will work differently when called in default "form" (new xxTask.execute()`) - on older version if will go parallel, on never it will go one by one. Ensure you do this always the same.
Finally, if you really know you going to have 100 uploads fired, then I'd sit down and rework your app's architecture - you definitely got some things very wrong there.

Android: FTP client file transfer in passive mode taking time to close connection after 100% upload

Android: FTP client file transfer in passive mode taking time to close connection after 100% upload
While transferring files through FTP client, in passive mode, we are using async task.
Even after the progress update specified 100% of the file has been uploaded, still ftp connection holds async task from coming to on post execute.
The time taken is directly proportional to Internet speed and size of the file uploaded.
Tried with standalone application to upload zip files,
Tried ftp both in active and passive modes.
Still the issue persists.
public class UploadZipFiles extends AsyncTask<Object, Integer, Object> {
ArrayList<String> zipFiles;
String userName, password;
WeakReference<ServiceStatusListener> listenerReference;
private Context mContext;
private long totalFileSize = 0;
protected long totalTransferedBytes = 0;
final NumberFormat nf = NumberFormat.getInstance();
private CustomFtpClient ftpClient = null;
public UploadZipFiles(Context mContext, ServiceStatusListener listener,
ArrayList<String> zipFiles, String userName, String password) {
Log.d("u and p", "" + userName + "=" + password);
this.mContext = mContext;
this.zipFiles = zipFiles;
this.userName = userName;
this.password = password;
this.listenerReference = new WeakReference<ServiceStatusListener>(
listener);
nf.setMinimumFractionDigits(2);
nf.setMaximumFractionDigits(2);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// getting total size of the file
for (String file : zipFiles) {
totalFileSize = totalFileSize + new File(file).length();
}
}
#Override
protected Object doInBackground(Object... arg0) {
ftpClient = new CustomFtpClient();
try {
ftpClient.connect(ftpUrl, 21);
ftpClient.login(userName, password);
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
for (String file : zipFiles) {
InputStream in;
in = new FileInputStream(new File(file));
ftpClient.storeFile(new File(file).getName(), in);
in.close();
}
} catch (IOException e1) {
e1.printStackTrace();
}
return "Success";
}
#Override
protected void onPostExecute(Object result) {
if (result instanceof Exception) {
listenerReference.get().onFailure(
new Exception(result.toString()));
} else {
listenerReference.get().onSuccess("Success");
}
}
#Override
protected void onProgressUpdate(Integer... values) {
int uploadProgress = ((float) values[0] / totalFileSize) * 100);
//Some code to show loader
.......
}
/** Custom client to publish progress **/
public class CustomFtpClient extends FTPClient {
public boolean storeFile(String remote, InputStream local)
throws IOException {
final OutputStream output;
final Socket socket;
if ((socket = _openDataConnection_(FTPCommand.STOR, remote)) == null)
return false;
output = new BufferedOutputStream(socket.getOutputStream(),
getBufferSize());
try {
Util.copyStream(local, output, getBufferSize(),
CopyStreamEvent.UNKNOWN_STREAM_SIZE,
new CopyStreamListener() {
#Override
public void bytesTransferred(
long totalBytesTransferred,
int bytesTransferred, long streamSize) {
totalTransferedBytes = totalTransferedBytes
+ bytesTransferred;
publishProgress((int) totalTransferedBytes);
if (totalTransferedBytes == totalFileSize) {
Log.d(TAG, "upload completed");
}
}
#Override
public void bytesTransferred(
CopyStreamEvent arg0) {
// TODO Auto-generated method stub
}
});
} catch (IOException e) {
try {
socket.close();
} catch (IOException f) {
}
throw e; }
output.close();
socket.close();
return completePendingCommand();
}
}
}

How to add progress bar to standalone Asynctask?

I have an asynctask that is in its own activity. I pass it a string value and it connects to my web service and downloads Json data based on the name I pass in, returning the Json resultset. Works great.
I'd like to add a progress spinner to the asynctask, but I'm stymied as to how to do it. I've perused this and many other blogs, and come close but have not yet found the solution. It seems I either need to have the asynctask in with an Activity class to get the context or I have to pass in the context as a parameter -- but I need the input parameter to be String. I've read about the possibility of building an Object that could hold the String and a Context parameter, but I'm very new to Java and don't know how to build something like that nor have I found a good explanation of how to do so. So often an explanation gets right up to what I need and then says, "... and then you do X and that's it," when X is what I need to know.
All I want is just a spinner thingie to whirl while the download happens. No text, no dialog, just a spinner.
class MyTask extends AsyncTask<Request, Void, Result> {
protected ProgressDialog progressDialog;
#Override
protected void onPreExecute()
{
super.onPreExecute();
progressDialog = ProgressDialog.show(YourActivity.this, "", "", true, false);
}
#Override protected Boolean doInBackground(Request... params) {
// do some work here
return true;
}
#Override protected void onPostExecute(Result res) {
progressDialog.dismiss();
}
}
Add a ProgressBar(this is what it's actually called, Spinners are like drop down menus in Android) to the layout of the Activity where you're initializing your AsyncTask.
Then make two functions startProgress() and stopProgress(), which start and stop the progress bar.
Give your AsyncTask a reference to the Activity, either by sending it during initialization or execution, or making a function in your asyncTask setActivity(MyActivity activity) and call it between your AsyncTask initialization and execution.
Override the onPreExecute() of your AsyncTask to call activity.startProgress() and onPostExecute() to call activity.stopProgress().
EDIT: You can also try passing a reference to the ProgressBar in the constructor of your AsyncTask. Get the reference to the ProgressBar in the onCreate() method of your activity, then add it in the AsyncTask constructor. In the onPreExecute() and onPostExecute() methods of the AsyncTask, start and stop the progress bars accordingly.
You can pass various parameters to an AsyncTask, not just one!
One way to do this is to make member variables in your AsyncTask and initialize them using a constructor that accepts parameters.
For example:
private class MyAsyncTask extends AsyncTask<null, null, null> {
String mFirstParam = null;
Context mContext = null;
// Constructor which accepts parameters
public MyAsyncTask(String _firstParam, Context _context){
this.mFirstParam = _firstParam;
this.mContext = _context;
}
}
When you create an instance of your AsyncTask, create it as follows:
MyAsyncTask task = new MyAsyncTask(myFirstStringParam, mySecondContextParam);
task.execute();
Now you can use both these parameters throughout the scope of your AsyncTask.
Consider passing the ImageView containing of "loading" image and set its Visibility to View.GONE once you have finished downloading your data.
i.e. download your data in the doInBackground method and then change the ImageViews visibility to View.GONE in the onPostExecute method
I think you can pass the progress bar instance to AsyncTask when your create it in its constructor. Here is a downloader example by using AsyncTask -
public void downloadFile(String url, String path, ProgressDialog progress) {
DownloadFileAsync downloader = new DownloadFileAsync(progress);
File file = new File(path);
if (file.exists()) {
file.delete();
}
downloader.execute(url, path);
}
class DownloadFileAsync extends AsyncTask<String, String, String> {
private final WeakReference<ProgressDialog> progressbarReference;
public DownloadFileAsync(ProgressDialog progress) {
progressbarReference = new WeakReference<ProgressDialog>(progress);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#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();
/*
* android.util.Log.v("downloadFile", "Lenght of file: " +
* lenghtOfFile + ":" + aurl[1]);
*/
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(aurl[1]);
try {
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);
}
} finally {
if (output != null) {
output.flush();
output.close();
}
if (input != null) {
input.close();
}
}
} catch (Exception e) {
ProgressDialog p = null;
if (progressbarReference != null) {
p = progressbarReference.get();
}
if (p != null && p.isShowing()) {
p.dismiss();
}
}
return null;
}
protected void onProgressUpdate(String... progress) {
if (progressbarReference != null) {
ProgressDialog p = progressbarReference.get();
if (p != null) {
p.setProgress(Integer.parseInt(progress[0]));
}
}
}
#Override
protected void onPostExecute(String unused) {
ProgressDialog p = null;
if (progressbarReference != null) {
p = progressbarReference.get();
}
if (p != null && p.isShowing()) {
p.dismiss();
}
}
}
ProgressDialog is a custom Dialog which have a progress bar inside it.
Hope it helps.

Categories

Resources