Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I wanna create download app from url using android code like download manager
but really I don't know how to start
thanks for any help or any video tuts
Thats quite easy
http://developer.android.com/reference/android/app/DownloadManager.html
Example: http://androidtrainningcenter.blogspot.co.at/2013/05/android-download-manager-example.html
/**
* Start Download
*/
public void startDownload() {
DownloadManager mManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
Request mRqRequest = new Request(
Uri.parse("http://androidtrainningcenter.blogspot.in/2012/11/android-webview-loading-custom-html-and.html"));
mRqRequest.setDescription("This is Test File");
// mRqRequest.setDestinationUri(Uri.parse("give your local path"));
long idDownLoad=mManager.enqueue(mRqRequest);
}
But be sure you are min. on API 9
this code will download any file from url just replace the url and location..
public class AndroidDownloadFileByProgressBarActivity extends Activity {
// button to show progress dialog
Button btnShowProgress
// Progress Dialog
private ProgressDialog pDialog;
// 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 = " u r l";
#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);
}
});
}
#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;
}
}
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);
}
}
Manifest File:
<!-- Permission: Allow Connect to Internet -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- Permission: Writing to SDCard -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<!-- Download Button -->
<Button android:id="#+id/btnProgressBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Download File with Progress Bar"
android:layout_marginTop="50dip"/>
</LinearLayout>
This is java code for download image from url you can also use it with android application
public static void main(String ar[]) throws IOException
{
URL url = new URL("http://zeroturnaround.com/wp-content/uploads/2013/06/no-button-640x480-sky.jpg");
InputStream ios= url.openStream();
OutputStream fou1=new FileOutputStream("/home/delta/Desktop/image.jpg");
byte[] b=new byte[2048];
int length;
while((length=ios.read(b))!=-1)
{
fou1.write(b,0,length);
}
//fio1.close();
fou1.close();
}
Related
This is my code. When i run this code showing me error. Help me with that i already wasted lots of time on this task.
public class AndroidDownloadFileByProgressBarActivity extends Activity {
// button to show progress dialog
Button btnShowProgress;
MediaController mediaController ;
// Progress Dialog
private ProgressDialog pDialog;
VideoView videoView;
// 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://192.168.1.107/MSEManagement/static/uploads/productIntroduction/4/4.mp4";
#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
//videoView = (VideoView) 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;
}
}
class DownloadFileFromURL extends AsyncTask<String, String, String> {
#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/4.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);
}
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialog.setProgress(Integer.parseInt(progress[0]));
}
#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
videoView =(VideoView)findViewById(R.id.videoView);
mediaController= new MediaController(AndroidDownloadFileByProgressBarActivity.this);
mediaController.setAnchorView(videoView);
Uri uri=Uri.parse("/sdcard/4.mp4");
videoView.setMediaController(mediaController);
videoView.setVideoURI(uri);
videoView.requestFocus();
videoView.start();
}
}
When i run my code on my phone its running but not working android emulators. What should i do now i am stuck in these things.
D/VideoView: Error: 1,0
E/Error:: /sdcard/4.mp4 (Permission denied)
W/MediaPlayer: Couldn't open /sdcard/4.mp4: java.io.FileNotFoundException: No content provider: /sdcard/4.mp4
W/VideoView: Unable to open content: /sdcard/4.mp4
java.io.FileNotFoundException: /sdcard/4.mp4 (Permission denied)
If your app run correctly on your phone and does not work on emulator,
these can be happen
Your Manifest file should include permissions like a
<uses-permission android:name="android.permission.INSTALL_PACKAGES" />
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Maybe your phone SDK Version and emulator have different sdk try it same sdk version emulator with you phone.
i am download some data from URL. and i want to display the number of bytes and the % of bytes download together in the progress dialog.
now i can only show the % of bytes downloads.
here is my code
public class MainActivity extends ActionBarActivity {
// button to show progress dialog
Button btnShowProgress;
// Progress Dialog
private ProgressDialog pDialog;
private 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://ibuildmartdev.agicent.com/data/projs/3/11_01.pdf?5";
DownloadFileFromURL df;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setContentView(R.layout.activity_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
df =new DownloadFileFromURL();
df.execute(file_url);
}
});
}
/**
* Background Async Task to download file
* */
class DownloadFileFromURL extends AsyncTask<String, String, String> implements OnKeyListener {
/**
* Before starting background thread Show Progress Bar Dialog
* */
#SuppressWarnings("deprecation")
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Downloading file. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setMax(500);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(true);
pDialog.show();
pDialog.setOnKeyListener(this);
}
/**
* 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[2048];
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
pDialog.dismiss();
// 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));*/
}
#Override
protected void onCancelled() {
Log.i("main Activity", "Asyn task Cancled");
super.onCancelled();
}
#Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
df.cancel(false);
pDialog.dismiss();
Log.i("main Activity", "true");
return true;
}
return false;![enter image description here][1]
}
}
this code only show the download progress in %. but i want to show the download progress in % as well as total no of bytes download.
You can do this :
publishProgress("" + (int) ((total * 100) / lenghtOfFile)+ "lengthOfFile="+lengthOfFile); //You can use as a thing to split variable.Here, i used the name "lengthOfFile=" and i will get this through publish progress and split it there
#Override
protected void onProgressUpdate(String... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
String str[]=values[0].split("lengthOfFile=");
String percent=str[0];
String bytes=str[1];
}
I am developing an app that downloads files and show 2 progress bars, the first one for the current downloading file, and the 2nd one for total progress based on the number of files.
I am using the DoubleProgressBar library in my app:
I succeeded to update the first ProgressBar, but stuck with the 2nd one.
Here is my code for the AsyncTask class:
private DoubleProgressDialog pDialog;
class DownloadFileFromURL extends AsyncTask<String, Integer, String> {
Context mContext;
public DownloadFileFromURL(Context ctx) {
// TODO Auto-generated constructor stub
this.mContext = ctx;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(CUSTOM_PROGRESS_DIALOG);
}
/* Downloading file in background thread */
#Override
protected String doInBackground(String... f_url) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(f_url[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// getting file length
int fileLength = connection.getContentLength();
for (int i = 0; i <= ArrayOfFiles.length; i++){
File f = new File(Environment.getExternalStorageDirectory() + "/Folder/", ArrayOfFiles[i]);
// input stream to read file - with 8k buffer
input = new BufferedInputStream(url.openStream(), 8192);
// Output stream to write file
output = new FileOutputStream(f);
byte data[] = new byte[8192];
long total = 0;
int count;
int EntireProgress = 0;
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled()) {
input.close();
return null;
}
total += count;
// publishing the progress....
if (fileLength > 0) // only if total length is known
publishProgress((int)(total * 100 / fileLength));
output.write(data, 0, count);
/*Here is my trouble, the 2nd ProgressBar is updating as the same of the first one, I need the 2nd one to update itself slowly till all files get downloaded*/
int CurrentProgress = pDialog.getProgress();
pDialog.setSecondaryProgress(CurrentProgress );
publishProgress(CurrentProgress );
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
}
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// dismiss the dialog after the file was downloaded
dismissDialog(CUSTOM_PROGRESS_DIALOG);
if (result != null)
Toast.makeText(mContext,"Download error: " + result, Toast.LENGTH_LONG).show();
else
Toast.makeText(mContext,"File downloaded", Toast.LENGTH_SHORT).show();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
// if we get here, length is known, now set indeterminate to false
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgress(progress[0]);
}
}
I also used this method in my activity class:
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case CUSTOM_PROGRESS_DIALOG:
pDialog = new DoubleProgressDialog(NetworkActivity.this);
pDialog.setMessage("Downloading file. Please wait...");
pDialog.setMax(100);
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.setButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
pDialog.show();
return pDialog;
default:
return null;
}
}
Any idea?
First part is to move pDialog.setSecondaryProgress to the onProgressUpdate(Integer... progress) method.
You are also resetting the secondary progress in each download task by setting it to CurrentProgress which is set to pDialog.getProgress();. Hence the second progress will always be reset after the download is finished.
Edit:
// publishing the progress....
if (fileLength > 0) // only if total length is known
publishProgress((int)(total * 100 / fileLength), pDialog.getSecondaryProgress());
(...)
int CurrentProgress = pDialog.getProgress();
// do not update secondary progress here
// pDialog.setSecondaryProgress(CurrentProgress );
int secondaryProgress = (CurrentProgress + 100 * i)/ArrayOfFiles.length;
publishProgress(CurrentProgress, secondaryProgress);
And the onProgressUpdate
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
(...)
pDialog.setProgress(progress[0]);
pDialog.setSecondaryProgress(progress[1]);
}
If you are not setting your DownloadFileFromUrl outside your main class I would suggest something like this
int CurrentProgress = pDialog.getProgress();
int secondaryProgress = (CurrentProgress + 100 * id_treated_file)/number_of_files;
// id_treated_file - 0, 1, 2, ... , number_of_files - 1
pDialog.setSecondaryProgress(CurrentProgress);
// secondaryProgress will be progress[1] in your onProgressUpdate method
publishProgress(CurrentProgress, secondaryProgress);
your onProgressUpdate method should look like this :
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
// if we get here, length is known, now set indeterminate to false
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgress(progress[0]);
pDialog.setSecondaryProgress(progress[1]);
}
EDIT
or you can try
pDialog.setSecondaryProgress((progress[0] + 100 * id_treated_file)/number_of_files);
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.
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.