Android - Downloading Image From Web, Saving To Internal Memory In Location Private To App, Displaying For List Item
What I'm trying to do is this: I want my application to download an image from the Internet and save it to the phone's internal memory in a location that is private to the applicat
Solution 1:
it seems that some code is left out, I re-wrote it like this:
ProductUtils.java
public static String productLookup(String productID, Context c) throws IOException {
URL url = new URL("http://www.samplewebsite.com/" + productID + ".jpg");
InputStream input = null;
FileOutputStream output = null;
try {
String outputName = productID + "-thumbnail.jpg";
input = url.openConnection().getInputStream();
output = c.openFileOutput(outputName, Context.MODE_PRIVATE);
int read;
byte[] data = new byte[1024];
while ((read = input.read(data)) != -1)
output.write(data, 0, read);
return outputName;
} finally {
if (output != null)
output.close();
if (input != null)
input.close();
}
}
Solution 2:
Looks like simply referring to the image file name when trying to read it was not enough, and I had to call getFilesDir() to get the path of the file storage. Below is the code I used:
Stringpath= context.getFilesDir().toString();
StringfileName= cursor.getString(cursor.getColumnIndex(DbAdapter.KEY_PRODUCT_ID));
if (fileName != null && !fileName.equals("")) {
BitmapbMap= BitmapFactory.decodeFile(path + "/" + fileName);
if (bMap != null) {
thumbnail.setImageBitmap(bMap);
}
}
Solution 3:
voidwriteToFile(Bitmap _bitmapScaled)
{
ByteArrayOutputStreambytes=newByteArrayOutputStream();
_bitmapScaled.compress(Bitmap.CompressFormat.PNG, 40, bytes);
try{
File f;
//you can create a new file name "test.jpg" in sdcard folder.if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
f =newFile(android.os.Environment.getExternalStorageDirectory(),"FamilyLocator/userimages/"+imageName);
elsef=newFile(Environment.getDataDirectory(),"FamilyLocator/userimages/"+imageName);
f.createNewFile();
//write the bytes in fileFileOutputStreamfo=newFileOutputStream(f);
fo.write(bytes.toByteArray());
// remember close de FileOutput
fo.close();
}catch(Exception e){e.printStackTrace();}
}
Post a Comment for "Android - Downloading Image From Web, Saving To Internal Memory In Location Private To App, Displaying For List Item"