Download and saving file using Asynctask is not working properly - android

I have used the following class for downloading a file and saving it to the sdcard.
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(Environment.getExternalStorageDirectory().getAbsolutePath()+"PurchasedFrames/"+filename);
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) {
File file = new File("/sdcard/PurchasedFrames/", filename );
Bitmap myBitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
ImageView frame = (ImageView) findViewById(R.id.frame);
frame.setImageBitmap(myBitmap);
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
Dialog method
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;
}
}
My problem using the above codes, progressBar will appear but it will disappear without finishing and no download occur. I could't notice any logcat error or any other error from debugging. Can anybody tell what can be happen or how to overcome from this problem?

So my assumption was correct. In my application I used a static method for returning a file path that calls mkdirs() in case that such path doesn't exist.
For your code such method would look so:
public static File getSaveFilePath(String fileName) {
File dir = new File(Environment.getExternalStorageDirectory(), "PurchasedFrames");
dir.mkdirs();
File file = new File(dir, fileName);
return file;
}
Then replace the line with output stream:
OutputStream output = new FileOutputStream(getSaveFilePath(fileName));
Also replace your exception block with catch (Exception e) { Log.e("DownloadFileAsync", e.toString()); "}

Related

How to hide the browser when downloading files from online

I am trying to download a file from an online source of mine. The issue I am having is that the browser window keeps appearing as it load into the download server. Is there some way that I may be able to hide this? I already have this code below in the doInBackground portion of an AsyncTask, but cant seem to get it to hide the browser bar. Here is my code at this point:
private class getErDone extends AsyncTask<Void, Void, Void>{
#Override
protected void onPreExecute() {
ProgressDialog progressDialog = new ProgressDialog(getApplicationContext());
progressDialog.setTitle("Downloading Software");
progressDialog.setMessage("Now Updating, DO NOT TURN OFF DEVICE");
progressDialog.setCancelable(false);
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
try{
Intent goToMarket = new Intent(Intent.ACTION_VIEW)
.setData(Uri.parse("http://mydownloadlink.com/myfile?dl=1"));
//**Note** As convincing as it seems, this is not the real download link
startActivity(goToMarket);
}catch (UnknownError e){
e.printStackTrace();
}
/*catch (MalformedURLException e){
e.printStackTrace();
}catch (IOException t){
t.printStackTrace();
}*/
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
}
Thanks everyone!
here is sample from my code, download without browser:
private TextView mFileDownloadProgressBarPercent;
private ProgressBar mFileDownloadProgressBar;
private Runnable mFileExecutionTaskAfterDownload;
public String fileDownloadedResultPath;
and asynctask:
class DownloadFileFromURL extends AsyncTask<String, String, String> {
// Before starting background thread
// Show Progress Bar Dialog
#Override
protected void onPreExecute() {
super.onPreExecute();
if(mFileDownloadProgressBar != null)
mFileDownloadProgressBar.setVisibility(View.VISIBLE);
if(mFileDownloadProgressBarPercent != null)
mFileDownloadProgressBarPercent.setVisibility(View.VISIBLE);
}
// 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);
String extStorageDirectory = Environment.getExternalStorageDirectory()
.toString();
File folder = new File(extStorageDirectory, "pdf"); // for example we are downloading pdf's so store in pdf dir.
folder.mkdir();
File subFolder = new File(extStorageDirectory+"/pdf", "fileId"); // here you can place files by id of category etc..
subFolder.mkdir();
String fileName = url.toString().substring(url.toString().lastIndexOf("/")+1);
fileDownloadedResultPath = subFolder + "/" + fileName;
// Output stream to write file
OutputStream output = new FileOutputStream(subFolder + "/" + fileName);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
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;
}
protected void onProgressUpdate(String... progress) {
if(mFileDownloadProgressBar != null)
mFileDownloadProgressBar.setProgress(Integer.parseInt(progress[0]));
if(mFileDownloadProgressBarPercent != null)
mFileDownloadProgressBarPercent.setText(mContext.getString(R.string.downloading_file) + " " + String.format("%s%%",Integer.parseInt(progress[0])+""));
}
#Override
protected void onPostExecute(String file_url) {
if(mFileDownloadProgressBar != null)
mFileDownloadProgressBar.setVisibility(View.GONE);
if(mFileDownloadProgressBarPercent != null)
mFileDownloadProgressBarPercent.setVisibility(View.GONE);
if(mFileExecutionTaskAfterDownload != null)
mFileExecutionTaskAfterDownload.run();
}
}

How to upload and download images into server from android using phpmyadmin and json?

I mean, to my local host database.
Please help me.
Find this link.It contain both code of Android and Php for image uploading.
http://www.androidhive.info/2014/12/android-uploading-camera-image-video-to-server-with-progress-bar/
Image Downloading:
call this method in onCreate and mImageUrl is your url to download image
new DownloadImage().execute(mImageUrl);
class DownloadImage extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
#Override
protected String doInBackground(String... mImageUrl) {
int count;
try {
URL url = new URL(mImageUrl[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/downloadedImage.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;
}
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String mImageUrl) {
// 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() + "/downloadedImage.jpg";
// setting downloaded into image view
my_image.setImageDrawable(Drawable.createFromPath(imagePath));
}
}
#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;
}
}

download file from url and read later locally

I want to download a file from url to read this file later locally. I have this code to download the file:
private void startDownload() {
String url = "my url";
new DownloadFileAsync().execute(url);
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Actualizando programa..");
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("/myfile.json");
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);
}
}
I donĀ“t know where it will be save the file with this code and how can I read this file later locally.
To save your file, to your app dir use this:
//save to cache
try {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File(activity.getFilesDir(), "/myfile.json")));
oos.writeObject(list);
oos.flush();
oos.close();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
To retrieve content:
ObjectInputStream dis = new ObjectInputStream(new FileInputStream(new File(context.getFilesDir(), "/myfile.json")));
ArrayList<String> = (ArrayList<String>) dis.readObject();
dis.close();
I hope it helps!

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

Android Asyck Task download cannot update Progress Dialog Bar

I am trying to download the movie from the FTP Server . It can be successfully downloaded but the progress of the download cannot be seen. Would you please tell me why publishProgress() is not working well ?
The below is my code
public void doClick(View v){
boolean x = decodedLink.startsWith("ftp://");
boolean y = decodedLink.startsWith("http://");
if(x ==true && y==false)
{
//ftp
myurl = null;
try {
myurl = new URL("ftp://newrising:newrising2014cap!#newrising.win5.siteonlinetest.com/dummy/giant.mp4");
} catch (MalformedURLException e) {
e.printStackTrace();
}
pd = new ProgressDialog(this);
pd.setTitle("EOrder");
pd.setMessage("Downloading file. Please wait...");
pd.setIndeterminate(false);
pd.setMax(100);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setCancelable(true);
new FTPDownload().execute(myurl);
}
else if(x ==false && y==true)
{
//http
}
else
{
//invalid message
}
}
class FTPDownload extends AsyncTask<URL , Integer , Void>{
boolean running = true;
int count ;
Date today = Calendar.getInstance().getTime();
Format formatter = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss");
String reportDate = formatter.format(today);
String file = reportDate + "_" + "giant.mp4";
#Override
protected Void doInBackground(URL... params) {
// TODO Auto-generated method stub
Log.d("******", "Background thread starting......");
try
{
URL url = new URL("ftp://newrising:newrising2014cap!#newrising.win5.siteonlinetest.com/dummy/giant.mp4");
URLConnection conection = url.openConnection();
conection.connect();
int lenghtOfFile = conection.getContentLength();
Log.d("lenghtOfFile","values: "+lenghtOfFile);
InputStream input = new BufferedInputStream(url.openStream(), 8192);
OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory() + File.separator + file);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int)((total/lenghtOfFile)*100));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
}
catch(Exception e)
{
System.out.println("Error: could not connect to host " + decodedLink);
e.printStackTrace();
}
return null;
}
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
Log.d("progress","values: "+progress[0]);
pd.setProgress(progress[0]);
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
pd.dismiss();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd.show();
}
#Override
protected void onCancelled() {
running = false;
}
try this code
Hope this will work.. It will show you download progress as well.
new DownloadFileAsync().execute(fileURL);
class DownloadFileAsync extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected String doInBackground(String... aurl) {
try {
// connecting to url
URL u = new URL(downloadURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
// lenghtOfFile is used for calculating download progress
int lenghtOfFile = c.getContentLength();
// this is where the file will be seen after the download
FileOutputStream f = new FileOutputStream(new File(rootDir
+ "/my_downloads/", fileName));
// file input is from the url
InputStream in = c.getInputStream();
// here's the download code
byte[] buffer = new byte[1024];
int len1 = 0;
long total = 0;
while ((len1 = in.read(buffer)) > 0) {
total += len1; // total = total + len1
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
f.write(buffer, 0, len1);
}
f.close();
} catch (Exception e) {
Log.d(LOG_TAG, e.getMessage());
}
return null;
}
protected void onProgressUpdate(String... progress) {
// Log.d(LOG_TAG,progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
downloadtext.setText(progress[0] + "%");
}
#Override
protected void onPostExecute(String unused) {
// dismiss the dialog after the file was downloaded
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS: // we set this to 0
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Downloading file...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(true);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
Let me know if you need any more help
thanks
Umer
I would suggest you do the following in your onProgressUpdate
#Override
protected void onProgressUpdate(Integer... progress) {
int count = (progress[0]+1);
if(FTPDownload.this.isCancelled())
{
//Handle the canceling of the AsyncTask Exection
}
else{
pd.setMessage( count+" Of "+mCount+" Downloaded");
pd.show();
}

Categories

Resources