Android: Complete file not downloaded from url - android

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.

Related

Download MP3 file from server in sd card in Android

I want to download all mp3 files from server one by one and save into sd card folder. I have no any errors or exception but mp3 does not downloaded and does not show in SD card. Can someone help how to solve this issue.Here is my code.
if (imageName.endsWith(mp3_Pattern))
{
str_DownLoadUrl = namespace + "/DownloadFile/FileName/" + imageName;
Log.e("######### ", "str_DownLoadUrl = " + str_DownLoadUrl);
download_Mp3File(str_DownLoadUrl);
strDownLoadStatus = "1";
dbhelper.update_DownLoadStatus(imageName, strDownLoadStatus);
}
void download_Mp3File(final String fileUrl) {
new AsyncTask<String, Integer, String>()
{
#Override
protected String doInBackground(String... arg0)
{
int count;
File file = new File(newFolder, System.currentTimeMillis() + imageName);
try
{
URL url = new URL(fileUrl);
URLConnection conexion = url.openConnection();
conexion.connect();
// this will be useful so that you can show a tipical 0-100% progress bar
int lenghtOfFile = conexion.getContentLength();
// downlod the file
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(file);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
publishProgress((int) (total * 100 / lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
}
return null;
}
}.execute();
}
place a breakpoint in inputstream object to see is there any stream. then debug output stream to see the results.

Saving an mp3 file to sd

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

Save image from url to sdcard

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 :-)

How to download full data to a byte array

I want to download a zip file via a url. And I want to encrypt that without writing to the sd card. How to get full byte data from the url?
Thanks in advance
protected String doInBackground(String... url) {
int count;
try {
URL url1 = new URL(url[0]);
URLConnection conexion = url1.openConnection();
conexion.connect();
// this will be useful so that you can show a tipical 0-100%
// progress bar
int lenghtOfFile = conexion.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url1.openStream());
OutputStream output = new FileOutputStream(
"/sdcard/downloaded.zip");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
publishProgress((int) (total * 100 / lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
}
return null;
}
Use a ByteArrayOutputStream() and after downloading call toByteArray() function.

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