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
}
}
}
I am downloading a pdf file from my server.Recently I encountered that
when my internet was disconnected while the download was in progress I
couldn't open the pdf file because it was incomplete.How can I delete
a file programmatically if the download was incomplete and a file with
that extension was saved in the process? This is the code I am
currently using to download the pdf from a server.
class DownloadFileAsync extends AsyncTask<String, String, String>
{
final NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this);
final int notify_id = 1;
final NotificationManager NM = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
private String resp;
#Override
protected String doInBackground(String... params) {
int count;
builder.setSmallIcon(R.mipmap.ic_launcher);
builder.setContentTitle("Download Status...");
builder.setContentText("Download in Progress...");
try {
URL url = new URL(params[0]);
URLConnection connection = url.openConnection();
connection.connect();
int lengthOfFile = connection.getContentLength();
Log.d("ANDRO_ASYNC", "LENGTH OF FILE : " + lengthOfFile);
String fileName = params[0].substring(params[0].lastIndexOf('/') + 1, params[0].length());
Log.d("FILENAME", fileName);
resp = fileName;
if (isSDPresent) {
InputStream inputStream = new BufferedInputStream(url.openStream());
OutputStream outputStream = new FileOutputStream("sdcard/shatayushi/" + fileName);
byte data[] = new byte[1024];
long total = 0;
while ((count = inputStream.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lengthOfFile));
outputStream.write(data, 0, count);
}
outputStream.flush();
outputStream.close();
inputStream.close();
} else {
InputStream inputStream = new BufferedInputStream(url.openStream());
OutputStream outputStream = new FileOutputStream(getFilesDir() + "/shatayushi/" + fileName);
byte data[] = new byte[1024];
long total = 0;
while ((count = inputStream.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lengthOfFile));
outputStream.write(data, 0, count);
}
outputStream.flush();
outputStream.close();
inputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return params[0];
}
#Override
protected void onPostExecute(String filename) {
Log.d("PARAM", filename);
String fname = filename.substring(filename.lastIndexOf('/')+1, filename.length());
int position = Arrays.asList(pdf_url).indexOf(filename);
Log.d("Position",String.valueOf(position));
String magazine_id = magazine_names[position];
if (isSDPresent) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
builder.setProgress(0, 0, false);
builder.setContentText("Download Complete...");
NM.notify(notify_id, builder.build());
TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String device_imei = telephonyManager.getDeviceId();
update_info(device_imei,magazine_id);
Uri uri = Uri.parse("/storage/emulated/0/shatayushi/" + fname);
Intent intent = new Intent(MainActivity.this, MuPDFActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(Intent.ACTION_VIEW);
intent.setData(uri);
startActivity(intent);
} else {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
builder.setProgress(0, 0, false);
builder.setContentText("Download Complete...");
NM.notify(notify_id, builder.build());
Uri uri = Uri.parse(getFilesDir() + "/shatayushi/" + fname);
Intent intent = new Intent(MainActivity.this, MuPDFActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(Intent.ACTION_VIEW);
intent.setData(uri);
startActivity(intent);
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected void onProgressUpdate(String... values) {
Log.d("ANDRO_ASYNC", values[0]);
progressDialog.setProgress(Integer.parseInt(values[0]));
builder.setProgress(100, Integer.parseInt(values[0]), false);
NM.notify(notify_id, builder.build());
}
}
Any help or suggestion is appreciated.Thank you.
You can just get a pointer to the file and use "delete()" method
String fileName = "my_file"; //your file name
File parentFile; //get your parent file
File myFile = new File(parentFile, fileName);
myFile.delete();
You can handle the network I/O exceptions first instead of catching "Exception".
// Exception thrown when network timeout occurs
catch (InterruptedIOException iioe)
{
System.err.println ("Remote host timed out during read operation");
}
// Exception thrown when general network I/O error occurs
catch (IOException ioe)
{
System.err.println ("Network I/O exception- " + ioe);
}
then
catch(Exception e) {System.err.println ("Exception - " + ioe);
}
When you get the network type of error, you can then check that whether the file has been created/exists and then you can delete it using the following code,
File fdelete = new File(uri.getPath());
if (fdelete.exists()) {
if (fdelete.delete()) {
System.out.println("file Deleted :" + uri.getPath());
} else {
System.out.println("file not Deleted :" + uri.getPath());
}
}
Hope that this helps.
Based on Roee answer that I completed a bit up, here should be a working example :
class DownloadFileAsync extends AsyncTask<String, String, String> {
final NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this);
final int notify_id = 1;
final NotificationManager NM = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
private String resp;
#Override
protected String doInBackground(String... params) {
int count;
String stringToReturnToPostExecute = null;
builder.setSmallIcon(R.mipmap.ic_launcher);
builder.setContentTitle("Download Status...");
builder.setContentText("Download in Progress...");
try {
URL url = new URL(params[0]);
URLConnection connection = url.openConnection();
connection.connect();
int lengthOfFile = connection.getContentLength();
Log.d("ANDRO_ASYNC", "LENGTH OF FILE : " + lengthOfFile);
String fileName = params[0].substring(params[0].lastIndexOf('/') + 1, params[0].length());
Log.d("FILENAME", fileName);
resp = fileName;
if (isSDPresent) {
InputStream inputStream = new BufferedInputStream(url.openStream());
OutputStream outputStream = new FileOutputStream("sdcard/shatayushi/" + fileName);
byte data[] = new byte[1024];
long total = 0;
while ((count = inputStream.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lengthOfFile));
outputStream.write(data, 0, count);
}
outputStream.flush();
outputStream.close();
inputStream.close();
} else {
InputStream inputStream = new BufferedInputStream(url.openStream());
OutputStream outputStream = new FileOutputStream(getFilesDir() + "/shatayushi/" + fileName);
byte data[] = new byte[1024];
long total = 0;
while ((count = inputStream.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lengthOfFile));
outputStream.write(data, 0, count);
}
outputStream.flush();
outputStream.close();
inputStream.close();
stringToReturnToPostExecute = params[0];
}
} catch (Exception e) {
e.printStackTrace();
}
return stringToReturnToPostExecute ;
}
#Override
protected void onPostExecute(String filename) {
Log.d("PARAM", filename);
if(filename == null) {
//TODO delete your file here and dismissthe Dialog as well
}
String fname = filename.substring(filename.lastIndexOf('/')+1, filename.length());
int position = Arrays.asList(pdf_url).indexOf(filename);
Log.d("Position",String.valueOf(position));
String magazine_id = magazine_names[position];
if (isSDPresent) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
builder.setProgress(0, 0, false);
builder.setContentText("Download Complete...");
NM.notify(notify_id, builder.build());
TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String device_imei = telephonyManager.getDeviceId();
update_info(device_imei,magazine_id);
Uri uri = Uri.parse("/storage/emulated/0/shatayushi/" + fname);
Intent intent = new Intent(MainActivity.this, MuPDFActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(Intent.ACTION_VIEW);
intent.setData(uri);
startActivity(intent);
} else {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
builder.setProgress(0, 0, false);
builder.setContentText("Download Complete...");
NM.notify(notify_id, builder.build());
Uri uri = Uri.parse(getFilesDir() + "/shatayushi/" + fname);
Intent intent = new Intent(MainActivity.this, MuPDFActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(Intent.ACTION_VIEW);
intent.setData(uri);
startActivity(intent);
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected void onProgressUpdate(String... values) {
Log.d("ANDRO_ASYNC", values[0]);
progressDialog.setProgress(Integer.parseInt(values[0]));
builder.setProgress(100, Integer.parseInt(values[0]), false);
NM.notify(notify_id, builder.build());
} }
class DownloadFileAsync extends AsyncTask<String, String, String>
{
final NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this);
final int notify_id = 1;
final NotificationManager NM = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
private String resp;
int lengthOfFile;
#Override
protected String doInBackground(String... params) {
int count;
builder.setSmallIcon(R.mipmap.ic_launcher);
builder.setContentTitle("Download Status...");
builder.setContentText("Download in Progress...");
try {
URL url = new URL(params[0]);
URLConnection connection = url.openConnection();
connection.connect();
lengthOfFile = connection.getContentLength();
Log.d("ANDRO_ASYNC", "LENGTH OF FILE : " + lengthOfFile);
String fileName = params[0].substring(params[0].lastIndexOf('/') + 1, params[0].length());
Log.d("FILENAME", fileName);
resp = fileName;
if (isSDPresent) {
InputStream inputStream = new BufferedInputStream(url.openStream());
OutputStream outputStream = new FileOutputStream("sdcard/shatayushi/" + fileName);
byte data[] = new byte[1024];
long total = 0;
while ((count = inputStream.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lengthOfFile));
outputStream.write(data, 0, count);
}
outputStream.flush();
outputStream.close();
inputStream.close();
} else {
InputStream inputStream = new BufferedInputStream(url.openStream());
OutputStream outputStream = new FileOutputStream(getFilesDir() + "/shatayushi/" + fileName);
byte data[] = new byte[1024];
long total = 0;
while ((count = inputStream.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lengthOfFile));
outputStream.write(data, 0, count);
}
outputStream.flush();
outputStream.close();
inputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return params[0];
}
#Override
protected void onPostExecute(String filename) {
Log.d("PARAM", filename);
String fname = filename.substring(filename.lastIndexOf('/')+1, filename.length());
Log.d("LENGTH OF FILE : ",String.valueOf(lengthOfFile));
int position = Arrays.asList(pdf_url).indexOf(filename);
Log.d("Position",String.valueOf(position));
String magazine_id = magazine_names[position];
if (isSDPresent) {
File f = new File("/storage/emulated/0/shatayushi/" +fname);
if (f.length()<lengthOfFile)
{
if (f.delete())
{
progressDialog.setProgress(0);
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
builder.setProgress(0, 0, false);
builder.setContentText("Download was interrupted please try again!");
NM.notify(notify_id, builder.build());
Toast.makeText(MainActivity.this, "Download was interrupted please try again!", Toast.LENGTH_SHORT).show();
Log.d("Del","File deleted");
}else
{
Toast.makeText(MainActivity.this, "File not deleted", Toast.LENGTH_SHORT).show();
Log.d("NOTDel","File not deleted");
}
}else {
progressDialog.setProgress(0);
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
builder.setProgress(0, 0, false);
builder.setContentText("Download Complete...");
NM.notify(notify_id, builder.build());
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String device_imei = telephonyManager.getDeviceId();
// update_info(device_imei,magazine_id);
dbHandler.updateDownloadStatus(magazine_id, "YES");
Uri uri = Uri.parse("/storage/emulated/0/shatayushi/" + fname);
Intent intent = new Intent(MainActivity.this, MuPDFActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(Intent.ACTION_VIEW);
intent.setData(uri);
startActivity(intent);
}
} else {
File f = new File("/storage/emulated/0/shatayushi/" +fname);
if (f.length()<lengthOfFile)
{
if (f.delete())
{
progressDialog.setProgress(0);
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
builder.setProgress(0, 0, false);
builder.setContentText("Download was interrupted please try again!");
NM.notify(notify_id, builder.build());
Toast.makeText(MainActivity.this, "Download was interrupted please try again!", Toast.LENGTH_SHORT).show();
Log.d("Del","File deleted");
}else
{
Toast.makeText(MainActivity.this, "File not deleted", Toast.LENGTH_SHORT).show();
Log.d("NOTDel","File not deleted");
}
}else
{
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
builder.setProgress(0, 0, false);
builder.setContentText("Download Complete...");
NM.notify(notify_id, builder.build());
Uri uri = Uri.parse(getFilesDir() + "/shatayushi/" + fname);
Intent intent = new Intent(MainActivity.this, MuPDFActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(Intent.ACTION_VIEW);
intent.setData(uri);
startActivity(intent);
}
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected void onProgressUpdate(String... values) {
Log.d("ANDRO_ASYNC", values[0]);
progressDialog.setProgress(Integer.parseInt(values[0]));
builder.setProgress(100, Integer.parseInt(values[0]), false);
NM.notify(notify_id, builder.build());
}
}
I finally figured it out Sorry #Rotwang and thank you #user3793589.
As the title says I am trying to get help simplifing my code. I have multiple buttons, now only three while I test this out but I plan on having approximately thirty button choices. Currently I have a very long section of code and I think it can be shortened drastically maybe using an array? But I'm not sure how to implement it correctly. IF anyone has done this before or has an idea please share! Thanks to everyone!
public class myDL extends Activity {
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private Button startBtn;
private ProgressDialog mProgressDialog;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.filechoice);
mProgressDialog = new ProgressDialog(myDL.this);
mProgressDialog.setMessage("The file is now downloading, it will be saved on the SD card for future use. Please use WiFi to avoid operator charges.");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
Button section = (Button) findViewById(R.id.section);
section.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// TODO Auto-generated method stub
Intent section = new Intent(view.getContext(),
section.class);
startActivity(section);
}
});
Button back = (Button) findViewById(R.id.back);
back.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
setResult(RESULT_OK);
finish();
}
});
secOne = (Button) findViewById(R.id.secOne);
secOne.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startSecOne();
}
});
}
private void startSecOne() {
StartSecOne secOne = new StartSecOne();
secOne
.execute("www.website.com/document.pdf");
}
class StartSecOne extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog.show();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
mProgressDialog.setProgress(progress[0]);
}
#Override
protected String doInBackground(String... aurl) {
String isFileThere = Environment.getExternalStorageDirectory()
+ "/Android/Data/"
+ getApplicationContext().getPackageName()
+ "/files/test1.pdf";
File f = new File(isFileThere);
if (f.exists()) {
showPdf();
} else {
try {
URL url = new URL(aurl[0]);
URLConnection connection = url.openConnection();
connection.connect();
int fileLength = connection.getContentLength();
int tickSize = 2 * fileLength / 100;
int nextProgress = tickSize;
Log.d(
"ANDRO_ASYNC", "Lenght of file: " + fileLength);
InputStream input = new BufferedInputStream(
url.openStream());
String path = Environment.getExternalStorageDirectory()
+ "/Android/Data/"
+ getApplicationContext().getPackageName()
+ "/files";
File file = new File(path);
file.mkdirs();
File outputFile = new File(file, "test1.pdf");
OutputStream output = new FileOutputStream(outputFile);
byte data[] = new byte[1024 * 1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
if (total >= nextProgress) {
nextProgress = (int) ((total / tickSize + 1) * tickSize);
this.publishProgress((int) (total * 100 / fileLength));
}
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
mProgressDialog.dismiss();
showPdf();
} catch (Exception e) {
}
}
return null;
}
}
secTwo = (Button) findViewById(R.id.secTwo);
secTwo.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startSecTwo ();
}
});
}
private void startSecTwo () {
StartSecTwo secTwo = new StartSecTwo ();
secTwo
.execute("www.website.com/document2.pdf");
}
class StartSecTwo extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog.show();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
mProgressDialog.setProgress(progress[0]);
}
#Override
protected String doInBackground(String... aurl) {
String isFileThere = Environment.getExternalStorageDirectory()
+ "/Android/Data/"
+ getApplicationContext().getPackageName()
+ "/files/test2.pdf";
File f = new File(isFileThere);
if (f.exists()) {
showPdf();
} else {
try {
URL url = new URL(aurl[0]);
URLConnection connection = url.openConnection();
connection.connect();
int fileLength = connection.getContentLength();
int tickSize = 2 * fileLength / 100;
int nextProgress = tickSize;
Log.d(
"ANDRO_ASYNC", "Lenght of file: " + fileLength);
InputStream input = new BufferedInputStream(
url.openStream());
String path = Environment.getExternalStorageDirectory()
+ "/Android/Data/"
+ getApplicationContext().getPackageName()
+ "/files";
File file = new File(path);
file.mkdirs();
File outputFile = new File(file, "test2.pdf");
OutputStream output = new FileOutputStream(outputFile);
byte data[] = new byte[1024 * 1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
if (total >= nextProgress) {
nextProgress = (int) ((total / tickSize + 1) * tickSize);
this.publishProgress((int) (total * 100 / fileLength));
}
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
mProgressDialog.dismiss();
showPdf();
} catch (Exception e) {
}
}
return null;
}
}
secThree = (Button) findViewById(R.id.secThree);
secThree.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startSecThree ();
}
});
}
private void startSecThree () {
StartSecThree secThree = new StartSecThree ();
secThree
.execute("www.website.com/document3.pdf");
}
class StartSecThree extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog.show();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
mProgressDialog.setProgress(progress[0]);
}
#Override
protected String doInBackground(String... aurl) {
String isFileThere = Environment.getExternalStorageDirectory()
+ "/Android/Data/"
+ getApplicationContext().getPackageName()
+ "/files/test3.pdf";
File f = new File(isFileThere);
if (f.exists()) {
showPdf();
} else {
try {
URL url = new URL(aurl[0]);
URLConnection connection = url.openConnection();
connection.connect();
int fileLength = connection.getContentLength();
int tickSize = 2 * fileLength / 100;
int nextProgress = tickSize;
Log.d(
"ANDRO_ASYNC", "Lenght of file: " + fileLength);
InputStream input = new BufferedInputStream(
url.openStream());
String path = Environment.getExternalStorageDirectory()
+ "/Android/Data/"
+ getApplicationContext().getPackageName()
+ "/files";
File file = new File(path);
file.mkdirs();
File outputFile = new File(file, "test3.pdf");
OutputStream output = new FileOutputStream(outputFile);
byte data[] = new byte[1024 * 1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
if (total >= nextProgress) {
nextProgress = (int) ((total / tickSize + 1) * tickSize);
this.publishProgress((int) (total * 100 / fileLength));
}
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
mProgressDialog.dismiss();
showPdf();
} catch (Exception e) {
}
}
return null;
}
}
private void showPdf() {
// TODO Auto-generated method stub
mProgressDialog.dismiss();
File file = new File(Environment.getExternalStorageDirectory()
+ "/Android/Data/"
+ getApplicationContext().getPackageName()
+ "/files/test1.pdf");
PackageManager packageManager = getPackageManager();
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType("application/pdf");
List list = packageManager.queryIntentActivities(testIntent,
PackageManager.MATCH_DEFAULT_ONLY);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
intent.setDataAndType(uri, "application/pdf");
startActivity(intent);
}
}
final OnClickLisener listener = new OnClickListener() {
public void onClick(View v){
switch(v.getId()){
case R.id.zero:
break;
case R.id.one:
break;
case R.id.two:
break;
}
}
}
final int[] btnIds = new int[]{R.id.one, R.id.two, R.id.zero};
for(int i = 0; i < btnIds.length; i++) {
final Button btn = (Button)findViewById(btnIds[i]);
btn.setOnClickListener(listener);
}
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);
}