Downloaded File is empty - android

I have created an async task to download a .csv file from a webserver. Unfortunately the file is stored in the right directory, but it's empty.
This is my async task
public class DownloadTask extends AsyncTask<String, Integer, String> {
private Context context;
private ProgressDialog prgDialog = null;
private PowerManager.WakeLock mWakeLock;
private String fileName;
public DownloadTask(Context context, String fileName) {
this.context = context;
this.fileName = fileName;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
/* Take CPU lock to prevent CPU from going off if the user
presses the power button during download */
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getName());
mWakeLock.acquire();
prgDialog = new ProgressDialog(context);
prgDialog.setMessage(context.getString(R.string.prgDialogMessage));
prgDialog.setCancelable(false); // Not able to cancel until programmatically called
prgDialog.show();
}
#Override
protected String doInBackground(String... sUrl) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
/* Expect HTTP 200 OK, to make sure the app doesn't mistakenly save an error report
instead of the file */
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return R.string.errorServer + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
// Download the file
input = connection.getInputStream();
// Get dynamic storage directory
File myFile= new File(Environment.getExternalStorageDirectory(), fileName);
output = new FileOutputStream(myFile);
} 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) {
mWakeLock.release();
if (prgDialog != null) {
if (prgDialog.isShowing()) {
prgDialog.dismiss();
}
prgDialog = null;
}
if (result != null) {
Toast.makeText(context,R.string.errorDownload + result, Toast.LENGTH_LONG).show();
}
}
}
I don't get any error messages or exceptions, so I don't know where the problem is. I consign the URL with the execute() function of the async task.
Thanks for helping me!

Related

Unsuccessful attempt to create a folder and save mp3 file in android

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"));

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 check if AsyncTask has downloaded one item of a set

My app is a media player, it plays media by downloading the appropriate files from the Internet. I am using AsyncTask to do this, however the task takes longer to execute when multiple files need to be downloaded which results in a media player delay.
The desired behavior is to start playing a file after it has been downloaded while continuing to download any other files.
My code is as follows:
public class DownloadTask extends AsyncTask<String, Integer, String> {
private Context context;
private PowerManager.WakeLock mWakeLock;
private String folder;
private ProgressDialog mProgressDialog;
private int noOfURLs;
private int noUrlLoad;
public DownloadTask(Context context, String folder, ProgressDialog mProgressDialog) {
this.context = context;
this.folder = folder;
}
#Override
protected String doInBackground(String... sUrl) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
noOfURLs = sUrl.length;
for (int i = 0; i < sUrl.length; i++) {
URL url = new URL(sUrl[i]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Máy chủ trả về HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength();
// download the file
input = connection.getInputStream();
output = new FileOutputStream(Environment.getExternalStorageDirectory() + "/" + folder + "/File" + (i + 1) + "." + sUrl[i].charAt(sUrl[i].length() - 3) + sUrl[i].charAt(sUrl[i].length() - 2) + sUrl[i].charAt(sUrl[i].length() - 1));
byte data[] = new byte[4096];
long total = 0;
int count;
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);
}
noUrlLoad++;
} 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 onPreExecute() {
super.onPreExecute();
// take CPU lock to prevent CPU from going off if the user
// presses the power button during download
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
getClass().getName());
mWakeLock.acquire();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
// if we get here, length is known, now set indeterminate to false
}
#Override
protected void onPostExecute(String result) {
mWakeLock.release();
mProgressDialog.dismiss();
if (result != null)
Toast.makeText(context, context.getString(R.string.error) + result, Toast.LENGTH_LONG).show();
}
}
Inside your doInBackground method, call publishProgress(Integer) to send your updates to the UI thread. This will trigger the onProgressUpdate method to be called, and you'll be able to see when the first download has finished.
http://developer.android.com/reference/android/os/AsyncTask.html#publishProgress(Progress...)

Multiple files download android

I want to download some files from url to refresh my app but I don´t know what is the best way to do this. I have this code to download one file but when I download more than one sometimes gives me an error. Is it possible to do the download in background without using Android Activity? Thank you
class DownloadTask extends AsyncTask<String, Integer, String> {
private Context context;
private PowerManager.WakeLock mWakeLock;
public DownloadTask(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// take CPU lock to prevent CPU from going off if the user
// presses the power button during download
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
getClass().getName());
mWakeLock.acquire();
mProgressDialog.show();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
// if we get here, length is known, now set indeterminate to false
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgress(progress[0]);
}
#Override
protected void onPostExecute(String result) {
mWakeLock.release();
mProgressDialog.dismiss();
if (result != null)
Toast.makeText(context,"Error en la descarga: "+result, Toast.LENGTH_LONG).show();
else
Toast.makeText(context,"Programa actualizado correctamente", Toast.LENGTH_LONG).show();
}
#Override
protected String doInBackground(String... sUrl) {
InputStream input = null;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength();
// download the file
input = connection.getInputStream();
fOut = openFileOutput("example.json",MODE_PRIVATE);
byte data[] = new byte[4096];
long total = 0;
int count;
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));
fOut.write(data, 0, count);
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (fOut != null)
fOut.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return null;
}
}
and I call to this task with:
downloadTask.execute("myurl");
private class DownloadAsynkTask extends AsyncTask<String, Void, Integer> {
#Override
protected void onPreExecute() {
// progress dialog
}
#Override
protected Integer doInBackground(String... urls) {
HttpURLConnection connection = null;
InputStream is = null;
for (int i=0; i< urls.length; i++) {
try {
URL url = new URL(urls[i]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return connection.getResponseCode();
} else {
is = connection.getInputStream();
}
// do something whit url data (add it to list maybe)
if (connection != null) {
connection.disconnect();
}
if (is != null) {
is.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return 1;
}
#Override
protected void onPostExecute(Integer result) {
if (result == 1) {
// OK
} else {
}
}
}
and call it whit String[] urls
new DownloadAsynkTask().execute(urls);

MalformedURLException in android when downloading a zip file

I m download a zip in android and got following errors.
InputStream Connection is null exception thrown is
java.net.MalformedURLException: Protocol not found: www.songspk320.in/128/indian/Don-2-2011-128Kbps(Songs.PK).zip
at java.net.URL.<init>(URL.java:273)
at java.net.URL.<init>(URL.java:157)
at com.linkezzi.web.DownloadIconSetZIP.openInputStreamConnection(DownloadIconSetZIP.java:73)
at com.linkezzi.web.DownloadIconSetZIP.doInBackground(DownloadIconSetZIP.java:45)
at android.os.AsyncTask$2.call(AsyncTask.java:185)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
at java.lang.Thread.run(Thread.java:1019)
Code is Given Below.
public class DownloadIconSetZIP extends AsyncTask {
private File root = null;
private String url = null;
private File pathToLinkEziiIconSetRootFolder = null;
private File toBeExtracted = null;
private FileOutputStream fOut = null;
private Context mContext = null;
private InputStream input = null;
public DownloadIconSetZIP(Context mContext,String uriZIP){
this.url = uriZIP;
this.mContext = mContext;
}
protected Object doInBackground(Object[] params) {
if(this.url != null){
root = Environment.getExternalStorageDirectory();
try {
Log.e("Downloading Iconset in BackGround","URl = "+ url);
openInputStreamConnection();
Log.e("Iconset is Downloading from the URI = ",url.toUpperCase());
pathSetInLocalFileSystem();
downloadFile(input);
}catch(MalformedURLException malformedURLException){
malformedURLException.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
private void openInputStreamConnection() throws IOException,
MalformedURLException {
try {
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
// conn.setDoInput(true);
conn.setConnectTimeout(30000); // timeout 10 secs
conn.connect();
input = conn.getInputStream();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
private void downloadFile(InputStream input) throws IOException {
int byteCount = 0;
byte[] buffer = new byte[1024];
int bytesRead = -1;
while ((bytesRead = input.read(buffer)) != -1) {
fOut.write(buffer, 0, bytesRead);
byteCount += bytesRead;
}
fOut.flush();
fOut.close();
}
private void pathSetInLocalFileSystem() throws FileNotFoundException {
pathToLinkEziiIconSetRootFolder = searchFileInThisDirectory(root);
if(pathToLinkEziiIconSetRootFolder == null){
pathToLinkEziiIconSetRootFolder = new File(root.getAbsolutePath(),"LinkEziiIconsets");
if(!pathToLinkEziiIconSetRootFolder.exists() && pathToLinkEziiIconSetRootFolder.mkdir()){
Log.e("LinkEzii Iconset Container Folder is Created","LinkEzii Iconset Container Folder is Created");
}else{
Log.e("LinkEzii Iconset Container is Not Created","LinkEzii Iconset Container is Not Created");
}
}
File downloadedIconSetFile = new File(pathToLinkEziiIconSetRootFolder.getAbsolutePath(),"IconSetName Comes Here...");
if(!downloadedIconSetFile.exists()){
downloadedIconSetFile.mkdir();
Log.e("Container is Created for Iconset","Container is Created for iconset");
}
if(downloadedIconSetFile!=null){
toBeExtracted = new File(downloadedIconSetFile, "IconSet Zip Format.zip");
fOut = new FileOutputStream(toBeExtracted);
}
}
private File searchFileInThisDirectory(File file) throws NullPointerException {
if(file == null){
throw new NullPointerException();
}
File[] listFiles = file.listFiles();
File pathToLinkEziiIconSetRootFolder = null;
for(File searchIT: listFiles){
if(file.isDirectory() && file.getName().equals("LinkEziiIconsets")){
pathToLinkEziiIconSetRootFolder = file;
return pathToLinkEziiIconSetRootFolder;
}
}
return pathToLinkEziiIconSetRootFolder;
}
protected void onCancelled() {
super.onCancelled();
Log.i("Downloading is Cancelled","Download is Cancelled");
}
protected void onPostExecute(Object result) {
super.onPostExecute(result);
// Decompressing the File
if(toBeExtracted != null){
// Just to Move the Decompressing to the Back Ground Thread
new Thread(new Runnable() {
#Override
public void run() {
DecompressDownloadedDiagram decompressdDownloadedDiagram = new DecompressDownloadedDiagram(toBeExtracted.getPath(), toBeExtracted.getPath(),toBeExtracted);
decompressdDownloadedDiagram.unzip();
toBeExtracted.delete();
}
}).start();
Toast.makeText(mContext, "Icons Set is Successfully Downloaded", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(mContext, "Error! while downloading diagram", Toast.LENGTH_LONG).show();
Log.e("Some Error Occure While Downloading Diagram","Some Error Occure While Downloading Diagram");
}
Log.i("Downloading is Successful","Downloading is Successful");
}
protected void onPreExecute() {
super.onPreExecute();
Log.i("Downloading is Starting","Downloading is Starting");
}
protected void onProgressUpdate(Object[] values) {
super.onProgressUpdate(values);
Log.i("Downlaoding is in Progress","Downloading is in Progress");
}
}
MalformedURLException generally thrown when there is no protocol attached with the system you have to check whether any protocol is that by checking whether :// is present in your URL string.. If your url is having www you can check it with whole http://.
Find occurrence of http:// by calling contains() method on your url string. If you can find check whether they are starting characters of string call url.startsWith("http://") to make sure this exception can not be thrown.
If none of above tests pass just add this line.
url = "http://"+url;

Categories

Resources