I'm trying to download a zip file from an API. For this purpose I'm using this following code:
public class Download_Activity extends Activity {
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private Button startBtn;
private ProgressDialog mProgressDialog;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.download);
startBtn = (Button) findViewById(R.id.downloadButton);
startBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startDownload();
}
});
}
private void startDownload() {
String url = downloadURL;
new DownloadFileAsync().execute(url);
}
#Override
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;
}
}
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 urlConnection = url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.connect();
Log.i("1111", "1111" );
File SDCardRoot = Environment.getExternalStorageDirectory();
File file = new File(SDCardRoot, "hello1.zip");
Log.i("2222", "2222" );
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
int totalSize = urlConnection.getContentLength();
int downloadedSize = 0;
byte[] buffer = new byte[1024];
int bufferLength = 0;
Log.i("3333", "3333" );
Log.i("befferLength", "bufferLength: " + bufferLength);
Log.i("is read buffer", "is read buffer: " + inputStream.read(buffer));
while ((bufferLength = inputStream.read(buffer)) > 0) {
Log.i("inside while", "inside while ");
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
updateProgress(downloadedSize, totalSize);
}
Log.i("4444", "4444" );
fileOutput.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);
}
}
public void updateProgress(int currentSize, int totalSize) {
Toast.makeText(getApplicationContext(), "Loading Files...",
Toast.LENGTH_SHORT).show();
}
In this code, the zip file is created as "hello1.zip" but this file is empty in my mobile. Here I've various log statements to find the execution of code. To my surprise only upto "Log.i("2222", "2222" );" is printed while the rest of the logs are not printed. Can you please tell me what the problem is???
Thanks in advance..!
U can use DownloadManager class for this purpose it handles the pause and continues the dowloading in the case of network availablity and you can run a broadcast reciver to perform you actions( like pushing a notification etc) when dowloading is complete
http://developer.android.com/reference/android/app/DownloadManager.html
Related
I need to download zip file using multiple URL's and this is my postman
[URL's in postman]
public class downloadfile extends Activity {
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private Button starbtn;
private ProgressDialog mProgress;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startbtn = (Button)findViewById(R.id.startbtn);
startbtn.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
startDown();
}
});
}
private void startDown() {
String url = "http://farm1.static.flickr.com/114/298125983_0e4bf66782_b.zip";
new DownloadFileAsync().execute(url);
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgress = new ProgressDialog(this);
mProgress.setMessage("Downloading file..");
mProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgress.setCancelable(false);
mProgress.show();
return mProgress;
default:
return null;
}
}
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);
inputStreamStream inputStream = new BufferedinputStreamStream(url.openStream());
outputStreamStream outputStream = new FileoutputStreamStream("/sdcard/some_photo_from_gdansk_poland.zip");
byte data[] = new byte[1024];
long total = 0;
while ((count = inputStream.read(data)) != -1) {
total += count;
publishProgress(""+(int)((total*100)/lenghtOfFile));
outputStream.write(data, 0, count);
}
outputStream.flush();
outputStream.close();
inputStream.close();
} catch (Exception e) {}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC",progress[0]);
mProgress.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
}
I have one KML at this link:
http://myurl.com/mykml.kml
I want to get the com.ekito.simpleKML.model KML object from it.
I'm trying with this:
String url = "http://myurl.com/mykml.kml";
Serializer kmlSerializer = new Serializer();
Kml kml = kmlSerializer.read(url);
But the kml object is still null.
This is the link to the Ekito Simple KML library: https://github.com/Ekito/Simple-KML
I see the Ekito he can not read a file on the internet. Test this example!
private ProgressDialog progressBar;
public static final int KML_PROGRESS = 0;
public String fileURL ="http://myurl.com/mykml.kml";
// set in OnClick Button
new DownloadKML().execute(fileURL);
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case KML_PROGRESS:
progressBar = new ProgressDialog(this);
progressBar.setMessage("Downloading fileā¦");
progressBar.setIndeterminate(false);
progressBar.setMax(100);
progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressBar.setCancelable(true);
progressBar.show();
return progressBar;
default:
return null;
}
}
class DownloadKML extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(KML_PROGRESS);
}
#Override
protected String doInBackground(String... url) {
int count;
try {
URL url = new URL( url[0] );
URLConnection connect = url.openConnection();
connect.connect();
int progressOfFile = connect.getContentLength();
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/KML_Samples.kml");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress(""+(int)((total*100)/progressOfFile) );
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {}
return null;
}
protected void onProgressUpdate(String... progress) {
progressBar.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
String pathKML = Environment.getExternalStorageDirectory().toString() + "/KML_Samples.kml";
// load
Serializer kmlSerializer = new Serializer();
Kml kml = kmlSerializer.read(url);
}
}
I'm trying to create a method within my activity that will unzip the downloaded file to a certain directory. I have tried several different ways and haven't had much luck. I've seen some people use a separate class to do this task, I want to avoid doing that, but if it's my only option then I will do it. Here is my activity:
public class lava_parkour extends Activity {
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private Button startBtn;
private ProgressDialog mProgressDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lava_parkour);
startBtn = (Button)findViewById(R.id.button1);
startBtn.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
startDownload(v);
} });
}
private void startDownload(View v) {
String url = "https://www.dropbox.com/s/lxnizie52efq3e8/lava%20parkour.zip?
dl=1";
new DownloadFileAsync().execute(url);
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Downloading...");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
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("/sdcard/games/com.mojang/lava_parkour.zip");
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(lava_parkour.this, "Process completed! THis map has been added
to your game!", Toast.LENGTH_LONG).show();
}
}
}
Any help is appreciated!
i have this url http://translate.google.com/translate_tts?ie=UTF-8&q=hi&tl=en&total=1&idx=0&textlen=2
when i place it to pc and android browser it makes me force to download
how can i make it download in my android application without browser.
i tried to make to download using this tutorial how can i download audio file from server by url
.but it did not work.
anyone please help
Thank you Kristijana Draca think it is working but where it save in emulator here is my code public class Main extends Activity {
EditText inputtext;
Button listen;
Button shareButton;
TextView tv;
ProgressBar proBar;
//ProgressDialog progress;
MediaPlayer player;
public Boolean isPlaying=true;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
downloadContent();
}
private void downloadContent() {
DownloadFile downloadFile = new DownloadFile();
downloadFile.execute("http://translate.google.com/translate_a/t?client=t&source=baf&sl=ar&tl=en&hl=en&q=%D9%85%D8%B1%D8%AD%D8%A8%D8%A7&sc=1 ");
}
// usually, subclasses of AsyncTask are declared inside the activity class.
// that way, you can easily modify the UI thread from here
class DownloadFile extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... sUrl) {
try {
URL url = new URL(sUrl[0]);
URLConnection connection = url.openConnection();
connection.connect();
int fileLength = connection.getContentLength();
InputStream input = new BufferedInputStream(
connection.getInputStream());
// Create db
OutputStream output = new FileOutputStream(
Environment.getDataDirectory() + "/data/"
+ "com.jony.com" + "/file.mp3");
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
Toast.makeText(getApplicationContext(), "download complete", 1000).show();
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Toast.makeText(getApplicationContext(), "download complete", 1000).show();
}
}
});
You can download any file using AsyncTask.
downloadContent();
private void downloadContent() {
DownloadFile downloadFile = new DownloadFile();
downloadFile.execute("http://somehost.com/file.mp3");
}
// usually, subclasses of AsyncTask are declared inside the activity class.
// that way, you can easily modify the UI thread from here
private class DownloadFile extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... sUrl) {
try {
URL url = new URL(sUrl[0]);
URLConnection connection = url.openConnection();
connection.connect();
int fileLength = connection.getContentLength();
InputStream input = new BufferedInputStream(
connection.getInputStream());
// Create db
OutputStream output = new FileOutputStream(
Environment.getDataDirectory() + "/data/"
+ PACKAGE_NAME + "/file.mp3");
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
}
i keep getting this error telling me to suppress my showdialog code for my progress bar.
now what can i do to fix this, also i dont want to use any other way. im trying to learn showdialog for downloads
here my code
public class download extends Activity {
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private Button startBtn;
private ProgressDialog mProgressDialog;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startBtn = (Button)findViewById(R.id.startBtn);
startBtn.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
startDownload();
}
});
}
private void startDownload() {
String url = "http://practicalbuddhist.com/wp-content/uploads/2012/03/Synapses-Image-for-March-17-2010-Blog-Entry.jpg";
new DownloadFileAsync().execute(url);
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Running Download Test...");
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("/sdcard/Downloadtest.jpg");
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);
}
}
}
Use the Dialog class methods directly not the Activity helper methods.
In the Dialog API guide at http://developer.android.com/guide/topics/ui/dialogs.html they say explicitly to do not use ProgressDialog but use a custom layout with a ProgressBar.
On the other hand you could just use the DownloadManager to download files asynchrously. Check https://github.com/commonsguy/cw-android/blob/master/Internet/Download/src/com/commonsware/android/download/DownloadDemo.java for a simple example even with notifications.
If you still wants this method check http://www.androidhive.info/2012/04/android-downloading-file-by-showing-progress-bar/ for a simple example using a ProgressDialog-