How to download an MP3 file - android

I want to download an mp3 file using an AsyncTask or a thread.
How can I do this?

You can do something like this...
When you decide to start downloading:
new Thread(new Runnable()
{
#Override
public void run()
{
File out;
Downloader DDL;
DDL=new Downloader();
out=new File(Environment.getExternalStorageDirectory() + "/DestFileName.txt");
DDL.DownloadFile("SourceURL",out);
}
}).start();
Where the downloader class is
public class Downloader {
public void Downloader()
{
// TODO Auto-generated method stub
}
public boolean 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(FileNotFoundException e)
{
return false;
}
catch (IOException e)
{
return false;
}
return true;
}
}

Refer to this thread:
android: file download in background

Use This Function In for Downloading Files On SDCARD
public void downloadNauhe(String url) {
class DownloadFile extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... url) {
int count;
try {
URL url1 = new URL("http://downloads.hussainiat.com/nauhey/arsalan_haider/vol_2011_-_12/01_tum_jawab_e_zulm_dogay_-_arsalan_haider_2011_-_2012.mp3");
URLConnection conexion = url1.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
InputStream input = new BufferedInputStream(url1.openStream());
OutputStream output = new FileOutputStream("/sdcard/01_manum_abbas_as_-_mesum_abbas_2012.mp3");
byte data[] = new byte[1024];
long total = 0;
System.out.println("downloading.............");
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int)((total/(float)lenghtOfFile)*100));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
mprBar.setProgress(values[0]);
}
}
DownloadFile downloadFile = new DownloadFile();
downloadFile.execute(url);
}
Don'forget to add permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>

Related

Internal storage not storing file on my device

Hi friends have lot of confusion.
First thing is it's not storing in on my device instead of it stores on my emulator under this path data/data/com.customfonts/files/Robotoo.ttf. Then when I try to get file throwing Runtime Exception file not found because it's searching under data/user/0/com.customfonts/Robotoo.ttf instead of searching data.data/com.customfonts/files/Robotoo.ttf.
getDirectory.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
new DownloadingTask().execute();
Log.i("FilePAthFirst",""+getFilesDir());
}
});
btnGETDATA.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String filename="Robotoo.ttf";
getTypeface(filename);
}
});
private Typeface getTypeface(String filename)
{
Typeface font;
try
{
font = Typeface.createFromFile(getFilesDir() +"/"+filename);
Log.i("FOnt found",""+font);
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
return font;
}
private class DownloadingTask extends AsyncTask<Void,Void,Void>{
#Override
protected Void doInBackground(Void... voids) {
try {
URL url = new URL(fonturl);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.connect();
FileOutputStream fos = new FileOutputStream(getApplicationContext().getFilesDir()+ "Robotoo.ttf");
Log.i("Download","complete");
Log.i("FOS",""+fos.toString());
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 (Exception e) {
e.printStackTrace();
outputFile = null;
Log.e("Error", "Download Error Exception " + e.getMessage());
}
return null;
}
}
Harmonize the code to get the file path for saving the file and loading the file.
To load the tff also use getApplicationContext().getFilesDir()+filename
I used your same code, which is in answer it working fine, May be you can check you have permission for the internet in Manifest <uses-permission android:name="android.permission.INTERNET"></uses-permission>, if you already have this, You can wait till onPostExecute of your AsyncTask and check you are getting any error.
Internal storage
And For internal storage, It will not be constant as data.data/com.customfonts/files/ from Android 6.0, It will be dynamic, We should not hard code the path(You are doing that is correct)
Refer this Offical Doc
Edited: Forgot to Add earlier that to writing a file in internal storage as per doc we should use openFileOutput so I am using that.
private class DownloadingTask extends AsyncTask<Void,Void,Void> {
#Override
protected Void doInBackground(Void... voids) {
try {
URL url = new URL("[your url here]");
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.connect();
Log.d("sdsdfds", "doInBackground: " + getApplicationContext().getFilesDir());
FileOutputStream fos = getApplicationContext().openFileOutput("Robotoo4.ttf", MODE_PRIVATE);
Log.i("Download","complete");
Log.i("FOS",""+fos.toString());
InputStream is = c.getInputStream();
byte[] buffer = new byte[4 * 1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
File file = new File(getFilesDir() + "/" + "Robotoo4.ttf");
Log.d("", "onPostExecute: " + file.exists() + " " + file.getAbsolutePath() + " Length " + file.length() );
}
}

Store and retrieve image from URL in local database in an Android app

I am getting image path URL and now I want to get image from that URL and save in to local database but I am not able to convert it into bytes so that BLOB in database will accept it. I have tried a lot but all in vain. I used a code but ByteArrayBuffer not resolved type.
// code to convert image url into byte array
private byte[] getLogoImage(String url) {
try {
URL imageUrl = new URL(url);
URLConnection ucon = imageUrl.openConnection();
System.out.println("11111");
InputStream is = ucon.getInputStream();
System.out.println("12121");
BufferedInputStream bis = new BufferedInputStream(is);
System.out.println("22222");
ByteArrayBuffer baf = new ByteArrayBuffer(500);
int current = 0;
System.out.println("23333");
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
photo = baf.toByteArray();
System.out.println("photo length" + photo);
} catch (Exception e) {
Log.d("ImageManager", "Error: " + e.toString());
}
return accImage;
}
after that I have used tutorial "https://github.com/CoderzHeaven/StoreImageSqliteAndroid" to save into database
Replace your method by this
private byte[] getLogoImage(String url) {
try {
URL imageUrl = new URL(url);
URLConnection ucon = imageUrl.openConnection();
System.out.println("11111");
InputStream is = ucon.getInputStream();
System.out.println("12121");
byte[] buffer = new byte[8192];
int bytesRead;
ByteArrayOutputStream accImage = new ByteArrayOutputStream();
while ((bytesRead = is.read(buffer)) != -1) {
accImage.write(buffer, 0, bytesRead);
}
return accImage.toByteArray();
} catch (Exception e) {
Log.d("ImageManager", "Error: " + e.toString());
}
return null;
}
**You can try this method for download and save image into database**
public class MainActivity extends Activity {
protected SQLiteDatabase sqlitedatabase_obj;
DataBaseHelper databasehlpr_obj;
int accId;
byte[] accImage;
byte[] logoImage;
byte[] photo;#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AndroidContext.setContext(this);
sqlitedatabase_obj = DataBaseHelper.getInstance().getDb();
new ImageDownloader().execute("http://images.100bestbuy.com/images/small_137385013870957.jpg");
}
/* get logo image method */
private byte[] getLogoImage(String url) {
try {
URL imageUrl = new URL(url);
URLConnection ucon = imageUrl.openConnection();
System.out.println("test1");
InputStream is = ucon.getInputStream();
System.out.println("test2");
BufferedInputStream bis = new BufferedInputStream(is);
System.out.println("test3");
ByteArrayBuffer baf = new ByteArrayBuffer(500);
int current = 0;
System.out.println("test4");
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
photo = baf.toByteArray();
System.out.println("photo length" + photo);
} catch (Exception e) {
Log.d("ImageManager", "Error: " + e.toString());
}
return accImage;
}
public void insertUser() {
ContentValues userdetailValues = new ContentValues();
userdetailValues.put("account_image", photo);
sqlitedatabase_obj.insert(DataBaseHelper.IMG_table, null, userdetailValues);
}
/* AsyncTask method */
private class ImageDownloader extends AsyncTask<String, Void, Void> {
private ProgressDialog progressDialog;
#Override
protected Void doInBackground(String... param) {
sqlitedatabase_obj.delete(DataBaseHelper.IMG_table, null, null);
logoImage = getLogoImage(param[0]);
insertUser();
}
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(MainActivity.this, "Wait", "Downloading Image");
}
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
}
}
}

download file from url and read later locally

I want to download a file from url to read this file later locally. I have this code to download the file:
private void startDownload() {
String url = "my url";
new DownloadFileAsync().execute(url);
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Actualizando programa..");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
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("/myfile.json");
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]));
}
#SuppressWarnings("deprecation")
#Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
I donĀ“t know where it will be save the file with this code and how can I read this file later locally.
To save your file, to your app dir use this:
//save to cache
try {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File(activity.getFilesDir(), "/myfile.json")));
oos.writeObject(list);
oos.flush();
oos.close();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
To retrieve content:
ObjectInputStream dis = new ObjectInputStream(new FileInputStream(new File(context.getFilesDir(), "/myfile.json")));
ArrayList<String> = (ArrayList<String>) dis.readObject();
dis.close();
I hope it helps!

Save downloaded file using the External Storage (private)

this is my code to download a file and save it in the internal storage:
public class getResults extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params){
String fileName = "results"+month+year+".pdf";
URLConnection conn;
try {
URL url = new URL(params[0]);
conn = url.openConnection();
int contentLength = conn.getContentLength();
DataInputStream in = new DataInputStream(conn.getInputStream());
byte[] buffer = new byte[contentLength];
in.readFully(buffer);
in.close();
if (buffer.length > 0) {
DataOutputStream out;
FileOutputStream fos = openFileOutput(fileName,Context.MODE_PRIVATE);
out = new DataOutputStream(fos);
out.write(buffer);
out.flush();
out.close();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "true";
}
protected void onPostExecute(String result){
}
}
but how I have to change the code, so that I save the file on External Storage and app-private?
Use FileOutputStream fos = new FileOutputStream(getExternalFilesDir() + "/" + fileName); But this is not private memory.

How to write XML file on Android, getting from remote server

I need sometimes read XML file from remote server, and replace data in XML on my Android device.
I read data through XmlPullParser:
XmlPullParser users;
try {
URL xmlUrl = new URL("http://xx.xx.xx.xx/1.xml");
users = XmlPullParserFactory.newInstance().newPullParser();
users.setInput(xmlUrl.openStream(), null);
}
How can I replace it on Android?
Simply use this code, it's overwrites the file with the new file you download from the internet.
public static boolean downloadFile(String fileToDownload, File newPath,
String newFileName) {
try {
URL url = new URL(fileToDownload);
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
if (!newPath.isDirectory()) {
CreateLog.createFolder(newPath.toString());
}
File file = new File(newPath.toString() + "/" + newFileName);
if (!file.isFile()) {
CreateLog.writeLogToFile(newPath.toString() + newFileName,
"%TEMP%");
}
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ((bufferLength = inputStream.read(buffer)) > 0) {
fileOutput.write(buffer, 0, bufferLength);
}
fileOutput.close();
return true;
} catch (MalformedURLException e) {
CreateLog.addToLog(e.toString());
return false;
} catch (IOException e) {
CreateLog.addToLog(e.toString());
return false;
}
}
public static void createFolder(String filePath) {
File createFolder = new File(filePath);
createFolder.mkdirs();
}
A cleaner method is to use a Asynctask, the code runs in a new thread. But it's a bit harder to code.
private class GetProblems extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
for (String myUrl : params) {
try {
URL url = new URL(myUrl);
URLConnection ucon = url.openConnection();
ucon.setRequestProperty("Accept", "application/xml");
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
String str = new String(baf.toByteArray(), "UTF8");
return str;
} catch (MalformedURLException e) {
CreateLog.addToLog("[GetProblems] " + e.toString());
} catch (IOException e) {
CreateLog.addToLog("[GetProblems] " + e.toString());
}
}
return "error";
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
// updateProgressBar(values[0]);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
...write result to a file
}
}
Run the AsyncTask code:
new GetProblems().execute("http://myurl.com/xmlfile.xml");

Categories

Resources