Downloading a PDF file - android

In my application, the user needs to download PDF file from an url and store it on sdcard.
But the catch here is I can only use DefaultHttpClient to access the url.
I found couple of solutions but none used DefaultHttpClient.
After downloading the PDF, I would also likie to view the PDF in my application.

//use this method to download the pdf file
public void downloadPdfContent(String urlToDownload){
try {
String fileName="xyz";
String fileExtension=".pdf";
// download pdf file.
URL url = new URL(urlToDownload);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
String PATH = Environment.getExternalStorageDirectory() + "/mydownload/";
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, fileName+fileExtension);
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
System.out.println("--pdf downloaded--ok--"+urlToDownload);
} catch (Exception e) {
e.printStackTrace();
}
}
// for viewing the pdf use this method
private void onPdfClick()
{
// String pdfFile = Environment.getExternalStorageDirectory()+ File.separator + AstroManager.file.getName();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File("/sdcard/mydownload/xyz.pdf"), "application/*");
startActivity(intent);
}

If you have to open pdf file, pdf reader must have to be installed in your device.Otherwise it will show blank screen.
Also here is good example to download pdf from server and view its contents.

see http://developer.android.com/reference/org/apache/http/client/methods/HttpGet.html for retreiving data from a url with a DefaultHttpClient

Related

video download from google+/picasa android

We have a requirement to download video from google+/picasa and store it into sdcard.
Can you please any one help me to solve this issue?
google+/picasa
Converting from URI to byte[], then byte[] is stored to file:
InputStream videoStream = getActivity().getContentResolver().openInputStream(videoUri);
byte bytes[] = ByteStreams.toByteArray(videoStream );
videoFile = new File("abcd.mp4");
FileOutputStream out = new FileOutputStream(videoFile);
out.write(bytes);
out.close();
Can you try that one :
public String DownloadFromUrl(String DownloadUrl, String fileName) {
File SDCardRoot = null;
try {
SDCardRoot = Environment.getExternalStorageDirectory();
File files = new File(SDCardRoot+fileName);
int sizeoffile;
if(!files.exists())
{
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File (root.getAbsolutePath());
if(dir.exists()==false) {
dir.mkdirs();
}
URL url = new URL(DownloadUrl);
File file = new File(dir, fileName);
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
sizeoffile = ucon.getContentLength();
Log.d("SIZEOFFILE: ", sizeoffile+" BYTE");
/*
* Define InputStreams to read from the URLConnection.
*/
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
/*
* Read bytes to the Buffer until there is nothing more to read(-1).
*/
ByteArrayBuffer baf = new ByteArrayBuffer(5000);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
/* Convert the Bytes read to a String. */
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.flush();
fos.close();
}
}
catch (IOException e) {
e.getMessage();
}
return SDCardRoot+fileName; }
Finally i found the solution.
Uri videoUri = data.getData();
File videoFile = null;
final InputStream imageStream;
try {
imageStream = getActivity().getContentResolver().openInputStream(videoUri);
byte bytes[] = ByteStreams.toByteArray(imageStream);//IStoByteArray(imageStream);
videoFile = new File(Environment.getExternalStorageDirectory()+ "/"+System.currentTimeMillis()+".mp4");
videoFile.createNewFile();
FileOutputStream out = new FileOutputStream(videoFile);
out.write(bytes);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch (Exception ee){
ee.printStackTrace();
}
I have recently encountered this.
I first discovered that what I'm receiving is a picture rather than a video.
But I didn't understand why Facebook is successfully playing the online video I shared via (Google+'s) Photo.
I then occasionally discovered that the file they're currently giving is a GIF with the original extension in the MediaStore.Images.Media.DISPLAY_NAME section of the contentUri.
Eeek!

How to download and automatic install apk from url in android

I'm trying to programmatically download an .apk file from a given URL and then install it, but I am getting a FileNotFoundException. What could be a possible reason for the issue?
try {
URL url = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
String PATH = "/mnt/sdcard/Download/";
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, "VersionUpdate.apk");
if(outputFile.exists()){
outputFile.delete();
}
FileOutputStream fos = new FileOutputStream(outputFile);
**//Getting error in this line**
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.flush();
fos.close();
is.close();
} catch (Exception e) {
Log.e("UpdateAPP", "Update error! " + e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(String unused) {
//dismiss the dialog after the file was downloaded
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(Uri.parse("file:///sdcard/download/VersionUpdate.apk"),"application/vnd.android.package-archive");
startActivity(intent);
}
You just replaced by InputStream is = c.getInputStream(); to given code.
InputStream is ;
int status = c.getResponseCode();
if (status != HttpURLConnection.HTTP_OK)
is = c.getErrorStream();
else
is = c.getInputStream();
Try the following code
File outputFile = new File(file, "VersionUpdate.apk");
if(!outputFile.exists())
{
outputFile.createNewFile();
}
What you are doing is deleting the file, when it already exist, then FileOutputStream will not get file where you want to download the apk .
If the file already exist, FileOutputStream will override the content with new update.
If you have queries, do ask!!

How to delete the .apk after installation

I am using the following program to download and install an apk. How can I remove the apk from the sdcard after successful installation? What I tried is:
File file = new File("/sdcard/filename.apk");
boolean deleted = file.delete();
But it will delete the file before installation.
protected Boolean doInBackground(String... arg0) {
try {
URL url = new URL( weburl +"username="+usename+"&password="+usepass +"&apk="+apk);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard, "filename.apk");
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();
// this.checkUnknownSourceEnability();
// this.initiateInstallation();
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(new File("/sdcard/filename.apk"));
intent.setDataAndType(uri, "application/vnd.android.package-archive");
startActivity(intent);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private void installApk(){
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(new File("/sdcard/filename.apk"));
intent.setDataAndType(uri, "application/vnd.android.package-archive");
startActivity(intent);
}
You can register a broadcast receiver that will notify you when installation will complete and at that time you can fire your code for delete apk.
please see this question
How to find out when an installation is completed

Android: downloaded file size less than its actual size

I want to update my application automatically
This is the code i am using
public void Update(String apkurl){
try {
URL url = new URL(apkurl);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
String PATH = Environment.getExternalStorageDirectory() + "/download/";
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, "DeliverReceipt.apk");
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();//till here, it works fine - .apk is download to my sdcard in download file
/*Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/apk/" + "DeliverReceipt.apk")), "application/vnd.android.package-archive");
startActivity(intent); //installation is not working
*/
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Update error!", Toast.LENGTH_LONG).show();
}
}
The downloaded file is just 20kb size, which is less than the original
how can i solve this problem?
thank you
*noted : if i try this url in browser it's work, an apk can be downloaded
You should probably flush before you close the file, using fos.flush()

Can't download file in Android phone - Android..?

I having problem with file download,
I am able to download file in emulator but It is not working with the phone.
I have defined the permission for the Internet and write SD card.
I having one doc file on server, and if user click on download. It downloads the file. This works fine in emulator but not working in phone.
Edit
My code for download file
public void downloadFile(String _url, String fileName) {
File PATH = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
try {
PATH.mkdirs();
URL url = new URL(_url); // you can write here any link
File file = new File(PATH, fileName);
long startTime = System.currentTimeMillis();
Log.d("Manager", "download begining");
Log.d("DownloadManager", "download url:" + url);
Log.d("DownloadManager", "downloaded file name:" + fileName);
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
/*
* Define InputStreams to read from the URLConnection.
*/
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
/*
* Read bytes to the Buffer until there is nothing more to read(-1).
*/
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
/* Convert the Bytes read to a String. */
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.close();
Log.d("ImageManager",
"download ready in"
+ ((System.currentTimeMillis() - startTime) / 1000)
+ " sec");
} catch (IOException e) {
Log.d("ImageManager", "Error: " + e);
}
}
try the snippets given bellow...
File PATH = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
try {
//set the download URL, a url that points to a file on the internet
//this is the file to be downloaded
_url = _url.replace(" ", "%20");
URL url = new URL(_url);
//create the new connection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//set up some things on the connection
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
//and connect!
urlConnection.connect();
//create a new file, specifying the path, and the filename
//which we want to save the file as.
File file = new File(PATH,fileName);
//this will be used to write the downloaded data into the file we created
FileOutputStream fileOutput = new FileOutputStream(file);
//this will be used in reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
//this is the total size of the file
int totalSize = urlConnection.getContentLength();
Log.i("Download", totalSize+"");
//variable to store total downloaded bytes
// int downloadedSize = 0;
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0; //used to store a temporary size of the buffer
//now, read through the input buffer and write the contents to the file
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
//add the data in the buffer to the file in the file output stream (the file on the sd card
fileOutput.write(buffer, 0, bufferLength);
}
//close the output stream when done
fileOutput.close();
return true;
//catch some possible errors...
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
make sure you have enters the correct download path(url)

Categories

Resources