Progress bar for file transfer to sd - android

i use the following code for downloading a file from the internet. using this code i have a progress dialog
private void startDownload() {
String url = tv.getText().toString();
new DownloadFileAsync().execute(url);
}
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(
"data/data/com.xxxxxxxx.android/app_p_pic/"
+ "blabla"
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) {
e.printStackTrace();
}
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);
}
}
}
is there a way of using the above code to transfer a file from say internal to sd? at the momment i use the following code but iv been unable to get the progress to work with progress bar
protected void ontrans() {
String title = tv.getText().toString();
try {
myInput = new FileInputStream(title);
File directory = new File(Environment.getExternalStorageDirectory()
+ "/android_files/data/secure");
if (!directory.exists()) {
directory.mkdirs();
}
OutputStream myOutput = new FileOutputStream(
Environment.getExternalStorageDirectory()
+ "/android_files/data/secure/" + chosenFile);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
Toast.makeText(File_exActivity.this, "file move Succesfully!",
Toast.LENGTH_SHORT).show();
showDialog(11);
} catch (FileNotFoundException e) {
Toast.makeText(File_exActivity.this, "no file found!",
Toast.LENGTH_LONG).show();
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
Toast.makeText(File_exActivity.this, "move unsuccesfull!",
Toast.LENGTH_LONG).show();
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Things to think about: you can get the size of the source file File.length() and destination. Comparing them to display the difference in the progress bar.
The File.length() method returns the following according to the javadoc:
The length, in bytes, of the file denoted by this abstract pathname,
or 0L if the file does not exist. Some operating systems may return 0L
for pathnames denoting system-dependent entities such as devices or
pipes.

What you'll need to do is to create a progress bar object (you can add it into your layout if you want or create it programmatically) then update its state inside your download while loop. The means of creating a progress bar can be found here: http://developer.android.com/reference/android/widget/ProgressBar.html

Related

Get content length method (getContentLength()) of the URLConnection class returns negative 1 (-1)

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();
}
}

Saving pdf File in Android

im building an android App that download books in pdf format from url and storage it into the device , so i wrote this code to make folder named " Mypdf " and save the file after it download in it , but when i run the app in the device i only found Mypdf file but there is no any pdf book , below the code i used
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 {
File file = new File(Environment.getExternalStorageDirectory()+"/Mypdf");
file.mkdir();
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("Mypdf/ "+booknameText+ ".pdf");
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(getApplicationContext(), "The Book You downloaded had been saved into your SD Card " , Toast.LENGTH_LONG).show();
}
}
}
i used this function :
OutputStream output = new FileOutputStream("/sdcard/ "+booknameText+ ".pdf");
but some times many device's do'not have sdcard so the file will not be saved , so please can you help guys

Download docx file from url android

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

Download URL File if exist.

Hi everyone I'm trying download file from url if exist… my problem is file downloaded without exist from server…
i will appreciate if anyone help me…
I can not figure out check if file exist download it if not ignore…
private void startDownload() {
// TODO Auto-generated method stub
String url = "http://example.com/file/krs.db";
new DownloadFileAsync().execute(url);
}
class DownloadFileAsync extends AsyncTask<String, String, String> {
#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);
// create empty directory if not exist
File appDir = new File(sdcardBaseDir + externalPath);
if (!appDir.exists())
appDir.mkdirs();
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(sdcardBaseDir
+ externalPath + IcsvFileName);
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]);
}
}
Appreciate your help..
Use the code below to check whether your file is exist in the given url.
public static boolean exists(String URLName){
try {
HttpURLConnection.setFollowRedirects(false);
// note : you may also need
// HttpURLConnection.setInstanceFollowRedirects(false)
HttpURLConnection con =
(HttpURLConnection) new URL(URLName).openConnection();
con.setRequestMethod("HEAD");
return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}
The method returns 'true' if file exists, Then download it.
Ignore otherwise.
If you connect to a HTTP URL, you will actually get back a HttpURLConnection object. It has a getResponseCode method that gives you the HTTP status code.

Saving to internal storage using existing code - Android

I would rather my application save the required text file in the internal storage for the app than the users /sdcard/ so there isn't files being created which may annoy them at some point. Could someone direct me on how to change my code so the text file is saved internally rather than externally.
public void updatebutton(View v){
startDownload();
}
private void startDownload() {
String url = "http://nowactivity.webs.com/teststring.txt";
Toast.makeText(this, "Updating", Toast.LENGTH_LONG);
new DownloadFile().execute(url);
}
class DownloadFile extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... aurl) {
int count;
try {
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/textfile.txt");
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;
}
I think what you want is Context.openFileOutput(). (Activity extends Context, so you could call this from within an Activity, for instance.)
Incidentally, you should use Environment.getExternalStorageDirectory() instead of something like "/sdcard"

Categories

Resources