Android phone crashes on downloading video(mp4) file - android

I want my app to download a video from an url.
For now I want to write download the file to my sd card.
I tried some different scripts, I don't receive an android.os.NetworkOnMainThreadException exception. But my application crashes.
Download a file programatically on Android
What is best way to download files from net programatically in android?
Does anyone know how to create a working method?
To solve this exception it has to be an async task.
public static void downloadFile(String url, File outputFile) {
try {
URL u = new URL(url);
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = new byte[contentLength];
stream.readFully(buffer);
stream.close();
DataOutputStream fos = new DataOutputStream(new FileOutputStream(outputFile));
fos.write(buffer);
fos.flush();
fos.close();
} catch(Exception e) {
Log.e("theple", "" + e);
}
}
Logs:
03-14 12:09:46.535: E/theple(6987): android.os.NetworkOnMainThreadException

I made it working, thx for the help anyway.
My code:
public class FileDownloader extends AsyncTask<String, Integer, String>
{
#Override
protected String doInBackground(String... params)
{
try {
URL u = new URL(params[0]);
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = new byte[contentLength];
stream.readFully(buffer);
stream.close();
DataOutputStream fos = new DataOutputStream(new FileOutputStream(new File(params[1])));
fos.write(buffer);
fos.flush();
fos.close();
} catch(Exception e) {
Log.e("theple", "" + e);
}
return null;
}
}

There are many ways you can perform downloading,in-spite of creating a method for it you should use "thread,Async class or service",That error "Network on Main thread comes due to the process is taking time".
I am showing example of Using Async Task and with Service
*
*class DownloadFile extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... sUrl) {
try {
URL url = new URL(sUrl[0]);
URLConnection connection = url.openConnection();
connection.connect();
// this will be useful so that you can show a typical 0-100% progress bar
int fileLength = connection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/file_name.extension");
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
}
return null;
}**
And With Service
you can use :
class DownloadService extends IntentService {
public static final int UPDATE_PROGRESS = 8344;
public DownloadService() {
super("DownloadService");
}
#Override
protected void onHandleIntent(Intent intent) {
String urlToDownload = intent.getStringExtra("url");
ResultReceiver receiver = (ResultReceiver) intent.getParcelableExtra("receiver");
try {
URL url = new URL(urlToDownload);
URLConnection connection = url.openConnection();
connection.connect();
// this will be useful so that you can show a typical 0-100% progress bar
int fileLength = connection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/BarcodeScanner-debug.apk");
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
Bundle resultData = new Bundle();
resultData.putInt("progress" ,(int) (total * 100 / fileLength));
receiver.send(UPDATE_PROGRESS, resultData);
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
}
Bundle resultData = new Bundle();
resultData.putInt("progress" ,100);
receiver.send(UPDATE_PROGRESS, resultData);
}
}
Hope this will be helpful for you.

Related

Android - Cannot play audio after downloading from Url because of wrong data source. How to solve this?

I have downloaded an audio file from Url thanks to Giridharan's answer in the link below:
Android - Save image from URL onto SD card
The problem is that I cannot play it, the error is as follows:
java.io.IOException: setDataSourceFD failed.: status=0x80000000
I'm sure that the audio url on the Internet is working fine, because I can play audio directly from that Url without downloading, but after download it then cannot play anymore, maybe the data source was changed incorrectly while downloading.
So how to solve this problem? Any help will be appreciated! Thanks for reading.
Download Audio from web using below code.
private void startDownload() {
String url = "http://farm1.static.flickr.com/114/298125983_0e4bf66782_b.jpg";
// Smaple url String url = "http://farm1.static.flickr.com/114/298125983_0e4bf66782_b.jpg";
new DownloadFileAsync().execute(url);
}
class DownloadFileAsync extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// create dialog if you want
}
#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/myAudio.mp3");
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;
}
#Override
protected void onPostExecute(String unused) {
// hide/dismiss dialog if you have any
}
}
then play it using /sdcard/myAudio.mp3 path in your media player.
if have any issue see this thread.
Finally I found the solution to my question, and now I post here to help everyone else faces the same problem can overcome it.
public String downloadAudioFromUrl(String url) {
int count;
File file = null;
try {
URL urls = new URL(url);
URLConnection connection = urls.openConnection();
connection.connect();
// this will be useful to show the percentage 0-100% in progress bar
int lengthOfFile = connection.getContentLength();
File storageDir = new File(Environment.getExternalStorageDirectory().toString() + "/Photo_Quiz/Audio");
if (!storageDir.exists()) {
storageDir.mkdirs();
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmssSSS").format(new Date());
String filename = "audio_" + timeStamp + ".3gp";
file = new File(storageDir, filename);
InputStream input = new BufferedInputStream(urls.openStream());
OutputStream output = new FileOutputStream(file.getAbsolutePath());
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress...
// publishProgress((int) (total * 100 / lengthOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
notifyNewMediaFile(file);
} catch (Exception e) {
e.printStackTrace();
}
return file.getAbsolutePath();
}

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.

download file and crash app

my app downloaded file with this :
public class DownloadService extends IntentService {
public static final int UPDATE_PROGRESS = 8344;
public DownloadService() {
super("DownloadService");
}
#Override
protected void onHandleIntent(Intent intent) {
String urlToDownload = intent.getStringExtra("url");
String fileToStore= intent.getStringExtra("file");
ResultReceiver receiver = (ResultReceiver) intent.getParcelableExtra("receiver");
try {
URL url = new URL(urlToDownload);
URLConnection connection = url.openConnection();
connection.connect();
// this will be useful so that you can show a typical 0-100% progress bar
int fileLength = connection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(connection.getInputStream());
OutputStream output = new FileOutputStream("/sdcard/SingingStudio/"+fileToStore+".zip");
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
Bundle resultData = new Bundle();
resultData.putInt("progress" ,(int) (total * 100 / fileLength));
receiver.send(UPDATE_PROGRESS, resultData);
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
}
Bundle resultData = new Bundle();
resultData.putInt("progress" ,100);
receiver.send(UPDATE_PROGRESS, resultData);
}
}
my app work in any device properly . but in all kitkat version of android for example xperia z4 and too galaxy grande 4.2.2
when file downloaded . if i go to any activity app is crash .
but if it download file with DownloadManager app is not crash .
why ?

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

Android: Complete file not downloaded from url

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.

Categories

Resources