Downloading mp3 with meta data/properties such as title, artists and etc - java

I have the following code. Everything works fine except that the downloded MP3 file does not have any property (metadata) such as Artist, title and etc when I play using the default music player. If tried to download the same mp3 file from the site directly using android browser and play using the default music player, all the metatdata are intact (ie. music player display title, artist and etc).
#Override
protected String doInBackground(String... aurl) {
int count;
i = Integer.parseInt(aurl[0]);
try {
sura = "abc.mp3";
String addr = "http://www.xyzabc.com/" + sura;
URL url = new URL(addr);
HttpURLConnection conexion = (HttpURLConnection) url.openConnection();
conexion.setRequestMethod("GET");
conexion.setDoOutput(true);
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
InputStream input = new BufferedInputStream(url.openStream());
File file = new File(rootDir + "/mysite/" + sura);
OutputStream output = new FileOutputStream(file);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1 & run == true) {
total += count;
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
}
return null;
}

The System content provider didn't update as soon as your downloading complete.
Try restart your emulator or install/unstall your sd card, see if the content provider updates.
The uri is MediaStore.Audio.Media.EXTERNAL_CONTENT_URI and you can get details by query MediaStore.Audio.Media.DATA, MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.COMPOSER, MediaStore.Audio.Media.ALBUM,
MediaStore.Audio.Media.ARTIST and others (All in MediaStore.Audio.Media.*)
If you want to get the information immediately, maybe you should update the Content Provider manual by yourself.

Related

how to download image / files from ftp server via url in android?

private String ftpUrl = "ftp://%s:%s#%s/%s;";
private static String host = "www.krishnas.com.np";
private static String user = "tryagn#krishnas.com.np";
private static String pass = "technology_krixnas";
private static String filePath = "112.jpg";
private static String savePath =
Environment.getExternalStorageDirectory() + "/" +
Environment.DIRECTORY_DCIM +"/abe.jpg";
My doInBackground() in asynctask is:
protected String doInBackground(String... f_url) {
int count;
try {
ftpUrl = String.format(ftpUrl, user, pass, host, filePath);
//System.out.println("URL: " + ftpUrl)
Log.d("-----------", ""+ftpUrl);
// try {
//URL url = new URL(ftpUrl);
//URLConnection conn = url.openConnection();
// InputStream inputStream = conn.getInputStream();
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// this will be useful so that you can show a tipical 0-100% progress bar
int lenghtOfFile = conection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream(), 8192);
// Output stream
OutputStream output = new FileOutputStream(savePath);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
i=(int)((total*100)/lenghtOfFile);
publishProgress(""+(int)((total*100)/lenghtOfFile));
// i = (int)((total*100)/lenghtOfFile);
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// c
// losing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
I want to download a file/image from my FTP server, it shows image in link but does not download in internal storage. I am learning ftp server downloader not the http request!! Don't know where it goes wrong??
You are using external storage to store file Environment.getExternalStorageDirectory()
So if you want to store it in internal storage,
You can use getFilesDir() or getCacheDir():
File file = new File(context.getFilesDir(), filename);
For more Information refer this link:

Android Webview app not downloading successful

My Android app has a Webview to access to my website. I noticed in the server that when a file is downloaded by the app the bandwidth used is less than when is downloaded by another device or browser.
In method onDownloadStart I call to an AsyncTask class:
protected String doInBackground(String... sUrl) {
try {
URL url = new URL(sUrl[0]);
//Getting directory to store the file
//Connection handler
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.connect();
//Obtaining filename
File outputFile = new File(directory, filename);
InputStream input = new BufferedInputStream(connection.getInputStream());
OutputStream output = new FileOutputStream(outputFile);
byte buffer[] = new byte[1024];
int bufferLength = 0;
int total = 0;
while ((bufferLength=input.read(buffer))!=-1) {
total += bufferLength;
output.write(buffer, 0, bufferLength);
}
connection.disconnect();
output.flush();
output.close();
input.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
Files downloaded are empty altough their filename and format are correct and I receive HTTP 200 message from the server; also execution does not enter into the while loop. I have tried to change buffer size and the problem is not solved.

Android how to use Environment.getExternalStorageDirectory() corretly

Android how to use Environment.getExternalStorageDirectory()
How can i use Environment.getExternalStorageDirectory() to read/write a image from the SD card ? or is there a better way to do it?
I did use the source to download e save the image:
try {
URL url = new URL(urlBaseImagem + icone);
URLConnection conection = url.openConnection();
conection.connect();
// this will be useful so that you can show a tipical 0-100% progress bar
int lenghtOfFile = conection.getContentLength();
//
// download the file
InputStream input = new BufferedInputStream(url.openStream(), 8192);
// Output stream
//File sdCard = Environment.getExternalStoragePublicDirectory(DOWNLOAD_SERVICE);
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File(sdCard.getAbsolutePath() + "/cardapioweb/rest/");
if(directory.exists() == false){
directory.mkdirs();
}
File outputFile = new File(directory, icone);
OutputStream output = new FileOutputStream(outputFile);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
//publishProgress(""+(int)((total*100)/lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
Log.w("CardapioWeb:" , "Imagem " + outputFile.toString() + " salva no sdcard");
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
I did use the source to load e show the image:
File arq = new File(this.sdCard.getAbsolutePath() + "/cardapioweb/rest/" + filialDataCollection.get(position).get(KEY_ICONE));
//verifica se a imagem foi baixada com sucesso
if(arq.exists() == true){
//deve exibir a imagem do sdcard
File outputFile1 = new File(this.sdCard.getAbsolutePath() + "/cardapioweb/rest/", filialDataCollection.get(position).get(KEY_ICONE));
Drawable imagem = Drawable.createFromPath(outputFile1.toString());
holder.tvWeatherImage.setImageDrawable(imagem);
}
The above codes works perfectly fine on the emulator (Android Virtual Device) with Eclipse !!!!
But when I generate the apk and install on my Galaxy S4, the app can not read images (no error is generated). Just does not display the images. What could be wrong?
Put a log in your code to see what
outputFile1.toString();
actually points to, is it what you expect?
Personally, I would have used outputFile1.getAbsolutePath(); NOT the line below:
Drawable imagem = Drawable.createFromPath(outputFile1.toString());

Android, Download a .txt file and save internally

like the title states i am simply trying to download a test.txt file, the following url and save it internally, ideally within drawable.
i have been trying to modify this to work but will little success i keep getting "unable to download null" errors
int count;
try {
URL url = new URL("https://www.darkliteempire.gaming.multiplay.co.uk/testdownload.txt");
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
InputStream is = url.openStream();
File testDirectory = new File(Environment.getExternalStorageDirectory() + "/Download");
if (!testDirectory.exists()) {
testDirectory.mkdir();
}
FileOutputStream fos = new FileOutputStream(testDirectory + "/test.txt");
byte data[] = new byte[1024];
long total = 0;
int progress = 0;
while ((count = is.read(data)) != -1) {
total += count;
int progress_temp = (int) total * 100 / lenghtOfFile;
fos.write(data, 0, count);
}
is.close();
fos.close();
} catch (Exception e) {
Log.e("ERROR DOWNLOADING", "Unable to download" + e.getMessage());
}
There must be a simpler way to do this?
the file itself is tiny with perhaps 3 or 4 lines of text so i dont need anything fancy
Please Update your below code line and write valid url.
URL url = new URL("https://www.http://darkliteempire.gaming.multiplay.co.uk/testdownload.txt");
after write valid url your code line look like this.
URL url = new URL("http://www.darkliteempire.gaming.multiplay.co.uk/testdownload.txt");
it will solve your problem.
Using AQuery library you get something pretty straightforward. Plus you'll get hips of other cool functions to shorten your code.
http://code.google.com/p/android-query/wiki/AsyncAPI
String url = "https://picasaweb.google.com/data/feed/base/featured?max-results=16";
File ext = Environment.getExternalStorageDirectory();
File target = new File(ext, "aquery/myfolder/photos.xml");
aq.progress(R.id.progress).download(url, target, new AjaxCallback<File>(){
public void callback(String url, File file, AjaxStatus status) {
if(file != null){
showResult("File:" + file.length() + ":" + file, status);
}else{
showResult("Failed", status);
}
}
});

Updating progress dialog

I am trying to make an application that can help me to evaluate the time to download the file from a web resource. I have found 2 samples:
Download a file with Android, and showing the progress in a ProgressDialog
and
http://www.helloandroid.com/tutorials/how-download-fileimage-url-your-device
The second example shows a smaller download time, but I cannot understand how to update progress dialog using it. I think something should be done with "while" expression in second case, but I cannot find what. Could someone give me any piece of advice?
UPD:
1st code:
try {
time1 = System.currentTimeMillis();
URL url = new URL(path);
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("/sdcard/analyzer/test.jpg");
byte data[] = new byte[1024];
long total = 0;
time11 = System.currentTimeMillis();
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
publishProgress((int)(total*100/lenghtOfFile));
output.write(data, 0, count);
}
time22= System.currentTimeMillis()-time11;
output.flush();
output.close();
input.close();
} catch (Exception e) {}
timetaken = System.currentTimeMillis() - time1;
2nd code:
long time1 = System.currentTimeMillis();
DownloadFromUrl(path, "test.jpg");
long timetaken = System.currentTimeMillis() - time1;
Where
public void DownloadFromUrl(String imageURL, String fileName) { //this is the downloader method
try {
URL url = new URL(imageURL); //you can write here any link
File file = new File(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(PATH+file);
fos.write(baf.toByteArray());
fos.close();
} catch (IOException e) {
Log.d("ImageManager", "Error: " + e);
}
So the thing is that first method seems to be slower for about 30%.
The second example may run faster, but it monopolizes the GUI thread. The first approach, using AsyncTask, is better; it allows the GUI to stay responsive as the download proceeds.
I found it helpful to compare AsyncTask with SwingWorker, as shown in this example.
first link is best. But i can't provide code( it's home comp) in monday or later i can provide full function. But :
private class DownloadFile extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... url) {
int count;
try {
URL url = new URL(url[0]);
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("/sdcard/somewhere/nameofthefile.ext");
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;
}
this class are best for it ( imho) . publishProgress it's simple function where u have max two lines. Set max and set current. How u can see in this code lenghtOfFile it's how many bytes have ur file. total-current progress ( example 25 from 100 bytes) . Run this class easy : DownloadFile a = new DownloadFile(); a.execute(value,value);//or null if u not using value. Hope u understand me , im not good speaking on english.

Categories