im building an android App that download books in pdf format from url and storage it into the device , so i wrote this code to make folder named " Mypdf " and save the file after it download in it , but when i run the app in the device i only found Mypdf file but there is no any pdf book , below the code i used
class DownloadFileAsync extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected String doInBackground(String... aurl) {
int count;
try {
File file = new File(Environment.getExternalStorageDirectory()+"/Mypdf");
file.mkdir();
URL url = new URL(aurl[0]);
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("Mypdf/ "+booknameText+ ".pdf");
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();
} 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);
Toast.makeText(getApplicationContext(), "The Book You downloaded had been saved into your SD Card " , Toast.LENGTH_LONG).show();
}
}
}
i used this function :
OutputStream output = new FileOutputStream("/sdcard/ "+booknameText+ ".pdf");
but some times many device's do'not have sdcard so the file will not be saved , so please can you help guys
Related
Below is my AsyncTask to download a PDF file from CloudBoost database. The code works and downloads the file; however, what does not work is the progress bar update because the file length returned is -1. Can someone give me a tip on how I can deal with this.
By the way loading.setProgress(progress[0]); line in the the progress update method is being initialized at the top of the class that this AsyncTask class is nested in.
class DownloadPdfFromInternet extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
int count;
try {
URL url = new URL(strings[0]);
URLConnection connection = url.openConnection();
connection.connect();
// get length of file
int lengthOfFile = connection.getContentLength();
Log.d("dozer74", "LengthOf File: " + lengthOfFile);
InputStream input = new BufferedInputStream(url.openStream(), 10 * 1024);
OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory().getPath() + "/" + pubName);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int) (total * 100 / lengthOfFile));
// write data to file
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
protected void onProgressUpdate(Integer... progress) {
loading.setProgress(progress[0]);
}
#Override
protected void onPostExecute(String url) {
loading.dismiss();
openPdfFile();
}
}
I am trying to download a file from an online source of mine. The issue I am having is that the browser window keeps appearing as it load into the download server. Is there some way that I may be able to hide this? I already have this code below in the doInBackground portion of an AsyncTask, but cant seem to get it to hide the browser bar. Here is my code at this point:
private class getErDone extends AsyncTask<Void, Void, Void>{
#Override
protected void onPreExecute() {
ProgressDialog progressDialog = new ProgressDialog(getApplicationContext());
progressDialog.setTitle("Downloading Software");
progressDialog.setMessage("Now Updating, DO NOT TURN OFF DEVICE");
progressDialog.setCancelable(false);
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
try{
Intent goToMarket = new Intent(Intent.ACTION_VIEW)
.setData(Uri.parse("http://mydownloadlink.com/myfile?dl=1"));
//**Note** As convincing as it seems, this is not the real download link
startActivity(goToMarket);
}catch (UnknownError e){
e.printStackTrace();
}
/*catch (MalformedURLException e){
e.printStackTrace();
}catch (IOException t){
t.printStackTrace();
}*/
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
}
Thanks everyone!
here is sample from my code, download without browser:
private TextView mFileDownloadProgressBarPercent;
private ProgressBar mFileDownloadProgressBar;
private Runnable mFileExecutionTaskAfterDownload;
public String fileDownloadedResultPath;
and asynctask:
class DownloadFileFromURL extends AsyncTask<String, String, String> {
// Before starting background thread
// Show Progress Bar Dialog
#Override
protected void onPreExecute() {
super.onPreExecute();
if(mFileDownloadProgressBar != null)
mFileDownloadProgressBar.setVisibility(View.VISIBLE);
if(mFileDownloadProgressBarPercent != null)
mFileDownloadProgressBarPercent.setVisibility(View.VISIBLE);
}
// Downloading file in background thread
#Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
String extStorageDirectory = Environment.getExternalStorageDirectory()
.toString();
File folder = new File(extStorageDirectory, "pdf"); // for example we are downloading pdf's so store in pdf dir.
folder.mkdir();
File subFolder = new File(extStorageDirectory+"/pdf", "fileId"); // here you can place files by id of category etc..
subFolder.mkdir();
String fileName = url.toString().substring(url.toString().lastIndexOf("/")+1);
fileDownloadedResultPath = subFolder + "/" + fileName;
// Output stream to write file
OutputStream output = new FileOutputStream(subFolder + "/" + fileName);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress(""+(int)((total*100)/lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
protected void onProgressUpdate(String... progress) {
if(mFileDownloadProgressBar != null)
mFileDownloadProgressBar.setProgress(Integer.parseInt(progress[0]));
if(mFileDownloadProgressBarPercent != null)
mFileDownloadProgressBarPercent.setText(mContext.getString(R.string.downloading_file) + " " + String.format("%s%%",Integer.parseInt(progress[0])+""));
}
#Override
protected void onPostExecute(String file_url) {
if(mFileDownloadProgressBar != null)
mFileDownloadProgressBar.setVisibility(View.GONE);
if(mFileDownloadProgressBarPercent != null)
mFileDownloadProgressBarPercent.setVisibility(View.GONE);
if(mFileExecutionTaskAfterDownload != null)
mFileExecutionTaskAfterDownload.run();
}
}
I have an android app which downloads a video by clicking a button and saves it on user's device. when users click on the button the app checks if the video is in users' device, and if it is not it downloads the video and if it has been downloaded the app just plays the video without the need to download.
However when the download crashes the file is there , but the app can't plays it and gets tricked that the file has been downloaded already.
I wanted to ask if there are any ways to check if the download process has crashed or the file is corrupted.
Thanks
You can use AsyncTask as below to check if the download was interupted or not.
Below code is just for example purpose
class DownloadFileFromURL extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
initialText.setText(getString(R.string.connecting));
}
#Override
protected String doInBackground(String... f_url) {
int count;
try {
String fileURL = f_url[0];
if (fileURL.contains(" ")) {
fileURL = fileURL.replace(" ", "%20");
}
URL url = new URL(fileURL);
filename = f_url[0].substring(fileURL.lastIndexOf("/") + 1);
URLConnection connection = url.openConnection();
connection.connect();
// getting file length
int lengthOfFile = connection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
File file = new File(FilePath);
if (!file.exists()) {
if (!file.isDirectory()) {
file.mkdirs();
}
}
// Output stream to write file
OutputStream output = new FileOutputStream(FilePath + filename);
byte data[] = new byte[1024];
long total = 0;
runOnUiThread(new Runnable() {
#Override
public void run() {
setSubTitle(getString(R.string.downloading));
initialText.setText(ad_tv_initialText.getText().toString() + getString(R.string.connected));
}
});
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress("" + (int) ((total * 100) / lengthOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
return "SUCCESS";
} catch (Exception e) {
return "FAILED";
}
}
protected void onProgressUpdate(String... progress) {
progress.setProgress(Integer.parseInt(progress[0]));
progressText.setText(progress[0] + " %");
}
#Override
protected void onPostExecute(String result) {
if (result.equals("SUCCESS")) {
takeDecisionToPlay();
} else if (result.equals("FAILED")) {
setSubTitle(getString(R.string.failed_));
finalText.setText(getString(R.string.failed));
}
}
}
I have used the following class for downloading a file and saving it to the sdcard.
class DownloadFileAsync extends AsyncTask<String, String, String> {
#SuppressWarnings("deprecation")
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected String doInBackground(String... aurl) {
int count;
try {
URL url = new URL(aurl[0]);
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(Environment.getExternalStorageDirectory().getAbsolutePath()+"PurchasedFrames/"+filename);
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();
} 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) {
File file = new File("/sdcard/PurchasedFrames/", filename );
Bitmap myBitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
ImageView frame = (ImageView) findViewById(R.id.frame);
frame.setImageBitmap(myBitmap);
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
Dialog method
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;
}
}
My problem using the above codes, progressBar will appear but it will disappear without finishing and no download occur. I could't notice any logcat error or any other error from debugging. Can anybody tell what can be happen or how to overcome from this problem?
So my assumption was correct. In my application I used a static method for returning a file path that calls mkdirs() in case that such path doesn't exist.
For your code such method would look so:
public static File getSaveFilePath(String fileName) {
File dir = new File(Environment.getExternalStorageDirectory(), "PurchasedFrames");
dir.mkdirs();
File file = new File(dir, fileName);
return file;
}
Then replace the line with output stream:
OutputStream output = new FileOutputStream(getSaveFilePath(fileName));
Also replace your exception block with catch (Exception e) { Log.e("DownloadFileAsync", e.toString()); "}
I would rather my application save the required text file in the internal storage for the app than the users /sdcard/ so there isn't files being created which may annoy them at some point. Could someone direct me on how to change my code so the text file is saved internally rather than externally.
public void updatebutton(View v){
startDownload();
}
private void startDownload() {
String url = "http://nowactivity.webs.com/teststring.txt";
Toast.makeText(this, "Updating", Toast.LENGTH_LONG);
new DownloadFile().execute(url);
}
class DownloadFile extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... aurl) {
int count;
try {
URL url = new URL(aurl[0]);
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("/sdcard/textfile.txt");
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();
} catch (Exception e) {}
return null;
}
I think what you want is Context.openFileOutput(). (Activity extends Context, so you could call this from within an Activity, for instance.)
Incidentally, you should use Environment.getExternalStorageDirectory() instead of something like "/sdcard"