Downloading pdf from a link in Android [closed] - android

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I need to download the pdf from below URL in Android. Any idea how this can be done:
http://bkinfo.in/Murli/1305/EME-26-05-2013.pdf
Similarly, there is an mp3:
http://bkinfo.in/Murli/1305/26-05-2013.mp3
Appreciate the ideas..
Finally....
Here is the full code that I used. May be useful for someone..
Add these to manifest:
Make sure your AVD can write to SDCard(if you are writing to card). U can set it by assigning memory chunck to SDCard in AVD Manager.
public class MainActivity extends Activity {
static ProgressDialog pd;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pd = new ProgressDialog(this);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setCancelable(false);
AsyncTaskTest at = new AsyncTaskTest();
at.execute();
}
public class AsyncTaskTest extends AsyncTask<Void, Integer, Integer> {
Session s = null;
protected void onPreExecute(){
pd.show();
}
protected Integer doInBackground(Void... vd){
try{
String[] urls = new String[3];
urls[0] = "http://bkinfo.in/Murli/1305/HMS-25-05-2013.pdf";
urls[1] = "http://bkinfo.in/Murli/1305/EME-25-05-2013.pdf";
urls[2] = "http://bkinfo.in/Murli/1305/25-05-2013.mp3";
String fileName = urls[2].substring(urls[2].lastIndexOf("/")+1); //Coupying the mp3
URL url = new URL(urls[2]);
URLConnection conection = url.openConnection();
conection.setConnectTimeout(10000);
conection.connect();
int lenghtOfFile = conection.getContentLength();
InputStream input = new BufferedInputStream(url.openStream(),8192);
OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory()+"/"+fileName);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1){
total += count;
output.write(data, 0, count);
publishProgress((int) ((total * 100) / lenghtOfFile));
}
output.flush();
output.close();
input.close();
}catch(Exception e){
Log.e("MyError:",e.toString());
}
return 0;
}
protected void onProgressUpdate(Integer... msg) {
pd.setProgress(msg[0]);
}
protected void onPostExecute(Integer in){
pd.dismiss();
showDialog("Done !");
}
private void showDialog(String msg){
final AlertDialog.Builder alertBox = new AlertDialog.Builder(new ContextThemeWrapper(MainActivity.this, android.R.style.Theme_Dialog));
alertBox.setMessage(msg);
alertBox.setCancelable(false)
.setPositiveButton("Ok", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog,int id){
dialog.cancel();
}
}).show();
}
}
}

Hope I am not spoon feeding! I have some tough time so I decided to share my working code.
private void downloadCommandFile(String dlUrl){
int count;
try {
URL url = new URL( dlUrl );
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoInput(true);
con.setDoOutput(true);
con.connect();
int fileSize = con.getContentLength();
Log.d("TAG", "Download file size = " + fileSize );
InputStream is = url.openStream();
String dir = Environment.getExternalStorageDirectory() + "dl_directory";
File file = new File( dir );
if( !file.exists() ){
file.mkdir();
}
FileOutputStream fos = new FileOutputStream(file + "EME-26-05-2013.pdf");
byte data[] = new byte[1024];
while( (count = is.read(data)) != -1 ){
fos.write(data, 0, count);
}
is.close();
fos.close();
} catch (Exception e) {
Log.e("TAG", "DOWNLOAD ERROR = " + e.toString() );
}
}
public class DownloadTask extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
String url = "http://bkinfo.in/Murli/1305/EME-26-05-2013.pdf"; // your url here
downloadCommandFile( url);
return null;
}
#Override
protected void onPostExecute(String result) {
// download complete
}
}
Call Async Task as follows:
new DownloadTask().execute();
And don't forget to add this to your manifest file:
<uses-permission android:name="android.permission.INTERNET"/>

Related

Delete file if AsyncTask Fail

Currently
I am downloading a file from a URL, I'm doing this within AsyncTask inside a Adapter. The problem I have is that when I press back onBackPressed the download stops but the file remains in the folder FileOutputStream(Environment.getExternalStorageDirectory().toString()+"/file.mp4");
My Question
Is it possible to delete the file if AsyncTask does not complete?
I have tried to do file.delete(); in the catch of doinbackground but I get error file.delete(); is ignored
Here is a summary of my adapter----
When Item in holder is clicked I call AsyncTask:
holder.setItemClickListener(new ItemClickListener() {
if (pos == 1) {
if(manager.fetchVideoPath(pos)==null) {
DownloadFileFromURL p = new DownloadFileFromURL();
p.execute(pos + "", "https://www.dropbox.com/s/xnzw753f13k68z4/Piper%20First%20Look%20%282016%29%20-%20Pixar%20Animated%20Short%20HD.mp4?dl=1");
a = "one";
bars.set(pos,new ProgressModel(pos,1));
//This is what is causing the issue
RecyclerVideoAdapter.this.notifyItemChanged(pos);
}
My AsyncTask:
private class DownloadFileFromURL extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
((CircularProgressBar)vview.findViewById(R.id.circularProgressBar)).setProgress(1);
}
#Override
protected String doInBackground(String... f_url) {
int count;
String pathreference = f_url[0]+",";
positionnumber = Integer.parseInt(f_url[0]);
try {
URL url = new URL(f_url[1]);
URLConnection conection = url.openConnection();
conection.connect();
int lenghtOfFile = conection.getContentLength();
InputStream input = new BufferedInputStream(url.openStream(),
8192);
if (a.equals("one")) {
OutputStream output = new FileOutputStream(Environment
.getExternalStorageDirectory().toString()
+ "/file.mp4");
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();
pathreference = pathreference+Environment.getExternalStorageDirectory().toString()+"/file.mp4";
output.close();
input.close();
}
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return pathreference;
}
protected void onProgressUpdate(String... progress) {
bars.get(positionnumber).setProgress_(Float.parseFloat(progress[0]));
((CircularProgressBar)vview.findViewById(R.id.circularProgressBar)).setProgress(bars.get(positionnumber).getProgress_());
}
#Override
protected void onPostExecute(String file_url) {
String []split = file_url.split(",");
int index1 = Integer.parseInt(split[0]);
videoHolderClass.set(index1,new VideoHolderClass(index1,imgres[0]));
bars.get(index1).setProgress_(0);
manager.insertVideoPath(index1+"",split[1]);
RecyclerVideoAdapter.this.notifyItemChanged(index1);
}
}
Building on the answer on this post, try to put the logic of deleting the file inside isCancelled() like this:
if (isCancelled() && file.exists())
file.delete();
else
{
// do your work here
}
Then you can call p.cancel(true) inside onBackPressed

android :: show progress dialog till asynctask does not get complete

I am downloading a zip file of 15 mb and then unzip it in the sd card.
I am using progress dialog to show the status. First time it works perfectly, and when I change the db version number on server to download new file and start the app again then progress dialog disappears in between and causes crash in the app.
Below is the code.
class CheckInAppUpdatesAsyncTask extends AsyncTask<Void, Void, Void> {
Dialog progress;
#Override
protected Void doInBackground(Void... params) {
try {
downloadDB();
} catch (Exception e) {
}
}
#Override
protected void onPostExecute(final Void result) {
stopWorking();
}
#Override
protected void onPreExecute() {
startWorking();
}
};5
private void startWorking() {
synchronized (this.diagSynch) {
if (this.pDiag != null) {
this.pDiag.dismiss();
}
this.pDiag = ProgressDialog.show(Browse.context, "Working...",
"Please wait while we load the encyclopedia.", true, false);
}
}
private void stopWorking() {
synchronized (this.diagSynch) {
if (this.pDiag != null) {
this.pDiag.dismiss();
}
}
}
Download code
URL url = new URL(serverFileURL);
Log.d("FILE_URLLINK", "serverFileURL " + serverFileURL);
URLConnection connection = url.openConnection();
InputStream input = connection.getInputStream();
connection.getContentLength();
byte data[] = new byte[1024];
input = new GZIPInputStream(input);
InputSource is = new InputSource(input);
InputStream in = new BufferedInputStream(is.getByteStream());
String inAppDBName = Constants.NEW_DB_NAME_TO_DOWNLOAD;
OutputStream output = new BufferedOutputStream(new FileOutputStream(dir + "/" + inAppDBName));
int length;
while ((length = in.read(data)) > 0) {
output.write(data, 0, length);
}
output.flush();
output.close();
input.close();
Any idea?
You should put unzip code before stopWorking(); in onPostExecute.
It will not close till all things happen.

Ekito Simple KML read source

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

AsyncTask How to get progress from MainActivity [duplicate]

This question already has answers here:
Download a file with Android, and showing the progress in a ProgressDialog
(16 answers)
Closed 8 years ago.
Hello i am writing a download project and i'm stuck right here.
#Override
protected void onProgressUpdate(Integer... progress) {
}
//I'm using in my mainactivity like that
Download download = new Download();
download.execute("http://");
I want to get progress when updated and yeah i can do this using onProgressUpdate but i wonder about can i get it from my mainactivity i mean where i called the class. I love that kinda dynamic classes because i can use them easily my every project. Thank you btw forgive me for my grammar.
I can see two options here :
You either pass the object where you want to display the progress to your AsyncTask with the constructor and then you store it :
private ProgressObject mObject;
public void MyAsyncTask(ProgressObject object) {
mObject = object
}
And the update in the onProgress() method :
object.setProgress(); //assuming the ProgressObject has a method setProgress() obviously
Or you can set up some kind of listener :
public interface ProgressListener() {
public void onProgress(int progress);
}
private mProgressListener;
public void MyAsyncTask(ProgressListener listener) {
mProgressListener = listener;
}
then use it in the onProgress() method :
mProgressListener.onProgress(80);
Just some examples, not much but I hope that help.
Use this
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;
File root = android.os.Environment.getExternalStorageDirectory();
//
File dir = new File (root.getAbsolutePath()+"/downoad"); //make ur folder to put download
if(dir.exists()==false) {
dir.mkdirs();
}
File file = new File(dir, "enter file name");
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(file);
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);
Toast.makeText(DisplayActivity.this,"Successfully downloaded in phone memory.", Toast.LENGTH_SHORT).show();
}
}
How to call?
new DownloadFileAsync().execute("your URL");

How to use AsyncTask to download files? [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I'm Using this class to download files:
public class DownloadService extends Service {
String downloadUrl;
LocalBroadcastManager mLocalBroadcastManager;
ProgressBar progressBar;
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/org.test.download/");
double fileSize = 0;
DownloadAsyncTask dat;
#Override
public IBinder onBind(Intent arg0) {
return null;
}
public DownloadService(String url,Context c, ProgressBar pBar){
downloadUrl = url;
mLocalBroadcastManager = LocalBroadcastManager.getInstance(c);
progressBar = pBar;
dat = new DownloadAsyncTask();
dat.execute(new String[]{downloadUrl});
}
private boolean checkDirs(){
if(!dir.exists()){
return dir.mkdirs();
}
return true;
}
public void cancel(){
dat.cancel(true);
}
public class DownloadAsyncTask extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... params) {
String fileName = downloadUrl.substring(downloadUrl.lastIndexOf("/")+1);
if(!checkDirs()){
return "Making directories failed!";
}
try {
URL url = new URL(downloadUrl);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
fileSize = urlConnection.getContentLength();
FileOutputStream fos = new FileOutputStream(new File(dir,fileName));
InputStream inputStream = urlConnection.getInputStream();
byte[] buffer = new byte[500];
int bufferLength = 0;
int percentage = 0;
double downloadedSize = 0;
while ( (bufferLength = inputStream.read(buffer)) > 0 )
{
if(isCancelled()){
break;
}
fos.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
percentage = (int) ((downloadedSize / fileSize) * 100);
publishProgress(percentage);
}
fos.close();
urlConnection.disconnect();
} catch (Exception e) {
Log.e("Download Failed",e.getMessage());
}
if(isCancelled()){
return "Download cancelled!";
}
return "Download complete";
}
#Override
protected void onProgressUpdate(Integer... values){
super.onProgressUpdate(values[0]);
if(progressBar != null){
progressBar.setProgress(values[0]);
}else{
Log.w("status", "ProgressBar is null, please supply one!");
}
}
#Override
protected void onPreExecute(){
mLocalBroadcastManager.sendBroadcast(new Intent("org.test.download.DOWNLOAD_STARTED"));
}
#Override
protected void onPostExecute(String str){
mLocalBroadcastManager.sendBroadcast(new Intent("org.test.download.DOWNLOAD_FINISHED"));
}
#Override
protected void onCancelled(){
mLocalBroadcastManager.sendBroadcast(new Intent("org.test.download.DOWNLOAD_CANCELLED"));
}
}
}
I'm using this because apparently DownloadManager wont work prior to API 9 and i'm targeting API 7
I have ListView which parses a XML File and shows packages that can be downloaded.
How can I modify this class to accept Array of strings containing URLs and download them one by one ?
Or is there any good way to download List of files ?
Look into using an IntentService. The thread in an IntentService runs in the background, which means you don't have to handle all the mess of thread handling.
IntentService kills off its thread once its done, so you have to persist the data.
To communicate back to your Activity, use a broadcast receiver.

Categories

Resources