Friday, May 29, 2015

Read image from internal memory in Android

Pada source di bawah sebelum mengakses image dari internal memory terlebih dahulu mendowload image tersebut dari internet. 


1. XML Layout
Buat dua XML layout file di folder “res/layout/” :

res/layout/activity_main.xml – pada halaman tersebut tambahkan ImageView

File : activity_main.xml
 <ImageView
        android:id="@+id/imageView"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:gravity="center"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        android:scaleType="fitXY"/>

2. Activity
Pada activity class daftarkan ImageView yang dibuat.

File : MainActivity.java


ImageView imageView;
String url = "https://www.google.co.id/images/srpr/logo11w.png" 
public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 imageView = (ImageView) findViewById(R.id.imageView);
}

3. Download File
Dowload file dari alamat url tersebut kemudian menyimpannya ke dalam memori internal

private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
 ImageView pImage;
 FileOutputStream ontput;
 String Path = "sdcard0/Download/";

 protected Bitmap doInBackground(String... p_urls) {
  String urldisplay = p_urls[0];
  Bitmap p_image = null;
  try {
   InputStream in = new java.net.URL(urldisplay).openStream();
   p_image = BitmapFactory.decodeStream(in);
   ontput = new FileOutputStream(Path + ImageFileName(urldisplay));
   p_image.compress(Bitmap.CompressFormat.PNG, 90, ontput);
   
  } catch (Exception e) {
   Log.e("Error", e.getMessage());
   e.printStackTrace();
  } finally {
   try {
    ontput.close();
   } catch (Exception e2) {
    Log.e("Error", e2.getMessage());
    e2.printStackTrace();
   }
  }
  return null;
 } 
}
private String ImageFileName(String p_url) {
 String ext = p_url.substring(p_url.lastIndexOf("/") );
 if (ext.indexOf("?")>-1) {
  ext = ext.substring(0,ext.indexOf("?"));
 }
 if (ext.indexOf("%")>-1) {
  ext = ext.substring(0,ext.indexOf("%"));
 }
 return ext;
}

Kemudian buat falidasi untuk mengecek apakah file sudah ada di memori atau belum.

String path = "sdcard0/Download/"+ ImageFileName(catalog.image_url);
Bitmap bitmap = BitmapFactory.decodeFile(path);
File filePath = new File(path);
if (!filePath.exists()) {
 new DownloadImageTask().execute(catalog.image_url);
 imageView.setImageBitmap(bitmap);
}else{
 imageView.setImageBitmap(bitmap);
}

S.M.H