Can't download any file with AsyncTask on mobile network - android

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

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

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!

Parsing error on downloaded apk for autoupdate

I want to implement autoupdate for my app.
I used the DownloadManager (and now an AsyncTask for download) and install the file.
The download is working fine. On the PostExecute I fire an intent to install the new apk. Everytime i got a parsing error.
When I open the file in ES File Explorer, I am able to install it successfully, but not within the app and the intent.
I even changed from /Android/data/packagename/files to /Download but still not working.
PS: i know the code is dirty, but working, and I changed so often so many thinks to get it work, but it doesnt...
public class UpdateAsyncTask extends AsyncTask<String, Integer, String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(LoginActivity.this);
mProgressDialog.setMessage("A message");
mProgressDialog.setIndeterminate(true);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
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]);
}
protected String doInBackground(String... arg0) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
//URL url = new URL(arg0[0]);
URL url = new URL(apkUrl);
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();
//output = new FileOutputStream(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString() + "Straffv2.apk");
output = new FileOutputStream("/storage/emulated/0/Download/Straffv2.apk");
File outputFile = new File(Environment.DIRECTORY_DOWNLOADS, "Straffv2.apk");
outputFile.setReadable(true, false);
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);
}
} 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;
}
protected void onPostExecute(String result){
mProgressDialog.dismiss();
if (result != null) {
//Toast.makeText(LoginActivity.this,"Download error: "+result, Toast.LENGTH_LONG).show();
}
else {
//Toast.makeText(LoginActivity.this,"File downloaded", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(Environment.DIRECTORY_DOWNLOADS, "Straffv2.apk")), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // without this flag android returned a intent error!
LoginActivity.this.startActivity(intent);
}
}
}

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