Monday, 29 June 2015

android display images



1, image from drawable folder:


ImageView  productImage = (ImageView)view.findViewById(R.id.picking_detail_image);
productImage.setImageResource(R.drawable.new_logo);


2, from a url:  (this solution also can display JFIF images)


ImageView  productImage = (ImageView)view.findViewById(R.id.picking_detail_image);

Bitmap bitmap = getImageBitmap(imageURL);
if(bitmap != null){
    productImage.setImageBitmap(bitmap);
}


public Bitmap getImageBitmap(String url) {


    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);


    Bitmap bm = null;
    try {
        URL aURL = new URL(url);
        URLConnection conn = aURL.openConnection();
        conn.connect();
        InputStream is = conn.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);
        bm = BitmapFactory.decodeStream(bis);
        bis.close();
        is.close();
    } catch (IOException e) {
        Log.d(AbstractLogTagProvider.getCurrentLogTag("Utils"), "Error getting bitmap", e);
    }
    return bm;
}



You must have this:

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

Otherwise you will have this error:

android.os.NetworkOnMainThreadException









No comments:

Post a comment