I need to download zip file using multiple URL's and this is my postman
[URL's in postman]
public class downloadfile extends Activity {
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private Button starbtn;
private ProgressDialog mProgress;
/** 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) {
startDown();
}
});
}
private void startDown() {
String url = "http://farm1.static.flickr.com/114/298125983_0e4bf66782_b.zip";
new DownloadFileAsync().execute(url);
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgress = new ProgressDialog(this);
mProgress.setMessage("Downloading file..");
mProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgress.setCancelable(false);
mProgress.show();
return mProgress;
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);
inputStreamStream inputStream = new BufferedinputStreamStream(url.openStream());
outputStreamStream outputStream = new FileoutputStreamStream("/sdcard/some_photo_from_gdansk_poland.zip");
byte data[] = new byte[1024];
long total = 0;
while ((count = inputStream.read(data)) != -1) {
total += count;
publishProgress(""+(int)((total*100)/lenghtOfFile));
outputStream.write(data, 0, count);
}
outputStream.flush();
outputStream.close();
inputStream.close();
} catch (Exception e) {}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC",progress[0]);
mProgress.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
}
Related
I am trying to download image on button click through Async Task but the image is not downloading. Is there any problem with the download link in the String "image_url"?
Logcat - skia: --- SkImageDecoder::Factory returned null
public class DownloadImageAsyncTask extends AppCompatActivity {
Button button;
ImageView imageView;
String image_url = "http://www.freegreatdesign.com/files/images/6/2921-large-apple-icon-png-1.jpg";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.download_image_async_task);
button = (Button) findViewById(R.id.bDownload);
imageView = (ImageView) findViewById(R.id.downImage);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DownloadTask downloadTask = new DownloadTask();
downloadTask.execute(image_url);
}
});
}
class DownloadTask extends AsyncTask<String, Integer, String>
{
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(DownloadImageAsyncTask.this);
progressDialog.setTitle("Download in progress...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMax(100);
progressDialog.setProgress(0);
progressDialog.show();
}
#Override
protected String doInBackground(String... params) {
String path = params[0];
int file_length = 0;
try {
URL url = new URL(path);
URLConnection urlConnection = url.openConnection();
urlConnection.connect();
file_length = urlConnection.getContentLength();
File new_folder = new File("sdcard/photoalbum");
if(!new_folder.exists())
{
new_folder.mkdir();
}
File input_file = new File(new_folder, "downloaded_image.jpg");
InputStream inputStream = new BufferedInputStream(url.openStream(), 8192);
byte[] data = new byte[1024];
int total = 0;
int count = 0;
OutputStream outputStream = new FileOutputStream(input_file);
while((count=inputStream.read())!=-1)
{
total+=count;
outputStream.write(data, 0, count);
int progress = (int) total*100/file_length;
publishProgress(progress);
}
inputStream.close();
outputStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "Download Complete...";
}
#Override
protected void onProgressUpdate(Integer... values) {
progressDialog.setProgress(values[0]);
}
#Override
protected void onPostExecute(String result) {
progressDialog.hide();
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show();
String path = "sdcard/photoalbum/downloaded_image.jpg";
imageView.setImageDrawable(Drawable.createFromPath(path));
}
}
}
I'm trying to download a zip file from an API. For this purpose I'm using this following code:
public class Download_Activity 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.download);
startBtn = (Button) findViewById(R.id.downloadButton);
startBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startDownload();
}
});
}
private void startDownload() {
String url = downloadURL;
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<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 urlConnection = url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.connect();
Log.i("1111", "1111" );
File SDCardRoot = Environment.getExternalStorageDirectory();
File file = new File(SDCardRoot, "hello1.zip");
Log.i("2222", "2222" );
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
int totalSize = urlConnection.getContentLength();
int downloadedSize = 0;
byte[] buffer = new byte[1024];
int bufferLength = 0;
Log.i("3333", "3333" );
Log.i("befferLength", "bufferLength: " + bufferLength);
Log.i("is read buffer", "is read buffer: " + inputStream.read(buffer));
while ((bufferLength = inputStream.read(buffer)) > 0) {
Log.i("inside while", "inside while ");
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
updateProgress(downloadedSize, totalSize);
}
Log.i("4444", "4444" );
fileOutput.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);
}
}
public void updateProgress(int currentSize, int totalSize) {
Toast.makeText(getApplicationContext(), "Loading Files...",
Toast.LENGTH_SHORT).show();
}
In this code, the zip file is created as "hello1.zip" but this file is empty in my mobile. Here I've various log statements to find the execution of code. To my surprise only upto "Log.i("2222", "2222" );" is printed while the rest of the logs are not printed. Can you please tell me what the problem is???
Thanks in advance..!
U can use DownloadManager class for this purpose it handles the pause and continues the dowloading in the case of network availablity and you can run a broadcast reciver to perform you actions( like pushing a notification etc) when dowloading is complete
http://developer.android.com/reference/android/app/DownloadManager.html
I'm trying to create a method within my activity that will unzip the downloaded file to a certain directory. I have tried several different ways and haven't had much luck. I've seen some people use a separate class to do this task, I want to avoid doing that, but if it's my only option then I will do it. Here is my activity:
public class lava_parkour extends Activity {
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private Button startBtn;
private ProgressDialog mProgressDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lava_parkour);
startBtn = (Button)findViewById(R.id.button1);
startBtn.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
startDownload(v);
} });
}
private void startDownload(View v) {
String url = "https://www.dropbox.com/s/lxnizie52efq3e8/lava%20parkour.zip?
dl=1";
new DownloadFileAsync().execute(url);
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Downloading...");
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);
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new
FileOutputStream("/sdcard/games/com.mojang/lava_parkour.zip");
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);
Toast.makeText(lava_parkour.this, "Process completed! THis map has been added
to your game!", Toast.LENGTH_LONG).show();
}
}
}
Any help is appreciated!
i keep getting this error telling me to suppress my showdialog code for my progress bar.
now what can i do to fix this, also i dont want to use any other way. im trying to learn showdialog for downloads
here my code
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.activity_main);
startBtn = (Button)findViewById(R.id.startBtn);
startBtn.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
startDownload();
}
});
}
private void startDownload() {
String url = "http://practicalbuddhist.com/wp-content/uploads/2012/03/Synapses-Image-for-March-17-2010-Blog-Entry.jpg";
new DownloadFileAsync().execute(url);
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Running Download Test...");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
class DownloadFileAsync extends AsyncTask<String, String, String> {
#SuppressWarnings("deprecation")
#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/Downloadtest.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]));
}
#SuppressWarnings("deprecation")
#Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
}
Use the Dialog class methods directly not the Activity helper methods.
In the Dialog API guide at http://developer.android.com/guide/topics/ui/dialogs.html they say explicitly to do not use ProgressDialog but use a custom layout with a ProgressBar.
On the other hand you could just use the DownloadManager to download files asynchrously. Check https://github.com/commonsguy/cw-android/blob/master/Internet/Download/src/com/commonsware/android/download/DownloadDemo.java for a simple example even with notifications.
If you still wants this method check http://www.androidhive.info/2012/04/android-downloading-file-by-showing-progress-bar/ for a simple example using a ProgressDialog-
public class ExampleActivity 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(true);
mProgressDialog.setButton("Cancel", new CancelOnClickListener());
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
private final class CancelOnClickListener implements DialogInterface.OnClickListener {
public void onClick(DialogInterface dialog, int which) {
ExampleActivity.this.finish();
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
new DownloadFileAsync().cancel(true);
}
}
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);
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);
}
}
}
Here if i click the start button,it will download the file automatically.but i want to cancel the download (if i don't like),so i put mProgressDialog.setButton("Cancel", new CancelOnClickListener());this exit the application.but the file is downloading.How to change the function inside doInBackground()
You are using 2 different instance of DownloadFileAsync in startDownload() and CancelOnClickListener. Try the following code:
public class ExampleActivity extends Activity {
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private Button startBtn;
private ProgressDialog mProgressDialog;
DownloadFileAsync dfa = new DownloadFileAsync();
/** 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";
dfa.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(true);
mProgressDialog.setButton("Cancel", new CancelOnClickListener());
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
private final class CancelOnClickListener implements DialogInterface.OnClickListener {
public void onClick(DialogInterface dialog, int which) {
ExampleActivity.this.finish();
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
dfa.cancel(true);
}
}
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);
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;
if(!isCancelled()){
while (!isCancelled() && (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);
}
}
}