Can't download file in Android phone - Android..? - 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)

Related

How to save file in internal storage in device

I am going with the download of files from the browser and stored in the internal storage of my device and the path appears as like /data/data/com.example/files/downloads/sample.pdf
but on next day i get the file path as empty ""
using below code to save the file from browser:
private String downloadfile(Uri uri) {
int count;
String fileName = "";
try {
// Output stream to write file
String root = null;
// if (Environment.isExternalStorageRemovable())
// else
root = getFilesDir().toString()+ "/download/";
File file = new File(root);
if (!file.exists())
file.mkdirs();
fileName = file.getAbsolutePath();
file = new File("" + uri);
fileName = fileName + "/" + file.getName();
URL url = new URL(uri.toString());
URLConnection conection = url.openConnection();
conection.setRequestProperty("Content-Type",
"application/octet-stream");
conection.setRequestProperty("Expect", "100-continue");
conection.setRequestProperty("Content-Disposition", "attachment");
conection.setRequestProperty("filename", file.getName());
conection.connect();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
OutputStream output = new FileOutputStream(fileName);
file = new File(fileName);
file.createNewFile();
byte data[] = new byte[1024];
while ((count = input.read(data)) != -1) {
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
String inputs = "EX";
Parameter.trackApplication(inputs, e.getMessage());
e.printStackTrace();
}
return fileName;
}
How can i solve this problem,please correct me where i am going wrong and help me out to fix this issue.

How to download file in Android over HTTPs

I am downloading a file in android which goes via plain HTTP. Now i want this connection to go over HTTPs and then download file, can someone help me in code what changes will i need to do that.
I changed
URLConnection ucon = url.openConnection();
to
//HttpsURLConnection ucon = (HttpsURLConnection) url.openConnection();
but that didn't work.
Code:
private void DownloadFile() {
try {
File root = android.os.Environment
.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath() + "/File");
if (dir.exists() == false) {
dir.mkdirs();
}
URL url = new URL(DownloadFile); // you can write here any link
File file = new File(dir, fileName);
long startTime = System.currentTimeMillis();
Log.d(LOG_TAG, "download begining");
Log.d(LOG_TAG, "download url:" + url);
Log.d(LOG_TAG, "downloaded file name:" + fileName);
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
//HttpsURLConnection ucon = (HttpsURLConnection) 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(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();
Log.d(LOG_TAG,
"download ready in"
+ ((System.currentTimeMillis() - startTime) / 1000)
+ " sec");
} catch (IOException e) {
Log.d(LOG_TAG, "Error: " + e);
}
}
Try this:
URL url = new URL("some 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();
//set the path where we want to save the file
//in this case, going to save it on the root directory of the
//sd card.
File SDCardRoot = new File("/sdcard/"+"Some Folder Name/");
//create a new file, specifying the path, and the filename
//which we want to save the file as.
File file = new File(SDCardRoot,"some file name");
//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();
//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);
//add up the size so we know how much is downloaded
downloadedSize += bufferLength;
int progress=(int)(downloadedSize*100/totalSize);
//this is where you would do something to report the prgress, like this maybe
//updateProgress(downloadedSize, totalSize);
}
//close the output stream when done
fileOutput.close();

Downloading the different formated images from url and storing it on sdcard

I am trying to download the images from url and storing it on sd card, it works fine for .jpg file but if image extension are .png or .jpeg then it is giving error , i want to download the diferent format images at the same time ..below is code which i have typed..
public void DownloadFromUrl(String DownloadUrl, String fileName) {
try {
File dir = new File("/sdcard/pluto");
if (dir.exists() == false) {
dir.mkdirs();
}
URL url = new URL(DownloadUrl); // you can write here any link
File file = new File(dir, fileName);
long startTime = System.currentTimeMillis();
Log.d("DownloadManager", "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(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();
Log.d("DownloadManager",
"download ready in"
+ ((System.currentTimeMillis() - startTime) / 1000)
+ " sec");
} catch (IOException e) {
Log.d("DownloadManager", "Error: " + e);
}
}
please help me..
Try this may be helpful .
same post with different image format.
Image download code works for all image format, issues with PNG format rendering

Download youtube on Android

After reading this: Code for download video from Youtube on Java, Android
I found a way the obtain the youtube download link which is similar to this:
http://o-o---preferred---lax02s10---v9---lscache4.c.youtube.com/videoplayback?upn=7XKwMrZklvQ&sparams=cp%2Cid%2Cip%2Cipbits%2Citag%2Cratebypass%2Csource%2Cupn%2Cexpire&fexp=903903%
I tried to download the video using
public void DownloadFromUrl(String DownloadUrl, String fileName) {
Log.i("DownloadFromUrl","DownloadFromUrl"+DownloadUrl);
try {
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File (root.getAbsolutePath() + "/youlike");
if(dir.exists()==false) {
dir.mkdirs();
}
URL url = new URL(DownloadUrl); //you can write here any link
File file = new File(dir, fileName);
long startTime = System.currentTimeMillis();
Log.d("DownloadManager", "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();
Log.i("URLConnection","URLConnection Succeed");
/*
* Define InputStreams to read from the URLConnection.
*/
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
Log.i("BufferedInputStream","BufferedInputStream Succeed");
/*
* 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);
Log.i("ByteArrayBuffer","ByteArrayBuffer Succeed");
}
/* Convert the Bytes read to a String. */
FileOutputStream fos = new FileOutputStream(file);
Log.i("FileOutputStream","FileOutputStream initialized");
fos.write(baf.toByteArray());
Log.i("fos.write(baf.toByteArray());","fos.write(baf.toByteArray()); initialized");
fos.flush();
fos.close();
Log.d("DownloadManager", "download ready in" + ((System.currentTimeMillis() - startTime) / 1000) + " sec");
} catch (IOException e) {
Log.d("DownloadManager", "Error: " + e);
}
}
But it returns an error message to me: java.io.FileNotFoundException
I tested the url and I am sure that it works. Can anyone tell me what the problem is?
Will it be that you should encode you youtube download link before open the http connection
Could it be that you did not set write permission on external storgae? File mkdirs() method not working in android/java

Can someone help me put this download code that I use in ASyncTask?

It works just fine when I run it in a thread, but I want to use Asynctask and when I execute my version of it, nothing happens:
try {
//set the download URL, a url that points to a file on the internet
//this is the file to be downloaded
URL url = new URL(filename2);
//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();
//set the path where we want to save the file
//in this case, going to save it on the root directory of the
//sd card.
SDCardRoot = Environment.getExternalStorageDirectory() + "/download/";
//create a new file, specifying the path, and the filename
//which we want to save the file as.
File file = new File(SDCardRoot,filename3);
//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();
//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);
//add up the size so we know how much is downloaded
downloadedSize += bufferLength;
//this is where you would do something to report the prgress, like this maybe
//updateProgress(downloadedSize, totalSize);
//publishProgress((int)(total*100/lenghtOfFile));
}
//close the output stream when done
fileOutput.close();
//catch some possible errors...
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
THIS IS MY ATTEMPT AS REQUESTED:
private class DownloadFile extends AsyncTask<Void, Integer, Long> {
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(Long result) {
Intent in = new Intent(mainmenu.this, DownloadService.class);
stopService(in);
}
#Override
protected Long doInBackground(Void... params) {
try {
//set the download URL, a url that points to a file on the internet
//this is the file to be downloaded
URL url = new URL(filename2);
//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();
//set the path where we want to save the file
//in this case, going to save it on the root directory of the
//sd card.
SDCardRoot = Environment.getExternalStorageDirectory() + "/download/";
//create a new file, specifying the path, and the filename
//which we want to save the file as.
File file = new File(SDCardRoot,filename3);
//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();
//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);
//add up the size so we know how much is downloaded
downloadedSize += bufferLength;
//this is where you would do something to report the prgress, like this maybe
//updateProgress(downloadedSize, totalSize);
//publishProgress((int)(total*100/lenghtOfFile));
}
//close the output stream when done
fileOutput.close();
//catch some possible errors...
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
here you go
public class WebRequest extends AsyncTask<URL, Void, String> {
ProgressDialog dialog;
Context _context;
String _title;
String _message;
public WebRequest(Context context,
String ProgressTitle, String ProgressMessage) {
this._context = context;
this._title = ProgressTitle;
this._message = ProgressMessage;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
dialog = new ProgressDialog(_context);
dialog.setTitle(_title);
dialog.setMessage(_message);
dialog.show();
}
#Override
protected String doInBackground(URL... params) {
// TODO Auto-generated method stub
try {
//set the download URL, a url that points to a file on the internet
//this is the file to be downloaded
URL url = params[0];
//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();
//set the path where we want to save the file
//in this case, going to save it on the root directory of the
//sd card.
SDCardRoot = Environment.getExternalStorageDirectory() + "/download/";
//create a new file, specifying the path, and the filename
//which we want to save the file as.
File file = new File(SDCardRoot,filename3);
//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();
//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);
//add up the size so we know how much is downloaded
downloadedSize += bufferLength;
//this is where you would do something to report the prgress, like this maybe
//updateProgress(downloadedSize, totalSize);
//publishProgress((int)(total*100/lenghtOfFile));
}
//close the output stream when done
fileOutput.close();
return "Success";
//catch some possible errors...
} catch (MalformedURLException e) {
e.printStackTrace();
return "Failed";
} catch (IOException e) {
e.printStackTrace();
return "Failed";
}
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
if (dialog.isShowing())
dialog.cancel();
Toast.makeText(_context,result,Toast.LENGTH_LONG);
}
}
//using this
WebRequest request = new WebRequest(context,"Downloading","Please wait..");
request.Execute(object of URL);

Categories

Resources