Audio file does not appear in play music app - java

So I have and android app where i get an audio file from a server and write the file to my sdcard:
InputStream inputStream = resp.getEntity().getContent();
File mess = new File("sdcard/Music/message"+ i +".3gp");
OutputStream out = new FileOutputStream(mess);
int read = 0;
byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
inputStream.close();
out.flush();
out.close();
However when I do this my file does not appear in the play music app. how can I fix this?

Try this code:
File f = new File(Environment.getExternalStorageDirectory(),"/Music/message\"+ i +\".3gp\"") ;

I guess your downloaded file hasn't been inserted into the media provider database, and therefor won't show up in the Play Music app.
You could try triggering a rescan of the sdcard after downloading the file:
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));

Related

Android AsyncTask downloading .mp3 file - info and thumbnail

I am trying to download a mp3 file from a server.
I successfully made it, and I can play the file, but there is no thumbnail and file info, such as artist and album names.
When I'm downloading the file directly from chrome, the information I stated above, DOES get downloaded.
Any ideas how to get it work?
Here is my code:
URL url = new URL(urlDwn+urlVid);
HttpURLConnection connection =(HttpURLConnection) url.openConnection();
connection.connect();
//file length
int lengthOfFile = connection.getContentLength();
//intput - read file
InputStream inputStream = new BufferedInputStream(url.openStream(), 8192);
//output - write file
if(true) {
System.out.println("Downloading");
OutputStream outputStream = new FileOutputStream(root+"/"+fileName);
System.out.println(root+"/"+fileName);
byte data[] = new byte[1024];
long total = 0;
while ((count = inputStream.read(data)) != -1) {
total += count;
//progress
publishProgress((int) ((total * 100) / lengthOfFile));
//writing to file
outputStream.write(data,0, count);
}
outputStream.flush();
outputStream.close();
inputStream.close();
I SOLVED IT!
it seems that the thumbnail and mp3 tag(artist and etc) were downloaded properly. the problem was in the file manager itself(or maybe the Android system), so when I restarted the device, it shown itself!
EDIT
There is no need to reboot. All you need to do is to add the lines below to the onPostExecute method, which tell the system that a new file has been added.
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(file));
sendBroadcast(intent);

Android: Corrupted characters in PDF

I'm using HttpURLConnection to get a PDF file from the server then saving that PDF to the user's phone. Getting the file is working perfectly, but when saving, some files contain corrupted characters.
InputStream in = null;
OutputStream fileOutput = null;
try {
File file = new File(path);
file.mkdirs();
file = new File(path + File.separator + fileName + "." + fileExentsion);
file.createNewFile();
fileOutput = new FileOutputStream(file);
final byte[] buffer = new byte[1024];
int read;
in = conn.getInputStream();
while ((read = in.read(buffer)) != -1) {
fileOutput.write(buffer, 0, read);
}
fileOutput.flush();
return Uri.fromFile(file).toString(); // To open an intent in onPostExecute()
}
I tried using BufferedReader and BufferedWriter but the OS couldn't open the file after being saved. It is really weird because the same strings appears in other files correctly. And when downloading the file from a desktop, it looks good too.

android : Zip Folder is invalid

i have a created 3 xml files and compressed into a zip folder . The folder is send from server. When i download the zip folder through browser, its working properly and can extract the files. But when i download it from android application and store in SD card, it is corrupted. I pulled the file from SD card to computer and tried to extract the folder, it shows Zip Folder is invalid . My code is given below :
DefaultHttpClient httpclient1 = new DefaultHttpClient();
HttpPost httpPostRequest = new HttpPost(
Configuration.URL_FEED_UPDATE);
byte[] responseByte = httpclient1.execute(httpPostRequest,
new BasicResponseHandler()).getBytes();
InputStream is = new ByteArrayInputStream(responseByte);
// ---------------------------------------------------
File file1 = new File(Environment
.getExternalStorageDirectory() + "/ast");
file1.mkdirs();
//
File outputFile = new File(file1, "ast.zip");
FileOutputStream fos = new FileOutputStream(outputFile);
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
When I used
ZipInputStream zin = new ZipInputStream(new BufferedInputStream(is));
The ZipInputStream can't store values from stream.
I'd guess that your main mistake is where you get the input stream. What you are actually doing is to get the server response as String (BasicResponseHandler) and then converting that to bytes again. Since Java is all UTF-8 this most likely does not work.
Better try something like
HttpResponse response = httpclient1.execute(httpPostRequest);
InputStream is = response.getEntity().getContent()
(And do better null pointer checking, read the content in a try-catch block and make sure you close all resources in a finally block.)

File not found exception - when creating new file on sdcard in android

In my application, my requirement is need to install .APK file from assets folder, so that I am trying to copy the apk file from assets folder to sdcard, I get File Not Found Exception.
these the following code:
String file_path = Environment.getExternalStorageDirectory().getAbsolutePath();
String file_name = "ImageDownloading.apk";
AssetManager assetManager = getAssets();
try{
InputStream input = new BufferedInputStream(assetManager.open(file_name));
File path = new File(file_path);
if(!path.exists()){
path.mkdirs()
}
File file = new File(path,file_name);
OutputStream output = new FileOutputStream(file); // Here i get File Not Found Exception error.
byte data[] = new byte[1024];
int count;
while ((count = input.read(data)) != -1) {
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
}
catch(FileNotFoundException e){
Toast.makeText(MainActivity.this,"File not found exception " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
I have spent a lot of time but i did not find out the solution.
Do you have this permission set in your manifest file?
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Android: Issue in downloading to SD

I've developed an application in which user can download .mp3 files from server. And pre-defined a path to mnt/sdcard/foldername for saving such files. I had run my program in HTC, LG, Samsung works perfect but when I running a same program at samsung galaxy s2 getting an issue that can't able to write(store) in mnt/sdcard/foldername and tried
Environment.getExternalStorageDirectory().getAbsolutePath()
but its shows downloaded file names in given path and zero bytes for each files properties. Any idea to solve this issue?
The SG2 does usually not have a sd-card and uses the internal flash memory as "external" storage. I have solved this issue with this code:
private File initCacheDir() {
String sdState = android.os.Environment.getExternalStorageState();
File imageCacheDir;
if (sdState.equals(android.os.Environment.MEDIA_MOUNTED)) {
File sdDir = android.os.Environment.getExternalStorageDirectory();
imageCacheDir = new File(sdDir, "Android/data/" + App.PACKAGE_NAME + "/files/imageCache");
}
else
imageCacheDir = context.getCacheDir();
if(!imageCacheDir.exists())
imageCacheDir.mkdirs();
return imageCacheDir;
}
Note that this code give you the location of the cache directory, which is usually located in the Android/data folder on the sd-card.
You'll find more details how to solve this issue with SG2 here:
How could i get the correct external storage on Samsung and all other devices?
try this
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"yourfile");
else
cacheDir=context.getCacheDir();
if(!cacheDir.exists())
cacheDir.mkdirs();
I finally found the code
public void download(String urlToDownload){
URLConnection urlConnection = null;
try{
URL url = new URL(urlToDownload);
//Opening connection of currrent url
urlConnection = url.openConnection();
urlConnection.connect();
//int lenghtOfFile = urlConnection.getContentLength();
String PATH = Environment.getExternalStorageDirectory() + "/1/";
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, "file.mp3");
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = url.openStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
System.out.println("downloaded"+urlToDownload);
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
Source: link

Categories