Downloading Images with progress bar and displaying them in grid view - android

I am new to Android and Java.
I have URL of 36 images.
I want to download all those images and display them in grid view.
I'm referring the code below, So please if some one can edit this code to download multiple images. and display in grid view.
The Below code is just taking one URL and downloading image from that
URL.
package com.example.androidhive;
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class AndroidDownloadFileByProgressBarActivity extends Activity {
// button to show progress dialog
Button btnShowProgress;
// Progress Dialog
private ProgressDialog pDialog;
ImageView my_image;
// Progress dialog type (0 - for Horizontal progress bar)
public static final int progress_bar_type = 0;
// File url to download
private static String file_url = "http://api.androidhive.info/progressdialog/hive.jpg";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// show progress bar button
btnShowProgress = (Button) findViewById(R.id.btnProgressBar);
// Image view to show image after downloading
my_image = (ImageView) findViewById(R.id.my_image);
/**
* Show Progress bar click event
* */
btnShowProgress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// starting new Async Task
new DownloadFileFromURL().execute(file_url);
}
});
}
/**
* Showing Dialog
* */
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type: // we set this to 0
pDialog = new ProgressDialog(this);
pDialog.setMessage("Downloading file. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(true);
pDialog.show();
return pDialog;
default:
return null;
}
}
/**
* Background Async Task to download file
* */
class DownloadFileFromURL extends AsyncTask<String, String, String> {
/**
* Before starting background thread
* Show Progress Bar Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
/**
* Downloading file in background thread
* */
#Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// this will be useful so that you can show a tipical 0-100% progress bar
int lenghtOfFile = conection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream(), 8192);
// Output stream
OutputStream output = new FileOutputStream("/sdcard/downloadedfile.jpg");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress(""+(int)((total*100)/lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
/**
* Updating progress bar
* */
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialog.setProgress(Integer.parseInt(progress[0]));
}
/**
* After completing background task
* Dismiss the progress dialog
* **/
#Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
dismissDialog(progress_bar_type);
// Displaying downloaded image into image view
// Reading image path from sdcard
String imagePath = Environment.getExternalStorageDirectory().toString() + "/downloadedfile.jpg";
// setting downloaded into image view
my_image.setImageDrawable(Drawable.createFromPath(imagePath));
}
}
}
Please HELP

i think you should use Universal image loader for display image in gridview.it works perfect!!!

Related

How to run progress bar in background?

I am try to create progress bar in background by using asynkTask.I am downlroading file from server and show the progress of file downloading by using progress bar this is working fine.
For creating this progressbar i am refer this link.
My code :
package com.example.androidhive;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
public class AndroidDownloadFileByProgressBarActivity extends Activity {
// button to show progress dialog
Button btnShowProgress;
// Progress Dialog
private ProgressDialog pDialog;
ImageView my_image;
// Progress dialog type (0 - for Horizontal progress bar)
public static final int progress_bar_type = 0;
String file = Environment.getExternalStorageDirectory()+"/MyAudio";
ProgressBar progressBar;
// File url to download
private static String file_url = "my url";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// show progress bar button
btnShowProgress = (Button) findViewById(R.id.btnProgressBar);
// Image view to show image after downloading
my_image = (ImageView) findViewById(R.id.my_image);
File f = new File(file);
if (!f.exists()) {
f.mkdirs();
} else {
// f.delete();
}
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
/**
* Show Progress bar click event
* */
btnShowProgress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// starting new Async Task
if (progressBar.getVisibility() != View.VISIBLE) {
progressBar.setVisibility(View.VISIBLE);
}
new DownloadFileFromURL().execute(file_url);
}
});
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
/**
* Showing Dialog
* */
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type:
pDialog = new ProgressDialog(this);
pDialog.setMessage("Downloading file. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(true);
pDialog.show();
return pDialog;
default:
return null;
}
}
/**
* Background Async Task to download file
* */
class DownloadFileFromURL extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Bar Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
// showDialog(progress_bar_type);
}
/**
* Downloading file in background thread
* */
#Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(),
8192);
// Output stream to write file
// OutputStream output = new
// FileOutputStream("/sdcard/Audio/downloadedfile.jpg");
OutputStream output = new FileOutputStream(file+
"audio.zip");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
/**
* Updating progress bar
* */
protected void onProgressUpdate(String... progress) {
// setting progress percentage
// pDialog.setProgress(Integer.parseInt(progress[0]));
progressBar.setProgress(Integer.parseInt(progress[0]));
}
/**
* After completing background task Dismiss the progress dialog
* **/
#Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
// dismissDialog(progress_bar_type);
if (progressBar.getVisibility() != View.VISIBLE) {
progressBar.setVisibility(View.VISIBLE);
}
// Displaying downloaded image into image view
// Reading image path from sdcard
String imagePath = Environment.getExternalStorageDirectory()
.toString() + "/downloadedfile.jpg";
// setting downloaded into image view
// my_image.setImageDrawable(Drawable.createFromPath(imagePath));
}
}
}
But my problem was when i am close my application and reopen my progress bar is not showing.
But my file download in background.I want to show the progress of downloading file if app will close and re-open it again i want to show progress of download.
How to i create this any one please help me...
As far as i know, all your ui updates such as the progress bar you're displaying, "dies" when you leave your app. You can see the activity lifecycle here for more information.
You can try using a sync adapter approach (although it's a bit harder to implement).
Take a read here. In that example from the developer docs, you can adapt it for your needs, that means, creating a notification to show the progress of the download, and not relying if the user leaves your app or not.

directory in FileOpenStream

I am trying to download a image file on the internet by android and I use this code:
public class AndroidDownloadFileByProgressBarActivity extends Activity {
// button to show progress dialog
Button btnShowProgress;
// Progress Dialog
private ProgressDialog pDialog;
ImageView my_image;
// Progress dialog type (0 - for Horizontal progress bar)
public static final int progress_bar_type = 0;
// File url to download
private static String file_url = "http://api.androidhive.info/progressdialog/hive.jpg";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// show progress bar button
btnShowProgress = (Button) findViewById(R.id.btnProgressBar);
// Image view to show image after downloading
my_image = (ImageView) findViewById(R.id.my_image);
/**
* Show Progress bar click event
* */
btnShowProgress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// starting new Async Task
new DownloadFileFromURL().execute(file_url);
}
});
}
/**
* Showing Dialog
* */
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type:
pDialog = new ProgressDialog(this);
pDialog.setMessage("Downloading file. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(true);
pDialog.show();
return pDialog;
default:
return null;
}
}
/**
* Background Async Task to download file
* */
class DownloadFileFromURL extends AsyncTask<String, String, String> {
/**
* Before starting background thread
* Show Progress Bar Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
/**
* Downloading file in background thread
* */
#Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
// Output stream to write file
OutputStream output = new FileOutputStream("/sdcard/downloadedfile.jpg");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress(""+(int)((total*100)/lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
/**
* Updating progress bar
* */
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialog.setProgress(Integer.parseInt(progress[0]));
}
/**
* After completing background task
* Dismiss the progress dialog
* **/
#Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
dismissDialog(progress_bar_type);
// Displaying downloaded image into image view
// Reading image path from sdcard
String imagePath = Environment.getExternalStorageDirectory().toString() + "/downloadedfile.jpg";
// setting downloaded into image view
my_image.setImageDrawable(Drawable.createFromPath(imagePath));
}
}
}
but in LogCat i have an error. it show that: /sdcard/downloadedfile.jpg (Permission denied).
I am using android 3.1, and I don't know how to solve it, please help me!
thank so much.
Add WRITE_EXTERNAL_STORAGE permission to the manifest file.

how to make a downloadable pdf which is stored in assets?

I'm searching for some source code which downloads files from assets.
To use in my application which I save my PDF files in assets. and The download button will appear if the user completed or finished the game.
I was only find the Download a file to your android device from a remote server
You can download files from internet without blocking UI. This example show how to download a image file from remote server. Just replace things like url and downloading path.
The code goes here:
package com.example.androidhive;
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class AndroidDownloadFileByProgressBarActivity extends Activity {
// button to show progress dialog
Button btnShowProgress;
// Progress Dialog
private ProgressDialog pDialog;
ImageView my_image;
// Progress dialog type (0 - for Horizontal progress bar)
public static final int progress_bar_type = 0;
// File url to download
private static String file_url = "yoururl/file.jpg";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// show progress bar button
btnShowProgress = (Button) findViewById(R.id.btnProgressBar);
// Image view to show image after downloading
my_image = (ImageView) findViewById(R.id.my_image);
/**
* Show Progress bar click event
* */
btnShowProgress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// starting new Async Task
new DownloadFileFromURL().execute(file_url);
}
});
}
/**
* Showing Dialog
* */
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type: // we set this to 0
pDialog = new ProgressDialog(this);
pDialog.setMessage("Downloading file. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(true);
pDialog.show();
return pDialog;
default:
return null;
}
}
/**
* Background Async Task to download file
* */
class DownloadFileFromURL extends AsyncTask<String, String, String> {
/**
* Before starting background thread
* Show Progress Bar Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
/**
* Downloading file in background thread
* */
#Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// this will be useful so that you can show a tipical 0-100% progress bar
int lenghtOfFile = conection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream(), 8192);
// Output stream
OutputStream output = new FileOutputStream("/sdcard/downloadedfile.jpg");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress(""+(int)((total*100)/lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
/**
* Updating progress bar
* */
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialog.setProgress(Integer.parseInt(progress[0]));
}
/**
* After completing background task
* Dismiss the progress dialog
* **/
#Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
dismissDialog(progress_bar_type);
// Displaying downloaded image into image view
// Reading image path from sdcard
String imagePath = Environment.getExternalStorageDirectory().toString() + "/downloadedfile.jpg";
// setting downloaded into image view
my_image.setImageDrawable(Drawable.createFromPath(imagePath));
}
}
}
Problem : Let us understand the problem first . You want the user to be able to download a file in the assets. I guess, if the game is completed then the user's details pertaining to that game session will be stored there.
Solution : For that you need to write in assets.
Well, the problem is you can't write any file there as the assets folder is read-only at runtime.
So the way of doing this is using Internal Storage .
Other alternatives you may want to look into are Shared Perferences and using Cache Files also explained in the link above .
If your application needs to download dependency files from server, you can go for APK Expansion Files provided by android (http://developer.android.com/guide/market/expansion-files.html).

How to getfull path from sdcard in android app?

hello i used code below and i run the project in android 3.0 tablet emulator in android application nad i get path /mnt/sdcard/ but not get fullpath.how solve it ?please help me!!And my code below
![package com.hope.project;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.content.Context;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
WebView myWebView;
TextView mDisplay;
AsyncTask<Void, Void, Void> mRegisterTask;
String name;
String Message;
String deviceId;
String regId;
IntentFilter gcmFilter;
SharedPreferences sharedPref;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myWebView = (WebView) findViewById(R.id.webView1);
final JavaScriptInterface myJavaScriptInterface = new JavaScriptInterface(
this);
myWebView.addJavascriptInterface(myJavaScriptInterface,
"AndroidFunction");
WebSettings settings = myWebView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setDatabaseEnabled(true);
settings.setDomStorageEnabled(true);
settings.setAllowFileAccess(true);
settings.setBuiltInZoomControls(true);
settings.setUseWideViewPort(true);
settings.setJavaScriptCanOpenWindowsAutomatically(true);
settings.setLoadWithOverviewMode(true);
myWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
myWebView.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// handle stuff here
// e.g. view.loadUrl(url);
Log.v("log", " on ovverRide " + url);
return true;
}
public void onPageFinished(WebView view, String url) {
// dismiss the indeterminate progress dialog
Log.v("log", "onPageFinished: " + url);
myWebView.setEnabled(false);
}
});
myWebView.loadUrl("file:///android_asset/www/index.html");
/* File urlName= Environment.getExternalStorageDirectory().getAbsoluteFile();
Log.v("log_tag", "urlNameDownload "+urlName);*/
/* File file\[\] = Environment.getExternalStorageDirectory().listFiles();
for (File f : file)
{
if (f.isDirectory()) {
String uri=f.getPath().substring(f.getPath().lastIndexOf("/") + 1);
Log.v("Name", uri);
Log.v("Name", f.getPath()+ "");
Log.v("Name", f.getAbsolutePath()+ "");
}
}*/
File dir = new File("mnt/sdcard/");
File\[\] files = (new File("mnt/sdcard/")).listFiles();
// This filter only returns directories
FileFilter dirFilter = new FileFilter() {
public boolean accept(File dir) {
return dir.isDirectory();
}
};
files = dir.listFiles(dirFilter);
for (int i=0; i<files.length; i++) {
if(files\[i\].getAbsolutePath().contains("Download"))
Log.v("log_tag","directory path : " + files\[i\].getAbsolutePath().substring(files\[i\].getAbsolutePath().lastIndexOf("/") +1));
}
}
protected void onDestroy() {
super.onDestroy();
}
public class JavaScriptInterface {
Context mContext;
JavaScriptInterface(Context c) {
mContext = c;
}
public void DownloadUrl(String url) {
Log.v("log", "login main url " + url);
String file_url = url;
new DownloadFileFromURL().execute(file_url);
/*
* String url_new = "http://"+url; Intent i = new
* Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(url_new));
* startActivity(i);
*/
}
}
class DownloadFileFromURL extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Bar Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
// showDialog(progress_bar_type);
}
/**
* Downloading file in background thread
* */
#Override
protected String doInBackground(String... f_url) {
int count;
Log.v("log", "login main url\[0\] " + f_url\[0\]);
try {
URL url = new URL(f_url\[0\]);
name = f_url\[0\].substring(f_url\[0\].lastIndexOf("/") + 1);
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(),
8192);
// Output stream to write file
// OutputStream output = new
// FileOutputStream("/sdcard/downloadedfile.jpg");
OutputStream output = new FileOutputStream(
Environment.getExternalStorageDirectory() + "/Download/" + name);
// OutputStream output = new
// FileOutputStream("/sdcard/downloadedUrl.mp4");
byte data\[\] = new byte\[1024\];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
/**
* Updating progress bar
* */
protected void onProgressUpdate(String... progress) {
// setting progress percentage
// pDialog.setProgress(Integer.parseInt(progress\[0\]));
}
/**
* After completing background task Dismiss the progress dialog
* **/
#Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
// dismissDialog(progress_bar_type);
// Displaying downloaded image into image view
// Reading image path from sdcard
/*
* Log.v("log","login main url\[0\] " +
* Environment.getExternalStorageDirectory().toString()); String
* videoPath = Environment.getExternalStorageDirectory() +"/"+name;
* Intent i = new Intent(MainActivity.this,
* VideoPlayActivity.class); i.putExtra("videoPath", videoPath);
* startActivity(i);
*/
Toast.makeText(MainActivity.this, "DownLoad Is Completed",
Toast.LENGTH_LONG).show();
}
}
}
Instead of hardcoding mnt/sdcard/ you should use the Environment object.
Specifically:
File dir = Environment.getExternalStorageDirectory();
Will give you a file object that is automatically pointing in the proper place for the External Storage of the device that it is running on.
Also, you've posted your entire Activity. The vast majority of it is unrelated to the problem you are having. In the future it is more likely that you'll get good help on StackOverflow if you take out a smaller section of your code that specifically relates to the problem you are having. It makes it easier for people who are answering to figure out your situation.

ProgressBar is not updating while downloading a file in Android

I've read almost every similar topic but I couldn't find a solution. So I decided to ask my own.
I want to download a file and show a progress dialog during the operation. The file gets downloaded successfully.
The first problem is that the progress bar doesn't update during the download operation. It just stays %0 and when the download is finished, the dialog disappears as expected.
The second problem is - I noticed this by accident - when my activity gets updated (for example, when screen orientation is changed) the dialog disappears but the download continues.
I hope someone can help.
Here's my code:
package com.mehmetakiftutuncu.downloadunzipshow;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener
{
final String LOG_TAG = "DownloadUnzipShow";
final String RELATIVE_PATH = "mehmetakiftutuncu";
final String FILE_NAME = "...";
final String FILE_URL = "...";
final String FULL_PATH = Environment.getExternalStorageDirectory().getPath() + "/" + RELATIVE_PATH + "/";;
Button buttonDownload, buttonUnzip, buttonShow;
ProgressDialog progressDialog;
public class MyFileDownloader extends AsyncTask<String, String, String>
{
boolean isSuccessful = true;
InputStream inputStream;
OutputStream outputStream;
#Override
protected void onPreExecute()
{
super.onPreExecute();
prepareProgressDialog();
Log.d(LOG_TAG, "Downloading: " + FILE_URL + " to " + FULL_PATH + FILE_NAME);
}
#Override
protected String doInBackground(String... params)
{
int count;
try
{
URL url = new URL(params[0]);
URLConnection connection = url.openConnection();
connection.connect();
int lengthOfFile = connection.getContentLength();
File path = new File(FULL_PATH);
if(!path.exists())
{
path.mkdir();
}
inputStream = new BufferedInputStream(url.openStream());
outputStream = new FileOutputStream(FULL_PATH + FILE_NAME);
byte[] data = new byte[1024];
long total = 0;
int percentage = 0;
while((count = inputStream.read(data)) != -1)
{
total += count;
percentage = (int) ((total / lengthOfFile) * 100);
publishProgress(String.valueOf(percentage));
outputStream.write(data, 0, count);
}
outputStream.flush();
outputStream.close();
inputStream.close();
}
catch(Exception e)
{
isSuccessful = false;
Log.e(LOG_TAG, "An error occured while downloading. Details: " + e.getMessage());
}
return null;
}
#Override
protected void onProgressUpdate(String... values)
{
super.onProgressUpdate(values);
progressDialog.setProgress(Integer.parseInt(values[0]));
}
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
if(isSuccessful)
{
Log.d(LOG_TAG, "File is successfully downloaded to: " + FULL_PATH + FILE_NAME);
}
progressDialog.dismiss();
}
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonDownload = (Button) findViewById(R.id.button_download);
buttonDownload.setOnClickListener(this);
}
private void prepareProgressDialog()
{
progressDialog = new ProgressDialog(this);
progressDialog.setTitle(getString(R.string.dialog_title));
progressDialog.setMessage(getString(R.string.dialog_message) + FILE_URL);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMax(100);
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
public void onClick(View v)
{
switch(v.getId())
{
case R.id.button_download:
new MyFileDownloader().execute(FILE_URL);
break;
}
}
}
The first problem is that the progress bar doesn't update during the
download operation. It just stays %0 and when the download is
finished, the dialog disappears as expected.
That is happening because the line:
percentage = (int) ((total / lengthOfFile) * 100);
always return 0 as you're doing an integer java division where total is smaller than lengthOfFile. Make total a double value. Also don't cast the percentage as a String, modify the second generic argument of the AsyncTask to be an Integer.
The second problem is - I noticed this by accident - when my activity
gets updated (for example, when screen orientation is changed) the
dialog disappears but the download continues.
On a configuration change(a rotation for example) the Activity will be recreated killing your dialog in the process. If you want to re-show the dialog you'll need to keep the AsyncTask across the configuration change by passing it to the onRetainNonConfigurationInstance() method of the Activity(or you could use fragments). In the onCreate method use getLastNonConfigurationInstance to see if you have a task retained and still running and reshow the dialog. Also you really shouldn't make the AsyncTask a inner class in the Activity because you'll tie it to the activity.
THe dialog disappearing- are you capturing orientation config changes, or are you letting Android do it? If you're letting Android do it, it will kill your activity and recreate it, which will destroy your dialog. The async task wouldn't get killed because the async task is owned by the system. To fix that, add android:configChange="orientation" to your manifest for the activity. General rule of thumb is if you want to have dialogs persist through rotation you need to do that.

Categories

Resources