Android how to use Environment.getExternalStorageDirectory() corretly - java

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());

Related

Remote file transfer using java nio

I am trying to use JAVA NIO to transfer a file from host A to client B without having to download the file locally and then giving the client B a link to download the file.
I am running a spark Apache framework and using maven project.
I mapped the request http://localhost:8080/download/hello in Spark using :
get("/download/:id",RequestHandler::downloadHandler);
Inside of the function is the code that downloads the file from :
"https://download.springsource.com/release/STS/3.8.1.RELEASE/dist/e4.6/spring-tool-suite-3.8.1.RELEASE-e4.6-linux-gtk-x86_64.tar.gz"
try {
URL url = new URL("https://download.springsource.com/release/STS/3.8.1.RELEASE/dist/e4.6/spring-tool-suite-3.8.1.RELEASE-e4.6-linux-gtk-x86_64.tar.gz");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
int respCode = +httpURLConnection.getResponseCode();
System.out.println("response code : "+respCode);
if (respCode == HttpURLConnection.HTTP_OK){
String fileName = "";
String disposition = httpURLConnection.getHeaderField("Content-Disposition");
String contentType = httpURLConnection.getContentType();
int contentLength = httpURLConnection.getContentLength();
if (disposition != null) {
// extracts file name from header field
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10,
disposition.length() - 1);
}
} else {
// extracts file name from URL
fileName = url.toString().substring(url.toString().lastIndexOf("/") + 1,
url.toString().length());
}
System.out.println("Content-Type = " + contentType);
System.out.println("Content-Disposition = " + disposition);
System.out.println("Content-Length = " + contentLength);
System.out.println("fileName = " + fileName);
httpURLConnection.disconnect();
System.out.println("other stuff : ");
System.out.println(url.getHost());
ReadableByteChannel readableByteChannel = Channels.newChannel(url.openStream());
FileOutputStream fileOutputStream = new FileOutputStream(fileName);
FileChannel fileChannel = fileOutputStream.getChannel();
fileChannel.transferFrom(readableByteChannel, 0, Long.MAX_VALUE);
fileOutputStream.close();
readableByteChannel.close();
}
} catch (IOException e) {
e.printStackTrace();
}
I fetch the filename and file size using httpURLConnection and then processed to download the file. what I am trying to do is, instead of downloading the file locally using fileChannel.transferFrom(readableByteChannel, 0, Long.MAX_VALUE) transfer the file directly to the client.
I did some research and I think it is possible with using Socketchannels but I didn't understand how it is supposed to work.
I also read this article
https://examples.javacodegeeks.com/core-java/nio/java-nio-large-file-transfer-tutorial/
and tried to understand the class Reciever, but it is still not clear to me how.
I would appreciate some guidance. Thank you

Save .gif to sd card

I am still new in Android programming,
and I wanna do something,
download .gif from url
save that downloaded .gif to my sd card
call it using glide
When I download .gif, and write it to sdcard, it is not readable.
and the size bigger than original file.
here is the code I use :
URL url = new URL(imgUrl + params[0]);
File file = new File(path + params[0]);
long startTime = System.currentTimeMillis();
URLConnection ucon = url.openConnection();
Log.d(TAG, "on do in background, url open connection");
InputStream is = ucon.getInputStream();
Log.d(TAG, "on do in background, url get input stream");
BufferedInputStream bis = new BufferedInputStream(is);
Log.d(TAG, "on do in background, create buffered input stream");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Log.d(TAG, "on do in background, create buffered array output stream");
byte[] img = new byte[1024];
int current = 0;
Log.d(TAG, "on do in background, write byte to baos");
while ((current = bis.read()) != -1) {
baos.write(img, 0, current);
}
Log.d(TAG, "on do in background, done write");
Log.d(TAG, "on do in background, create fos");
FileOutputStream fos = new FileOutputStream(file);
fos.write(baos.toByteArray());
Log.d(TAG, "on do in background, write to fos");
fos.flush();
fos.close();
is.close();
Log.d(TAG, "on do in background, done write to fos");
thx before.
baos.write(img, 0, current); means to write current zeros (current byte from img).
Try changing the line to baos.write(current);.

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);
}
}
});

file not saved correctly

Im trying to get image using webservice and saved to sd card. The file saved but i couldnt open the file. Once i open the file it saying "could not load image". Below is my code.
httpTransport.call(SOAP_ACTION, envelope);
Object response = envelope.getResponse();
test = response.toString();
Blob picture = org.hibernate.Hibernate.createBlob(test.replaceAll("-", "").getBytes());
String FILENAME = "voucher1.jpg";
File root = Environment.getExternalStorageDirectory();
FileOutputStream f = new FileOutputStream(new File(root, FILENAME));
InputStream x=picture.getBinaryStream();
int size=x.available();
byte b[]= new byte[size];
x.read(b);
f.write(b);
f.close();
Please help. Thanks
I changed the format..instead use web service i just use the image url to retrieve the image and it works...
i try this and its work fine. Thanks.
URL url = new URL(fileURL);
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/caldophilus.jpg");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
i assume you need to call f.flush() in order to write out all data in stream to file.
f.flush();
f.close();

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

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.

Categories