Android - How to Download a File from a Webserver

Android - How to download a file from a webserver

Using Async task

call when you want to download file : new DownloadFileFromURL().execute(file_url);

public class MainActivity extends Activity {

// Progress Dialog
private ProgressDialog pDialog;
public static final int progress_bar_type = 0;

// File url to download
private static String file_url = "http://www.qwikisoft.com/demo/ashade/20001.kml";

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

new DownloadFileFromURL().execute(file_url);

}

/**
* Showing Dialog
* */

@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type: // we set this to 0
pDialog = new ProgressDialog(this);
pDialog.setMessage("Downloading file. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(true);
pDialog.show();
return pDialog;
default:
return null;
}
}

/**
* Background Async Task to download file
* */
class DownloadFileFromURL extends AsyncTask<String, String, String> {

/**
* Before starting background thread Show Progress Bar Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}

/**
* Downloading file in background thread
* */
@Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection connection = url.openConnection();
connection.connect();

// this will be useful so that you can show a tipical 0-100%
// progress bar
int lenghtOfFile = connection.getContentLength();

// download the file
InputStream input = new BufferedInputStream(url.openStream(),
8192);

// Output stream
OutputStream output = new FileOutputStream(Environment
.getExternalStorageDirectory().toString()
+ "/2011.kml");

byte data[] = new byte[1024];

long total = 0;

while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
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;
}

/**
* Updating progress bar
* */
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialog.setProgress(Integer.parseInt(progress[0]));
}

/**
* After completing background task Dismiss the progress dialog
* **/
@Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
dismissDialog(progress_bar_type);

}

}
}

if not working in 4.0 then add:

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

Download file from a webserver into android external storage

You can use AndroidDownloadManager.

This Class handles all the steps of the download of a file and gets you information about the progress ext...

You should avoid the use of threads.

This is how you use it:

public void StartNewDownload(url) {       
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url)); /*init a request*/
request.setDescription("My description"); //this description apears inthe android notification
request.setTitle("My Title");//this description apears inthe android notification
request.setDestinationInExternalFilesDir(context,
"directory",
"fileName"); //set destination
//OR
request.setDestinationInExternalFilesDir(context, "PATH");
DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
final long downloadId = manager.enqueue(request); //start the download and return the id of the download. this id can be used to get info about the file (the size, the download progress ...) you can also stop the download by using this id
}

Download file from webserver and read content on android

so downloading to SD card is working

protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
InputStream input = new BufferedInputStream(url.openStream(), 8192);
File SDCardRoot = Environment.getExternalStorageDirectory();
SDCardRoot = new File(SDCardRoot.getAbsolutePath() + "/plus");
SDCardRoot.mkdir();
File file = new File(SDCardRoot,"settings.dat");
FileOutputStream output = new FileOutputStream(file);
byte data[] = new byte[1024];

while ((count = input.read(data)) != -1) {
output.write(data, 0, count);
}

output.flush();
output.close();
input.close();

} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}

and reading:

    new DownloadFileFromURL().execute("http://www.example.com/file.txt");
if (!Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
Log.d(LOG_TAG, "SD n\a " + Environment.getExternalStorageState());
return;
}
File sdPath = Environment.getExternalStorageDirectory();
sdPath = new File(sdPath.getAbsolutePath() + "/plus");
File sdFile = new File(sdPath, "settings.dat");
try {
BufferedReader br = new BufferedReader(new FileReader(sdFile));
String str = "";
while ((str = br.readLine()) != null) {
String[] words = str.split(",");
// do some work
}
}
Log.d(LOG_TAG, str);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}

Android Download file from a link

Inside you manifest file you need to add an intent filter:

    <activity
android:name="Downloader">
<intent-filter>
<action android:name="android.intent.action.VIEW" />

<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />

<data
android:host="domain.com"
android:scheme="http" />
</intent-filter>
</activity>

Then inside your "Download" activity's onCreate:

public class Download extends Activity {

private String filename;

@Override
protected void onCreate (final Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView(<your layout file>);
final Intent intent = getIntent ();
final Uri data = intent.getData ();
if (data != null) {
final List<String> pathSegments = data.getPathSegments ();
fileName = pathSegments.get (pathSegments.size () - 1);
}
}

Then in the clickhandler for the download button you can use a view intent to act like a link in android.

button.setOnClickListener (new View.OnClickListener () {
@Override public void onClick (final View v) {
Uri intentUri = Uri.parse("http://domain.com/" + filename);

Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setData(intentUri);
startActivity(intent);
}
});

How to download a file from a server and save it in specific folder in SD card in Android?

Your download URL is not a link to any file. It's a directory. Make sure its a file and exists. Also check your logcat window for error logs. One more suggestion, its always better to do a printStackTrace() in catch blocks instead of Logs. Its gives a more detailed view of the error.

Change this line:

    URL url = new URL("http://myexample.com/android/");

to:

    URL url = new URL("http://myexample.com/android/yourfilename.txt"); //some file url

Next, in catch block, add this line:

e.printStackTrace();

Also in the directory path, it should be something like this:

File dir = new File(root.getAbsolutePath() + "/mnt/sdcard/myclock/databases");

instead of

File dir = new File(root.getAbsolutePath() + "/myclock/databases");

Next, make sure you have acquired permission for writing to external storage in Android manifest.

Android - Download all files from a folder on server

I would suggest you to have a script at server's end, which first gives you list of all the files inside a folder, and then your application downloads each file one by one.

Download a file programmatically on Android

This is some working code I have for downloading a given URL to a given File object. The File object (outputFile) has just been created using new File(path), I haven't called createNewFile or anything.

private static void 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; // swallow a 404
} catch (IOException e) {
return; // swallow a 404
}
}


Related Topics



Leave a reply



Submit