I want to download and save pdf file to internal storage. Here is code that i am using:
I am calling my method from other class:
new Thread(new Runnable() {
public void run() {
new Main().downloadPdfContent("http://people.opera.com/howcome/2005/ala/sample.pdf");
}
}).start();
Method look like this:
public void downloadPdfContent(String urlToDownload){
URLConnection urlConnection = null;
try{
URL url = new URL(urlToDownload);
//Opening connection of currrent url
urlConnection = url.openConnection();
urlConnection.connect();
//int lenghtOfFile = urlConnection.getContentLength();
String PATH = Environment.getExternalStorageDirectory() + "/1/";
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, "test.pdf");
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = url.openStream();
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) {
// TODO: handle exception
e.printStackTrace();
}
}
I found link of pdf on the web:
http://people.opera.com/howcome/2005/ala/sample.pdf
However i get an exception on this line:
urlConnection.connect();
Exception:
java.net.UnknownHostException: people.opera.com
I can't figure out what's wrong. Maybe someone could take a look.
Thanks.
Put
<uses-permission android:name="android.permission.INTERNET"/>
in your AndroidManifest.xml
Follow following steps :
1) Declare file name
String fileName;
//for image
fileName = "matchfine1.png";
//for pdf
fileName = "samplepdf.pdf";
2) Call method to invoke download process.
startDownload(fileName);
3) Define startDownload method:
//for download file start
private void startDownload(String filename) {
String filedowname = filename;
//for image
String url = "http://farm1.static.flickr.com/114/298125983_0e4bf66782_b.jpg";
//for pdf
String url = "http://people.opera.com/howcome/2005/ala/sample.pdf";
new DownloadFileAsync().execute(url,filedowname);
}
4) For auto loading progressBar:
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Downloading file..");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
5) Define the download process extending AsyncTask
class DownloadFileAsync extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected String doInBackground(final String... aurl) {
try {
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File (root.getAbsolutePath() + "/Your_file_save_path/");
if(dir.exists()==false) {
dir.mkdirs();
}
URL url = new URL(aurl[0]);
String filename = aurl[1];
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(dir+"/"+filename);
byte data[] = new byte[1024];
long total = 0;
int count;
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]));
}
#Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
//for download file end
6) Replace "Your_file_save_path" by your file path in dir. and then download and check in the specified location.
I have used the same code and got Network.onThreadException Error. But then after using this piece of code in my oncreate() method, I was able to resolve the issue.
if (android.os.Build.VERSION.SDK_INT > 9)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
Related
I wrote a program that
Download the photo from the url...
But I have a problem...
Some photos are downloaded.
And there is no problem.
But some of the pictures are not downloadable incompletely :(
and in the file manager I look at
it is broken
Can you help?
my code is:
public class DownloadFileFromURL_img extends AsyncTask {
private viewHolderPost holderPOST;
public DownloadFileFromURL_img(viewHolderPost holderPOST) {
Log.d(TAG, "DownloadFileFromURL_img: ");
this.holderPOST = holderPOST;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
/**
* Downloading file in background thread
*/
#Override
protected String doInBackground(String... f_url) {
int count;
try {
File file = new File(Environment.getExternalStorageDirectory(), "98Diha/img");
if (!file.exists()) {
if (!file.mkdirs()) {
file.createNewFile();
}
}
InputStream input = null;
int response = -1;
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
if (!(conection instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try{
HttpURLConnection httpConn = (HttpURLConnection) conection;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
input = httpConn.getInputStream();
}
}
catch (Exception ex)
{
throw new IOException("Error connecting");
}
int lenghtOfFile = conection.getContentLength();
input = new BufferedInputStream(url.openStream());
String imgS[] = f_url[0].split("/");
String name = imgS[imgS.length - 1];
String path = Environment
.getExternalStorageDirectory().toString()
+ "/98diha/img/" + name;
File filePath = new File(path);
if (!filePath.exists()) {
OutputStream output = new FileOutputStream(path);
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();
} else {
SSToast(context, "Exist!");
holderPOST.dowload_img.setVisibility(View.GONE);
holderPOST.setWallpaper.setVisibility(View.VISIBLE);
holderPOST.setWallpaper.setText(context.getString(R.string.set_wp));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
holderPOST.setWallpaper.setTextColor(ContextCompat.getColor(context, R.color.Teal_400));
} else {
holderPOST.setWallpaper.setTextColor(context.getResources().getColor(R.color.Teal_400));
}
}
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
/**
* Updating progress bar
*/
protected void onProgressUpdate(String... progress) {
holderPOST.dowload_img.setVisibility(View.GONE);
holderPOST.setWallpaper.setVisibility(View.VISIBLE);
holderPOST.setWallpaper.setText(context.getString(R.string.dowloading));
}
/**
* After completing background task Dismiss the progress dialog
**/
#Override
protected void onPostExecute(String file_url) {
holderPOST.setWallpaper.setText(context.getString(R.string.set_wp));
holderPOST.setWallpaper.setTextColor(context.getResources().getColor(R.color.Teal_400));
Log.d(TAG, "onPostExecute: ");
}
}
Instead of using AsyncTask to download images from URL. You can use libraries such as Glide or Picasso to do it quickly just in one line. But if you don't want to use libraries than you could use DownloadManager to download it and save it in a file. You can check this tutorial or other tutorials on the web for the implementation of DownloadManager.
I want to download zip file from server by using ksoap liabry.I am getting data in base64 please give solution that how to convert base64 and save it as zip file
byte[] bytes;
byte[] data = result.getBytes("UTF-8");
File outputFile = new File(mediaStorageDir.getAbsolutePath(), + "filename.zip");
new FileOutputStream(outputFile);
bytes = Base64.decode(data, Base64.DEFAULT);
File filepath = new File(Environment.getExternalStorageDirectory(), "Folder/" + "filename.zip");
OutputStream pdffos = new FileOutputStream(filepath);
pdffos.write(bytes);
pdffos.flush();
pdffos.close();
This Code help me to downlad apk and store to sd card.
This may help you also..
public class SaveInBackground extends AsyncTask<String,Integer,String> {
View v;
OutputValue ov;
Boolean isError= false;
public SaveInBackground(View v,OutputValue ov){
this.v = v;
this.ov = ov;
}
#Override
protected void onPreExecute(){
Message.setText("Downloading...");
isToLoop =true;
new Thread(new Runnable() {
#Override
public void run() {
while (isToLoop) {
SystemClock.sleep(500);
runOnUiThread(new Runnable() {
#Override
public void run() {
int count = bar.getProgress() + 1;
bar.setProgress(count);
}
});
if(isToLoop)
break;
}
}
}).start();
}
#Override
protected void onProgressUpdate(Integer... values) {
bar.setProgress(values[0]);
}
#Override
protected String doInBackground(String... params) {InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(Globle.Infosoft_serverLink.replace("/Service.asmx/","")+ov.url);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
isError = true;
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
int fileLength = connection.getContentLength();
input = connection.getInputStream();
//publishProgress(80);
String path = Environment.getExternalStorageDirectory()+"/"+ov.Name+".apk";
output = new FileOutputStream(path );
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
if (fileLength > 0) // only if total length is known
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
return path;
}
catch (Exception e) {
isError =true;
Snackbar.make(v,"Error while accessing storage.",Snackbar.LENGTH_LONG).show();
return null;
}finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
}
#Override
protected void onPostExecute(String result){
if(!isError) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(result)), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
Message.setText("Downloaded");
reset(v);
}
}
Please help me to add update code to my app to be update from my server thank you
nothing worked from net , i need complete guide
You can't install your app without users permission and root access but you can download your applications new version from server then ask users for install. Here is an example:
{
PackageManager manager = context.getPackageManager();
try {
PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
version = info.versionName;
if (newversion.replace(".", "") < version.replace(".", "")) {
new DownloadFileFromURL().execute("http://exampl.com/Content/files/example.apk");
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
}
private class DownloadFileFromURL extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = onCreateDialog();
}
#Override
protected String doInBackground(String... f_url) {
int count;
try {
File file = new File(Environment.getExternalStorageDirectory() + "/example.apk");
if (file.exists()) {
file.delete();
}
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
int lenghtOfFile = conection.getContentLength();
pDialog.setMax(lenghtOfFile / 1024);
InputStream input = new BufferedInputStream(url.openStream(), 8192);
OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory() + "/example.apk");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress(total / 1024 + "");
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception ignored) {
}
return null;
}
protected void onProgressUpdate(String... progress) {
pDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String file_url) {
dialog.dismiss();
File file = new File(Environment.getExternalStorageDirectory() + "/example.apk");
if (file.exists()) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
} else {
//finish() or whatever you want
}
}
}
While Downloading pdf from link m getting error and its directly going to the catch and exception has been caught there therefore i have implemented permission into the manifest file . still m getting exception at file download time .
here is my code
TextView tv_loading;
String dest_file_path = "test.pdf";
int downloadedSize = 0, totalsize;
String download_file_url = "http://ilabs.uw.edu/sites/default/files/sample_0.pdf";
float per = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tv_loading = new TextView(this);
setContentView(tv_loading);
tv_loading.setGravity(Gravity.CENTER);
tv_loading.setTypeface(null, Typeface.BOLD);
downloadAndOpenPDF();
}
void downloadAndOpenPDF() {
new Thread(new Runnable() {
public void run() {
Uri path = Uri.fromFile(downloadFile(download_file_url));
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(path, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
} catch (ActivityNotFoundException e) {
tv_loading
.setError("PDF Reader application is not installed in your device");
}
}
}).start();
}
File downloadFile(String dwnload_file_path) {
File file = null;
try {
URL url = new URL(dwnload_file_path);
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
// connect
urlConnection.connect();
// set the path where we want to save the file
File SDCardRoot = Environment.getExternalStorageDirectory();
// create a new file, to save the downloaded file
file = new File(SDCardRoot, dest_file_path);
FileOutputStream fileOutput = new FileOutputStream(file);
// Stream used for reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
// this is the total size of the file which we are
// downloading
totalsize = urlConnection.getContentLength();
setText("Starting PDF download...");
// create a buffer...
byte[] buffer = new byte[1024 * 1024];
int bufferLength = 0;
while ((bufferLength = inputStream.read(buffer)) > 0) {
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
per = ((float) downloadedSize / totalsize) * 100;
setText("Total PDF File size : "
+ (totalsize / 1024)
+ " KB\n\nDownloading PDF " + (int) per
+ "% complete");
}
// close the output stream when complete //
fileOutput.close();
setText("Download Complete. Open PDF Application installed in the device.");
} catch (final MalformedURLException e) {
setTextError("Some error occured. Press back and try again.",
Color.RED);
} catch (final IOException e) {
setTextError("Some error occured. Press back and try again.",
Color.RED);
} catch (final Exception e) {
setTextError(
"Failed to download image. Please check your internet connection.",
Color.RED);
}
return file;
}
void setTextError(final String message, final int color) {
runOnUiThread(new Runnable() {
public void run() {
tv_loading.setTextColor(color);
tv_loading.setText(message);
}
});
}
void setText(final String txt) {
runOnUiThread(new Runnable() {
public void run() {
tv_loading.setText(txt);
}
});
}
thanks For help in Advance
I want to download files from Zippyshare site in Android.
The problem is that content length returned is -1. So I am not able to download a valid file.
Here is my code
public class DownloadFileDemo1 extends Activity {
ProgressBar pb;
Dialog dialog;
int downloadedSize = 0;
int totalSize = 0;
TextView cur_val;
String dwnload_file_path = "http://www17.zippyshare.com/i/95748527/55444/image.jpeg";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
showProgress(dwnload_file_path);
new Thread(new Runnable() {
public void run() {
downloadFile();
}
}).start();
}
void downloadFile(){
try {
URL url = new URL(dwnload_file_path);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("Accept-Encoding", "gzip");
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
//connect
urlConnection.connect();
//set the path where we want to save the file
File SDCardRoot = Environment.getExternalStorageDirectory();
//create a new file, to save the downloaded file
File file = new File(SDCardRoot,"downloaded_file.png");
FileOutputStream fileOutput = new FileOutputStream(file);
//Stream used for reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
System.out.println("ENCODING"+urlConnection.getContentEncoding());
if ("gzip".equals(urlConnection.getContentEncoding())) {
inputStream = new GZIPInputStream(inputStream);
}
InputSource is = new InputSource(inputStream);
//this is the total size of the file which we are downloading
totalSize = urlConnection.getContentLength();
runOnUiThread(new Runnable() {
public void run() {
pb.setMax(totalSize);
}
});
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
// update the progressbar //
runOnUiThread(new Runnable() {
public void run() {
pb.setProgress(downloadedSize);
float per = ((float)downloadedSize/totalSize) * 100;
cur_val.setText("Downloaded " + downloadedSize + "KB / " + totalSize + "KB (" + (int)per + "%)" );
}
});
}
//close the output stream when complete //
fileOutput.close();
runOnUiThread(new Runnable() {
public void run() {
// pb.dismiss(); // if you want close it..
}
});
} catch (final MalformedURLException e) {
showError("Error : MalformedURLException " + e);
e.printStackTrace();
} catch (final IOException e) {
showError("Error : IOException " + e);
e.printStackTrace();
}
catch (final Exception e) {
showError("Error : Please check your internet connection " + e);
}
}
void showError(final String err){
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(DownloadFileDemo1.this, err, Toast.LENGTH_LONG).show();
}
});
}
void showProgress(String file_path){
dialog = new Dialog(DownloadFileDemo1.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.myprogressdialog);
dialog.setTitle("Download Progress");
TextView text = (TextView) dialog.findViewById(R.id.tv1);
text.setText("Downloading file from ... " + file_path);
cur_val = (TextView) dialog.findViewById(R.id.cur_pg_tv);
cur_val.setText("Starting download...");
dialog.show();
pb = (ProgressBar)dialog.findViewById(R.id.progress_bar);
pb.setProgress(0);
pb.setProgressDrawable(getResources().getDrawable(R.drawable.green_progress));
}
}
How can I solve this problem?
According to documentation of getContentLength:
Returns the content length in bytes specified by the response header
field content-length or -1 if this field is not set or cannot be
represented as an int.
If you will check your link here, then you will spot, that Content Length was not set.
(I will just add, that I was not checking fully your code, but generally in main downloading loop with buffer - is downloading something, but I was not checking if it was correct, or not)
EDIT: I'm gonna 'hate' guy, that gave me '-1'. I'm helping with detail link and how checking it, why content length is returning -1, and someone is giving me negative. I change little downloadFile function just to download file, without giving update to UI, and then we have:
void downloadFile(){
try {
URL url = new URL(dwnload_file_path);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("Accept-Encoding", "gzip");
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
//connect
urlConnection.connect();
//set the path where we want to save the file
//create a new file, to save the downloaded file
File file = new File("downloaded_file.png");
FileOutputStream fileOutput = new FileOutputStream(file);
//Stream used for reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
System.out.println("ENCODING"+urlConnection.getContentEncoding());
if ("gzip".equals(urlConnection.getContentEncoding())) {
inputStream = new GZIPInputStream(inputStream);
}
InputSource is = new InputSource(inputStream);
//this is the total size of the file which we are downloading
totalSize = urlConnection.getContentLength();
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
// update the progressbar //
}
//close the output stream when complete //
fileOutput.close();
} catch (final MalformedURLException e) {
e.printStackTrace();
} catch (final IOException e) {
e.printStackTrace();
}
catch (final Exception e) {
e.printStackTrace();
}
}
As I checked this code is downloading file, but it isn't this image, but html page from zippyshare, as zippy has kind of protection to download files from their site.