How to download a file in Android - android

What i have:
I have uploaded a .json file to the Dropbox of my account I have
made it public
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

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

Related

Parse error when programmatically installing an APK

I am trying to create a mechanism for an app to update itself by downloading and installing a later APK from within the app.
I have an APK located on a server which installs fine if I simply navigate to the URI then open the .apk file. The problem comes when I try to install it programmatically. I get "Parse Error - There was a problem while parsing the package"
The target phone allows install from unknown sources and within AndroidManifest.xml I request these permissions:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>
<uses-permission android:name="android.permission.REQUEST_WRITE_PERMISSION"/>
The code to perform the update has been taken from another thread here on StackOverflow and changed slightly to suit my particular situation.
public class UpdateApp extends AsyncTask<String,Void,Void> {
private Context context;
public void setContext(Context contextf){
context = contextf;
}
#Override
protected Void doInBackground(String... arg0) {
try {
URL url = new URL(arg0[0]);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setDoOutput(true);
conn.connect();
File file = context.getCacheDir();
file.mkdirs();
File outputFile = new File(file, "update.apk");
if(outputFile.exists()){
outputFile.delete();
}
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = conn.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(outputFile), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
} catch (Throwable ex) {
Toast.makeText(context, ex.toString(), Toast.LENGTH_LONG).show();
}
return null;
}
}
What can I try in order to understand why the APK is generating an error when installed from within the code but installs without issue when downloaded from the server?
The app is being built for API 23 although it will be required to work with API 24 once complete.
You will have to make your cached apk file world-readable.
After is.close();
put
outputFile.setReadable(true, false);
This works for me on Android 8
startActivity(Intent(Intent.ACTION_VIEW).apply {
type = "application/vnd.android.package-archive"
data = FileProvider.getUriForFile(applicationContext, "$packageName.fileprovider", file)
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
})

Downloading and saving images from https URLs in android

I have this function that downloads and saves images in device -
public void DownloadFromUrl(String WebURL, String fileName) {
try {
URL url = new URL(WebURL);
file = new File(context.getFilesDir() + fileName+".jpg");
long startTime = System.currentTimeMillis();
URLConnection ucon = url.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
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();
} catch (IOException e) {
Log.d("ImageManager", "Error: " + e);
}
}
If I supply an https URL, it cannot save the image. Any pointers on how to download and save https images ?
I hope this link will help you. Uploading/Downloading Pictures by Tonikami.
https://www.youtube.com/playlist?list=PLe60o7ed8E-Q7tqKNPnWFdUoeniqH_-A9
Just use Picasso or Glide. It is super easy to use. And the best part is that it does automatic disk and memory caching, so you do not have to worry about anything.
Picasso - check out this link.
OR
Glide - check out this link.
The only mistake I made above is that I was trying to download and save large images when connectivity was slow. Some of my images are around 5-10 MB. Otherwise the code is fine.

Download file from a webserver into android external storage

In an android app, I am trying to download a file from a web server to /Download folder on external storage. download code is executed in a HandlerThread in a service. The service is doing other functions apart from downloading file. the code for downloading goes like this:
public void downloadFile(){
new Thread(new Runnable() {
#Override
public void run() {
try{
URL url = new URL("http://192.168.1.105/download/apkFile.apk");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
InputStream inputStream = connection.getInputStream();
File file = new File(Environment.getExternalStorageDirectory().getPath()+"/Download/apkFile.apk");
FileOutputStream fileOutputStream = new FileOutputStream(file);
int bytesRead;
byte[] buffer = new byte[4096];
while((bytesRead = inputStream.read(buffer)) != -1){
fileOutputStream.write( buffer, 0, bytesRead);
}
fileOutputStream.close();
inputStream.close();
}catch(Exception e){
e.printStackTrace();
}
}
}).start();
}
There is no error in executing but the file is not downloaded. Please suggest.
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
}
call
connection.setDoInput(true);
connection.connect();
before
InputStream inputStream = connection.getInputStream();

Not Able to download .apk on Android handset from our site

When i start downloading .apk on mobile handset(Google Nexus) from our site,following thing happens:
1.I get redirection link which is in the code
2.Start downloading the application but after download gets complete ,i get error download not completed(failed)
3. I get error page, saying page is not available,where as i an able to access net
here is the format of link to down load:/game.do?x=&y=&z=
Earlier i was able to download applications with same code.
.
If you have any idea about the problem please let me know.
Thanks
Rakesh
.apk size varies from 500KB to 5MB
Use below Code for download apk file from server
private void download(){
try {
URL url = new URL("url from apk file is to be downloaded");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard, "filename.ext");
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
fileOutput.write(buffer, 0, bufferLength);
}
fileOutput.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
And Refer below link for download and install apk file from url.
Download & Install APK File

Android Download Zip From Api And Store in SD CARD

I am working on an API which returns me a zip file containing multiple XML files, which i have to parse individually after extracting the zip file.
Here is the link for that(will download the zip-file) :
http://clinicaltrials.gov/ct2/results?term=&recr=&rslt=&type=&cond=&intr=&outc=&lead=&spons=&id=&state1=&cntry1=&state2=&cntry2=&state3=&cntry3=&locn=&gndr=Female&age=0&rcv_s=&rcv_e=&lup_s=&lup_e=studyxml=true
Here is my current code to save the zip-file in sdcard:
File root = Environment.getExternalStorageDirectory();
String url= "http://clinicaltrials.gov/ct2/results?term=&recr=&rslt=&type=&cond=&intr=&outc=&lead=&spons=&id=&state1=&cntry1=&state2=&cntry2=&state3=&cntry3=&locn=&gndr=Female&age=0&rcv_s=&rcv_e=&lup_s=&lup_e=xml=true";
try {
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.setDoInput(true);
conn.setConnectTimeout(10000); // timeout 10 secs
conn.connect();
InputStream input = conn.getInputStream();
FileOutputStream fOut = new FileOutputStream(new File(root, "new.zip"));
int byteCount = 0;
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = input.read(buffer)) != -1) {
fOut.write(buffer, 0, bytesRead);
byteCount += bytesRead;
}
fOut.flush();
fOut.close();
} catch (Exception e) {
e.printStackTrace();
}
Problem :
New.zip File is getting created in sdcard but it seems nothing is downloading also the file size is 0kb.
Is my code proper or I have to use something else to handel zipfiles.
Edit Solved :
I am extremely sorry the api link is invalid ... it should be
http://clinicaltrials.gov/ct2/results?term=&recr=&rslt=&type=&cond=&intr=&outc=&lead=&spons=&id=&state1=&cntry1=&state2=&cntry2=&state3=&cntry3=&locn=&gndr=Female&age=0&rcv_s=&rcv_e=&lup_s=&lup_e=&studyxml=true
& is required before studtxml..
Thnx every 1 for quick response ..
There is something wrong either in your .zip file URL or in .zip file size(0 byte size) because if we download this .zip file (From URL given by you) from web browser then also its downloaded with 0 byte size.
Downloaded .zip file URL.
Your Url in the code String url=... is not giving me a zip file.
http://clinicaltrials.gov/ct2/results?term=&recr=&rslt=&type=&cond=&intr=&outc=&lead=&spons=&id=&state1=&cntry1=&state2=&cntry2=&state3=&cntry3=&locn=&gndr=Female&age=0&rcv_s=&rcv_e=&lup_s=&lup_e=xml=true
The link you provided is different
http://clinicaltrials.gov/ct2/results?term=&recr=&rslt=&type=&cond=&intr=&outc=&lead=&spons=&id=&state1=&cntry1=&state2=&cntry2=&state3=&cntry3=&locn=&gndr=Female&age=0&rcv_s=&rcv_e=&lup_s=&lup_e=studyxml=true
Looks like there's an error: lup_e=xml=true should be lup_e=studyxml=true

Categories

Resources