I am saving image from url to sdcard. But image size is 0 in sdcard. Image is created in sdcard but now retrieve data from url and save. so it is giving me 0 size.
try
{
URL url = new URL("http://api.androidhive.info/images/sample.jpg");
InputStream input = url.openStream();
try {
//The sdcard directory e.g. '/sdcard' can be used directly, or
//more safely abstracted with getExternalStorageDirectory()
File storagePath = Environment.getExternalStorageDirectory();
OutputStream output = new FileOutputStream (new File(storagePath,username+".png"));
try {
byte[] buffer = new byte[2048];
int bytesRead = 0;
while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
output.write(buffer, 0, bytesRead);
}
} finally {
output.close();
}
} finally {
input.close();
}
} catch(Exception e)
{
System.out.println("error in sd card "+e.toString());
}
Try this code.It works...
You should have permission of internet and write external storage.
try
{
URL url = new URL("Enter the URL to be downloaded");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
File SDCardRoot = Environment.getExternalStorageDirectory().getAbsoluteFile();
String filename="downloadedFile.png";
Log.i("Local filename:",""+filename);
File file = new File(SDCardRoot,filename);
if(file.createNewFile())
{
file.createNewFile();
}
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
int totalSize = urlConnection.getContentLength();
int downloadedSize = 0;
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer)) > 0 )
{
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
Log.i("Progress:","downloadedSize:"+downloadedSize+"totalSize:"+ totalSize) ;
}
fileOutput.close();
if(downloadedSize==totalSize) filepath=file.getPath();
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
filepath=null;
e.printStackTrace();
}
Log.i("filepath:"," "+filepath) ;
return filepath;
Try this, this may late but it will help someone.
private class ImageDownloadAndSave extends AsyncTask<String, Void, Bitmap>
{
#Override
protected Bitmap doInBackground(String... arg0)
{
downloadImagesToSdCard("","");
return null;
}
private void downloadImagesToSdCard(String downloadUrl,String imageName)
{
try
{
URL url = new URL(img_URL);
/* making a directory in sdcard */
String sdCard=Environment.getExternalStorageDirectory().toString();
File myDir = new File(sdCard,"test.jpg");
/* if specified not exist create new */
if(!myDir.exists())
{
myDir.mkdir();
Log.v("", "inside mkdir");
}
/* checks the file and if it already exist delete */
String fname = imageName;
File file = new File (myDir, fname);
if (file.exists ())
file.delete ();
/* Open a connection */
URLConnection ucon = url.openConnection();
InputStream inputStream = null;
HttpURLConnection httpConn = (HttpURLConnection)ucon;
httpConn.setRequestMethod("GET");
httpConn.connect();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK)
{
inputStream = httpConn.getInputStream();
}
FileOutputStream fos = new FileOutputStream(file);
int totalSize = httpConn.getContentLength();
int downloadedSize = 0;
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer)) >0 )
{
fos.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
Log.i("Progress:","downloadedSize:"+downloadedSize+"totalSize:"+ totalSize) ;
}
fos.close();
Log.d("test", "Image Saved in sdcard..");
}
catch(IOException io)
{
io.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Declare your network operations in AsyncTask as it will load it as a background task. Don't load network operation on main thread. After this either in button click or in content view call this class like
new ImageDownloadAndSave().execute("");
And don't forget to add the nework permission as:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
Hope this will help :-)
Related
i'm trying to download an mp3 file from an URL and save ut on the sd card in an music folder.
But no matter what I do it wont save it on the SD , it just downloads it and after while trying to find it it's no wher et obe found.
Here is my code in the async task class:
protected String doInBackground(String... params) {
try{
URL url = new URL(params[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.connect();
File sd = Environment.getExternalStorageDirectory();
File file = new File(sd, "TestSongs.mp3");
FileOutputStream outputStream = new FileOutputStream(file);
InputStream inputStream = connection.getInputStream();
int totalsize = connection.getContentLength();
int downloadSize = 0;
byte[] buffer = new byte[1024];
int bufferLength = 0;
while((bufferLength = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0 , bufferLength);
downloadSize += bufferLength;
publishProgress("" + (int) ((downloadSize * 100) / totalsize));
}
outputStream.close();
}catch(Exception e) {
Log.d(TAG, e.getMessage());
}
return null;
}
Add
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
somewhere inside the your manifest, outside the <application></application> tag
I am trying to download file form Internet. I have given all permission.But my apps gives some Exception. Here is my source code ..........
private void write()
{
try {
URL url = new URL("http://wordpress.org/plugins/about/readme.txt");
// URL url = new URL("http://androidsaveitem.appspot.com/downloadjpg");
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
// c.setReadTimeout(10000); // millis
// c.setConnectTimeout(15000); // millis
c.setDoOutput(true);
c.connect();
String PATH = Environment.getExternalStorageDirectory()
+ "/download/";
File file = new File(PATH);
file.mkdirs();
String fileName = "Sap.txt";
File outputFile = new File(file, fileName);
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();
// }
} catch (IOException e) {
MessageBox(e.getMessage());
}
}
//permission
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
c.connect(); // this connect() function gives an exception. I can't identify the problem.
Please somebody help me....
add this in main function
new AsyncTaskRunner().execute("");
add below after main function
private class AsyncTaskRunner extends AsyncTask<String, String, String>
{
#Override
protected void onPostExecute(String result) {
try
{
MessageBox(result);
/*
String PATH = Environment.getExternalStorageDirectory()
+ "/download/";
File file = new File(PATH);
file.mkdirs();
String fileName = "Sap.txt";
File outputFile = new File(file, fileName);
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c;
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
*/
}
catch(Exception ex)
{
MessageBox(ex.getMessage()+"error ");
}
}
#Override
protected String doInBackground(String... params) {
try
{
URL url = new URL("http://wordpress.org/plugins/about/readme.txt");
// URL url = new
// URL("http://androidsaveitem.appspot.com/downloadjpg");
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
// c.setReadTimeout(10000); // millis
// c.setConnectTimeout(15000); // millis
//c.setDoOutput(true);
c.connect();
InputStream is = c.getInputStream();
String PATH = Environment.getExternalStorageDirectory()
+ "/download/";
File file = new File(PATH);
file.mkdirs();
String fileName = "Sap.txt";
File outputFile = new File(file, fileName);
FileOutputStream fos = new FileOutputStream(outputFile);
//InputStream is = c;
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
Log.v("esty", "Successfully");
return "Successfully";
}
catch(Exception ex)
{
Log.v("esty", ex.getMessage());
return "failed"+ex.getMessage();
}
}
i hope it solves your problem! :)
i have An Error while download PDF file From Server and save it on SD
i have permission To Access internet and external storage ..
It`s working fine on android 2.3.6
But on Tab 4.1.1 its create the file with 0 byte
URL url = new URL("https://docs.google.com/"+direct);
//create the new connection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//set up some things on the connection
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("Connection", "Keep-Alive");
urlConnection.setRequestProperty("Content-Type", "application/xml");
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(Environment.getExternalStorageDirectory().getAbsoluteFile()+"/folder/");
//create a new file, specifying the path, and the filename
//which we want to save the file as.
File file = new File(SDCardRoot,book.getBook_name()+".pdf");
//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
totalSize = urlConnection.getContentLength();
//variable to store total downloaded bytes
//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
publishProgress((downloadedSize*100)/totalSize);
}
//close the output stream when done
fileOutput.close();
//catch some possible errors...
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Try this:
private String getExternalSDPath() {
File file = new File("/system/etc/vold.fstab");
FileReader fr = null;
BufferedReader br = null;
try {
fr = new FileReader(file);
} catch (FileNotFoundException e) {
// handle
}
String path = null;
try {
if (fr != null) {
br = new BufferedReader(fr);
String s = br.readLine();
while (s != null) {
if (s.startsWith("dev_mount")) {
String[] tokens = s.split("\\s");
path = tokens[2]; // mount_point
if (Environment.getExternalStorageDirectory()
.getAbsolutePath().equals(path)) {
break;
}
}
s = br.readLine();
}
}
} catch (IOException e) {
// handle
} finally {
try {
if (fr != null) {
fr.close();
}
if (br != null) {
br.close();
}
} catch (IOException e) {
// handle
}
}
return path;
}
The code is made specifically for Samsung Devices with both internal, an internal that acts as external, and SD.
I needed to access the SD and came up with the above code, so you can try it and possibly modify it to work on all devices.
Edit: My download AsyncTask
private class DownloadFile extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
String filename = "somefile.pdf";
HttpURLConnection c;
try {
URL url = new URL("http://someurl.com/" + filename);
c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
} catch (IOException e1) {
return e1.getMessage();
}
File myFilesDir = new File(Environment
.getExternalStorageDirectory().getAbsolutePath()
+ "/Download");
File file= new File(myFilesDir, filename);
if (file.exists()) {
file.delete();
}
if ((myFilesDir.mkdirs() || myFilesDir.isDirectory())) {
try {
InputStream is = c.getInputStream();
FileOutputStream fos = new FileOutputStream(myFilesDir
+ "/" + filename);
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
} catch (Exception e) {
return e.getMessage();
}
} else {
return "Unable to create folder";
}
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG)
.show();
super.onPostExecute(result);
}
}
I have the set of images from server.I need to store the image in device.How to do that.Can anyone guide me to store the images in android device.What is the best way to do this process.
Thanks in Advance:)
You can download image from url and store it in sd card. Whenever you want to display images then simply load that image. Here simple code for this work.
private void downloadImagesToSdCard(String downloadUrl,String imageName)
{
try{
URL url = new URL(downloadUrl); //you can write here any link
File myDir = new File("/sdcard"+"/"+Constants.imageFolder);
//Something like ("/sdcard/file.mp3")
if(!myDir.exists()){
myDir.mkdir();
Log.v("", "inside mkdir");
}
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = imageName;
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
InputStream inputStream = null;
HttpURLConnection httpConn = (HttpURLConnection)ucon;
httpConn.setRequestMethod("GET");
httpConn.connect();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputStream = httpConn.getInputStream();
}
/*
* Define InputStreams to read from the URLConnection.
*/
// InputStream is = ucon.getInputStream();
/*
* Read bytes to the Buffer until there is nothing more to read(-1).
*/
FileOutputStream fos = new FileOutputStream(file);
int size = 1024*1024;
byte[] buf = new byte[size];
int byteRead;
while (((byteRead = inputStream.read(buf)) != -1)) {
fos.write(buf, 0, byteRead);
bytesDownloaded += byteRead;
}
/* Convert the Bytes read to a String. */
fos.close();
}catch(IOException io)
{
networkException = true;
continueRestore = false;
}
catch(Exception e)
{
continueRestore = false;
e.printStackTrace();
}
}
Hope this will help you.
In my app, I have requirement to download mp3 files from url. I am downloading file using Async Task. For testing purpose, I have kept file in dropbox. The problem is, it is not downloading complete file. The actual file size is of 5 MB. But, it is downloading only 29 KB of data. When I checked the length of content, it showed -1. I am not getting where is the problem. Below, I am posting my code.
#Override
protected Void doInBackground(String... sUrl)
{
InputStream input = null;
OutputStream output = null;
try
{
URL link = new URL(sUrl[0]);
HttpURLConnection urlConnection = (HttpURLConnection)link.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
int fileLength = urlConnection.getContentLength();
Log.v("Download file length", ""+fileLength);
input = urlConnection.getInputStream();
int downloadedSize = 0;
output = new FileOutputStream(Environment.getExternalStorageDirectory()
.getAbsolutePath()+"/audiofolder/1.mp3.mp3");
byte[] data = new byte[1024];
int bufferLength = 0;
while (((bufferLength = input.read(data)) > 0))
{
output.write(data, 0, bufferLength);
downloadedSize += bufferLength;
publishProgress((int)((downloadedSize/fileLength) * 100));
}//while
output.flush();
output.close();
input.close();
}//try
catch (MalformedURLException e)
{
e.printStackTrace();
}//catch
catch (IOException e)
{
e.printStackTrace();
}//catch
return null;
}//diInBackground
in My Application the Below Code Works Perfectly. you can try this Out.
#Override
protected Void doInBackground(String... aurl) {
try {
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
File file = new File("mnt/sdcard/");
file.mkdirs();
File outputfile = new File(file, title + ".mp3");
FileOutputStream fileOutput = new FileOutputStream(outputfile);
InputStream inputStream = conexion.getInputStream();
int totalSize = conexion.getContentLength();
int downloadedSize = 0;
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ((bufferLength = inputStream.read(buffer)) != -1) {
downloadedSize += bufferLength;
onProgressUpdate((int) ((downloadedSize * 100) / totalSize));
fileOutput.write(buffer, 0, bufferLength);
}
fileOutput.close();
} catch (Exception e) {
download = true;
e.printStackTrace();
}
return null;
}
Check your link.
When you see length of content = -1, it mean there is no length of content in header of link. It don't force under your download progress.
You only download 29KB because it download website, .html not file mp3.
Yout can copy and paste your link on brower to check.
From Android Documentation:
https://developer.android.com/reference/java/net/URLConnection.html#getContentLength()
getContentLength returns:
the content length of the resource that this connection's URL references, -1 if the content length is not known, or if the content length is greater than Integer.MAX_VALUE.