Reputation: 42844
What i have:
What i am trying to do:
I want to download the file to my RAW folder
of my android project
I am familiar with AsyncTask
and HttpClient
but what
methodology(steps) should I follow to download the file?
I tried searching for a similar question in stackoverflow but couldn't find one so posting a question myself
Upvotes: 0
Views: 946
Reputation: 38141
You cannot download a file into "assets" or "/res/raw". Those get compiled into your APK.
You can download the file to your apps internal data directories. See Saving Files | Android Developers.
There are plenty of examples and libraries to help you with the download. The following is a static factory method you could use in your project:
public static void download(String url, File file) throws MalformedURLException, IOException {
URLConnection ucon = new URL(url).openConnection();
HttpURLConnection httpConnection = (HttpURLConnection) ucon;
int responseCode = httpConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedInputStream bis = new BufferedInputStream(ucon.getInputStream());
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.close();
bis.close();
}
}
Then, to download a file from Dropbox:
String url = "https://dl.dropboxusercontent.com/u/27262221/test.txt";
File file = new File(getFilesDir(), "test.txt");
try {
download(url, file);
} catch (MalformedURLException e) {
// TODO handle error
} catch (IOException e) {
// TODO handle error
}
Please note that the above code should be run from a background thread or you will get a NetworkOnMainThreadException
.
You will also need to declare the following permission in your AndroidManifest:
<uses-permission android:name="android.permission.INTERNET" />
You can find some helpful libraries here: https://android-arsenal.com/free
I personally recommend http-request. You could download your dropbox file with HttpRequest like this:
HttpRequest.get("https://dl.dropboxusercontent.com/u/27262221/test.txt").receive(
new File(getFilesDir(), "test.txt"));
Upvotes: 2