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!
Related
I have an online music player in which I dedicated a button in order to download the file. There's a "progressDialog" which works fine and shows progress of downloading file and it seems that it's really downloading my file. But after completion there's no folder nor file on my device.
I also added Write External Storage permission in my manifest.
Here's my download class:
public class DownloadTask extends AsyncTask<String, Integer, String> {
#SuppressLint("StaticFieldLeak")
private Context context;
public static ProgressDialog progressBar;
public DownloadTask(Context context) {
this.context = context;
progressBar = new ProgressDialog(context);
progressBar.setMessage("Downloading...");
progressBar.setIndeterminate(true);
progressBar.setCancelable(true);
progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.show();
}
#Override
protected String doInBackground(String... strings) {
InputStream inputStream = null;
OutputStream outputStream = null;
HttpURLConnection connection = null;
try {
URL url = new URL(strings[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
int fileLength = connection.getContentLength();
inputStream = connection.getInputStream();
fileCache();
outputStream = new FileOutputStream(context.getFilesDir() + "listening"
+ strings[1] + ".mp3");
byte[] data = new byte[4096];
long total = 0;
int count;
while ((count = inputStream.read(data)) != -1) {
total += count;
if (fileLength > 0)
publishProgress((int) (total * 100 / fileLength));
outputStream.write(data, 0, count);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (outputStream != null) {
outputStream.flush();
outputStream.close();
}
if (inputStream != null)
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
if (connection != null)
connection.disconnect();
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
progressBar.setIndeterminate(false);
progressBar.setMax(100);
progressBar.setProgress(values[0]);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
progressBar.dismiss();
if (s != null) {
Toast.makeText(context, "Error while Downloading", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Downloaded successfully", Toast.LENGTH_SHORT).show();
}
}
private void fileCache() {
File myDir = new File(context.getFilesDir(), "listening");
if (!myDir.exists()) {
myDir.mkdirs();
}
}
}
And here's my button's function:
DownloadTask downloadTask = new DownloadTask(context);
downloadTask.execute(extra.getString("link"), extra.getString("title"));
I have an AsyncTask method for downloading a JSON file. After downloading, on postExecute I populate my listview.
My problem is this method will not work when I'm connected to mobile network. I've tried it with different phones, or it will be stuck in ProgressDialog spinner, or it will show nothing after dismissing ProgressDialog on postExecute.
But when the phone is connected to the wifi network it's fine and I'll get my result.
Method
public class JsonDownloader extends AsyncTask<String, Integer, String> {
private PowerManager.WakeLock mWakeLock;
private FileOutputStream out = null;
private File filename = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
PowerManager pm = (PowerManager) getActivity().getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,getClass().getName());
mWakeLock.acquire();
mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setTitle("Preparing List...");
mProgressDialog.setMessage("Please wait while list is populating...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setCancelable(true);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgressDialog.setMax(100);
mProgressDialog.setProgress(100);
mProgressDialog.show();
mProgressDialog.setContentView(R.layout.custom_progressdialog);
ProgressBar progressbar=(ProgressBar)mProgressDialog.findViewById(R.id.pbar);
progressbar.getIndeterminateDrawable().setColorFilter(Color.parseColor("#FF4081"), android.graphics.PorterDuff.Mode.SRC_IN);
}
#Override
protected String doInBackground(String... image_urls) {
InputStream input = null;
HttpURLConnection connection = null;
try {
URL url = new URL(image_urls[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
int fileLength = connection.getContentLength();
input = connection.getInputStream();
Log.i("in save()", "after mkdir");
filename = new File(path+offlineJsonFileName +".txt");
Log.i("in save()", "after file");
out = new FileOutputStream(filename);
Log.i("in save()", "after outputstream");
out.flush();
out.close();
Log.i("in save()", "after outputstream closed");
out = new FileOutputStream(filename);
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
if (isCancelled()) {
input.close();
return null;
}
total += count;
if (fileLength > 0) // only if total length is known
publishProgress((int) (total * 100 / fileLength));
out.write(data, 0, count);
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (out != null)
out.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return null;
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgress(progress[0]);
}
#Override
protected void onPostExecute(String args) {
mWakeLock.release();
mProgressDialog.dismiss();
ReadFile();
}
}
And I execute it like this:
jsonDownloader = new JsonDownloader();
jsonDownloader.execute(url);
out.flush();
out.close();
Log.i("in save()", "after outputstream closed");
out = new FileOutputStream(filename);
Remove that all. Why close and reopen an output stream?
After you are done with the writing do a flush().
I made it work by the following
class JsonDownloaderNew extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
System.out.println("Starting download");
mProgressDialog = new ProgressDialog(activity);
mProgressDialog.setTitle("Preparing List...");
mProgressDialog.setMessage("Please wait while list is populating...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setCancelable(false);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgressDialog.setMax(100);
mProgressDialog.setProgress(100);
mProgressDialog.show();
mProgressDialog.setContentView(R.layout.custom_progressdialog);
ProgressBar progressbar=(ProgressBar)mProgressDialog.findViewById(R.id.pbar);
progressbar.getIndeterminateDrawable().setColorFilter(Color.parseColor("#FF4081"), android.graphics.PorterDuff.Mode.SRC_IN);
}
#Override
protected String doInBackground(String... f_url) {
int count;
try {
System.out.println("Downloading");
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
File filename = new File(path+offlineJsonFileName +".txt");
OutputStream output = new FileOutputStream(filename);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// 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;
}
#Override
protected void onPostExecute(String file_url) {
System.out.println("Downloaded");
mProgressDialog.dismiss();
ReadFile();
}
}
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()); "}
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();
}
I want to download an mp3 file using an AsyncTask or a thread.
How can I do this?
You can do something like this...
When you decide to start downloading:
new Thread(new Runnable()
{
#Override
public void run()
{
File out;
Downloader DDL;
DDL=new Downloader();
out=new File(Environment.getExternalStorageDirectory() + "/DestFileName.txt");
DDL.DownloadFile("SourceURL",out);
}
}).start();
Where the downloader class is
public class Downloader {
public void Downloader()
{
// TODO Auto-generated method stub
}
public boolean DownloadFile(String url, File outputFile)
{
try {
URL u = new URL(url);
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = new byte[contentLength];
stream.readFully(buffer);
stream.close();
DataOutputStream fos = new DataOutputStream(new FileOutputStream(outputFile));
fos.write(buffer);
fos.flush();
fos.close();
}
catch(FileNotFoundException e)
{
return false;
}
catch (IOException e)
{
return false;
}
return true;
}
}
Refer to this thread:
android: file download in background
Use This Function In for Downloading Files On SDCARD
public void downloadNauhe(String url) {
class DownloadFile extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... url) {
int count;
try {
URL url1 = new URL("http://downloads.hussainiat.com/nauhey/arsalan_haider/vol_2011_-_12/01_tum_jawab_e_zulm_dogay_-_arsalan_haider_2011_-_2012.mp3");
URLConnection conexion = url1.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
InputStream input = new BufferedInputStream(url1.openStream());
OutputStream output = new FileOutputStream("/sdcard/01_manum_abbas_as_-_mesum_abbas_2012.mp3");
byte data[] = new byte[1024];
long total = 0;
System.out.println("downloading.............");
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int)((total/(float)lenghtOfFile)*100));
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);
mprBar.setProgress(values[0]);
}
}
DownloadFile downloadFile = new DownloadFile();
downloadFile.execute(url);
}
Don'forget to add permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>