I want to show a progressbar downloading a bitmap:
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
int fileLength = connection.getContentLength();
// download the file
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
progressDialog.setProgress((int) (total * 100 / fileLength));
Log.i("progre+ss", (int) (total * 100 / fileLength) + " ");
}
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
which is initialised with:
private void openprogresdialog() {
// TODO Auto-generated method stub
progressDialog = new ProgressDialog(PrMapGen.this);
progressDialog.setMessage("Generating File...");
progressDialog.setCancelable(false);
progressDialog.setIndeterminate(false);
progressDialog.setMax(100);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.show();
new Thread() {
public void run() {
try {
generatePrMap(DataArray,
getIntent().getExtras().getString("project"));
} catch (Exception e) {
}
progressDialog.dismiss();
projdata.close();
finish();
}
}.start();
}
My problem is the following:
when I use the while loop to update the progressbar, no image is returned, when I delete the while loop the bitmap is returned successfuly.
Why???
thanks in advance
Here is a tip to do it the easy way.
Declare an AsyncTask.
Put your code to download the image in the doInBackgroud() and set the progressBar inside onUpdateProgress().
You can check this question too.
Related
In my app I'm using executor service to download a file from url. Now I want to add a horizontal progress bar to show the download progress. but I face errors. how can I add a progress bar in this code, without using async task?
private class ExecutorServiceDownload implements Runnable {
private String url;
public ExecutorServiceDownload(String url) {
this.url = url;
}
#Override
public void run() {
dlFile(url);
}
private String dlFile(String surl) {
try {
// I added progressbar here and it didn't download anything
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
URL url = new URL(surl);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK)
return "Server returned HTTP " + connection.getResponseCode() + " " + connection.getResponseMessage();
input = connection.getInputStream();
String title = URLUtil.guessFileName(String.valueOf(url), null, null);
output = new FileOutputStream(Environment.getExternalStorageDirectory().toString() + "/test_files" + "/" + title);
int contentLength = connection.getContentLength();
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
output.write(data, 0, count);
}
} catch (Exception e) {
return e.toString();
}
return null;
}
}
Use this code for download with executor service:
in onCreate :
ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreat`enter code here`e(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = findViewById(R.id.progressbar);
downloading();
Downloading file with executor service:
private void downloading() {
progressBar.setVisibility(View.VISIBLE);
ExecutorService executor = Executors.newSingleThreadScheduledExecutor();
Handler handler = new Handler(Looper.getMainLooper());
executor.execute(new Runnable() {
int count;
#Override
public void run() {
//Background work here
try {
// put your url.this is sample url.
URL url = new URL("http://techslides.com/demos/sample-videos/small.mp4");
URLConnection conection = url.openConnection();
conection.connect();
int lenghtOfFile = conection.getContentLength();
// download the file
InputStream input = conection.getInputStream();
//catalogfile is your destenition folder
OutputStream output = new FileOutputStream(catalogfile + "video.mp4");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
publishProgress(Integer.valueOf("" + (int) ((total * 100) / lenghtOfFile)));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
handler.post(new Runnable() {
#Override
public void run() {
//UI Thread work here
progressBar.setVisibility(View.GONE);
}
});
} catch (Exception e) {
}
}
});
}
update progressbar
private void publishProgress(Integer... progress) {
progressBar.setProgress(progress[0]);
}
and horizontal progress bar use :
<ProgressBar
android:max="100"
style="?android:attr/progressBarStyleHorizontal"
android:visibility="invisible"
android:id="#+id/progressbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
Below is my AsyncTask to download a PDF file from CloudBoost database. The code works and downloads the file; however, what does not work is the progress bar update because the file length returned is -1. Can someone give me a tip on how I can deal with this.
By the way loading.setProgress(progress[0]); line in the the progress update method is being initialized at the top of the class that this AsyncTask class is nested in.
class DownloadPdfFromInternet extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
int count;
try {
URL url = new URL(strings[0]);
URLConnection connection = url.openConnection();
connection.connect();
// get length of file
int lengthOfFile = connection.getContentLength();
Log.d("dozer74", "LengthOf File: " + lengthOfFile);
InputStream input = new BufferedInputStream(url.openStream(), 10 * 1024);
OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory().getPath() + "/" + pubName);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int) (total * 100 / lengthOfFile));
// write data to file
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
protected void onProgressUpdate(Integer... progress) {
loading.setProgress(progress[0]);
}
#Override
protected void onPostExecute(String url) {
loading.dismiss();
openPdfFile();
}
}
am using sound cloud search api. when i hit the search url it give me search results. every audio has stream url but not download url because it depends on setting of the uploader. Every none downloadable file also has download count more than 1. for example, when you'll hit this url
http://api.soundcloud.com/tracks.json?client_id=4346c8125f4f5c40ad666bacd8e96498&q=tere%20bin&limit=1
It'll give the search result like that
[{"kind":"track","id":63225776,"created_at":"2012/10/13 01:52:38 +0000","user_id":26029726,"duration":206177,"commentable":true,"state":"finished","original_content_size":3298521,"last_modified":"2014/10/01 18:56:25 +0000","sharing":"public","tag_list":"","permalink":"tere-bin-uzair-jaswal-official","streamable":true,"embeddable_by":"all","downloadable":false,"purchase_url":null,"label_id":null,"purchase_title":null,"genre":"Musical","title":"Tere Bin - Uzair Jaswal [Official Music Audio]","description":"","label_name":"","release":"","track_type":"original","key_signature":"","isrc":"","video_url":null,"bpm":null,"release_year":null,"release_month":null,"release_day":null,"original_format":"mp3","license":"all-rights-reserved","uri":"https://api.soundcloud.com/tracks/63225776","user":{"id":26029726,"kind":"user","permalink":"uzair-jaswal-1","username":"Uzair Jaswal Music","last_modified":"2014/10/19 13:06:28 +0000","uri":"https://api.soundcloud.com/users/26029726","permalink_url":"http://soundcloud.com/uzair-jaswal-1","avatar_url":"https://i1.sndcdn.com/avatars-000110064166-2ts508-large.jpg"},"permalink_url":"http://soundcloud.com/uzair-jaswal-1/tere-bin-uzair-jaswal-official","artwork_url":"https://i1.sndcdn.com/artworks-000032079002-kup6vc-large.jpg","waveform_url":"https://w1.sndcdn.com/9bwAsZfGrxwN_m.png","stream_url":"https://api.soundcloud.com/tracks/63225776/stream","playback_count":359588,"download_count":100,"favoritings_count":7557,"comment_count":491,"attachments_uri":"https://api.soundcloud.com/tracks/63225776/attachments","policy":"ALLOW"}]
this is for only one audio and that audio is not downloadable but it has download count of 100. how is this possible ?
can anybody tell me how i can download that audio which is not downloadable?
any help would be much appreciated. Thanks :)
I fix it myself, i was using android and the stream url is also a download url. the stream url is also download url for downloading but it won't affect on download count. you can try like that
String file_url = "https://api.soundcloud.com/tracks/93216523/stream?client_id=4346c8125f4f5c40ad666bacd8e96498";
pass this url to asyntack and manage you download there, you can pass it like that
new DownloadFileFromURL().execute(file_url);
here is DownloadFileFromUR class using asyntask
class DownloadFileFromURL extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... f_url) {
URL u = null;
InputStream is = null;
try {
u = new URL(f_url[0]);
is = u.openStream();
HttpURLConnection huc = (HttpURLConnection)u.openConnection();//to know the size of video
int size = huc.getContentLength();
if(huc != null){
String fileName = "FILE2.mp3";
String storagePath = Environment.getExternalStorageDirectory().toString();
File f = new File(storagePath,fileName);
FileOutputStream fos = new FileOutputStream(f);
byte[] buffer = new byte[1024];
long total = 0;
int len1 = 0;
if(is != null){
while ((len1 = is.read(buffer)) > 0) {
total+=len1;
publishProgress((int)((total*100)/size));
fos.write(buffer,0, len1);
}
}
if(fos != null){
fos.close();
}
}
}catch (MalformedURLException mue) {
mue.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if(is != null){
is.close();
}
}catch (IOException ioe) {
// just going to ignore this one
}
}
return "";
}
#Override
protected void onPostExecute(String file_url) {
}
}
String file_url = "https://api.soundcloud.com/tracks/93216523/stream?client_id=4346c8125f4f5c40ad666bacd8e96498";
DownLoad Class:
private class DownloadFile extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
int count;
try {
URL url = new URL(file_url);
URLConnection conexion = url.openConnection();
conexion.connect();
// this will be useful so that you can show a tipical 0-100% progress bar
int lenghtOfFile = conexion.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(getOutputMediaFile());
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
publishProgress((int) (total * 100 / lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
i want to download file from url. http://opengov.dev.ifabrika.ru/upload/435/IF_Заявка_Программист PHP_2013-09-03.docx - you can try it, it work. My code is next:
new DownloadFileFromURL().execute("http://opengov.dev.ifabrika.ru/upload/435/IF_Заявка_Программист PHP_2013-09-03.docx");
DownloadFileFromUrl is
class DownloadFileFromURL extends AsyncTask<String, String, String> {
private ProgressDialog pDialog;
public static final int progress_bar_type = 0;
/**
* Before starting background thread Show Progress Bar Dialog
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(PostInfoActivity.this);
pDialog.setMessage("Downloading file. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* 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(Environment
.getExternalStorageDirectory().toString()
+ "/test.docx");
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
if (pDialog != null) {
pDialog.dismiss();
}
}
}
After this a saw new test.docx file in my root folder, but its size is 26 byte and i can not open it.
This happening because your url is in unicoded form so you have to first encode it then try to download
URLEncoder.encode(Url, "UTF-8")
It works for me.
You can try with this method by calling this method from your doInBackground
private void downloader(String urlstr) {
HttpURLConnection c = null;
FileInputStream fis = null;
FileOutputStream fbo = null;
File file = null, file1;
File outputFile = null;
InputStream is = null;
URL url = null;
try {
outputFile = new File(Environment
.getExternalStorageDirectory().toString()
+ "/test.docx");
if(outputFile.exists())
Log.e("File delete",outputFile.delete()+"");
fbo = new FileOutputStream(outputFile, false);
// connect with server where remote file is stored to download it
url = new URL(urlstr);
c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.setConnectTimeout(0);
c.connect();
is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fbo.write(buffer, 0, len1);
Log.e("length", len1+"----");
}
fbo.flush();
} catch (Exception e) {
} finally {
if (c != null)
c.disconnect();
if (fbo != null)
try {
fbo.close();
} catch (IOException e) {
e.printStackTrace();
}
if (is != null)
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
file = null;
outputFile = null;
}
}
I think Problem is you used only URLConnection class instead of HttpUrlConnection class. refer below link
Download a file with Android, and showing the progress in a ProgressDialog
Hey I have checked your link which you got after encoding...The Problem here is the + character which replaced the white space http://opengov.dev.ifabrika.ru/upload/435/IF_Заявка_Программист+PHP_2013-09-03.docx.....TO resolve this issue replace your + character with %20 and then try....This will definitely work... and you can also do that before encoding i.e replace your white space with %20...so the final link should be like http://opengov.dev.ifabrika.ru/upload/435/IF_Заявка_Программист%20PHP_2013-09-03.docx
My while statement I have set up is causing my code underneath it to not be executed.
When I use this code here:
while ((count = is.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
}
to update the progress dialog bar for the file download, my other code I need to have doesn't get executed.
I'm not sure why this is behaving the way it is, if someone could explain and help, that would be great.
Full code:
public class SetWallpaperAsync extends AsyncTask<String, String, String> {
private Context context;
private ProgressDialog pDialog;
String image_url;
URL mImageUrl;
String myFileUrl1;
Bitmap bmImg = null;
public SetWallpaperAsync(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setMessage("Downloading Image...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
pDialog.setMax(100);
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
InputStream is = null;
int count;
try {
mImageUrl = new URL(args[0]);
// myFileUrl1 = args[0];
HttpURLConnection conn = (HttpURLConnection) mImageUrl
.openConnection();
conn.setDoInput(true);
conn.connect();
is = conn.getInputStream();
int lenghtOfFile = conn.getContentLength();
byte data[] = new byte[1024];
long total = 0;
while ((count = is.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
}
//This code doesn't get executed when using the code above
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Config.RGB_565;
bmImg = BitmapFactory.decodeStream(is, null, options);
} catch (IOException e) {
e.printStackTrace();
}
finally {
if (is != null) {
try {
is.close();
} catch (Exception e) {
}
}
}
return null;
}
protected void onProgressUpdate(String... progress) {
pDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String args) {
// TODO Auto-generated method stub
if (bmImg == null) {
Toast.makeText(context, "Image still loading...",
Toast.LENGTH_SHORT).show();
pDialog.dismiss();
}
else {
WallpaperManager wpm = WallpaperManager.getInstance(context);
try {
wpm.setBitmap(bmImg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pDialog.dismiss();
Toast.makeText(context, "Wallpaper Successfully Set!",
Toast.LENGTH_SHORT).show();
}
}
}
Your while loop consumes all input there is i.e. until -1 end-of-stream is reached.
When you try to decode a bitmap from the same stream here:
bmImg = BitmapFactory.decodeStream(is, null, options);
... there's nothing to decode.
Probably there is some exception in the loop:
while ((count = is.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
}
that is causing the rest of the code for not being executed.
Check in the catch statement if there is some exception or debug for the code flow to identify the actual problem.
you need to set the maximum progress to content length...
protected String doInBackground(String... args) {
..........
final int contentLength = conn.getContentLength();
runOnUiThread(new Runnable() {
#Override
public void run() {
pDialog.setMax(contentLength);
}
});
.........
}