Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android : Load image from web URL [duplicate]

Possible Duplicate:
Loading remote images

I am developing an application where I have a list in which each row has an image,

this image is loaded from a web URL.

below is my code

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ImageView
            android:id="@+id/list_row_img"
            android:layout_width="200dp"
            android:layout_height="200dp"
            />

    <TextView
            android:id="@+id/list_row_description"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />

</LinearLayout>

and this is the activity code

@Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ImageView img= (ImageView) findViewById(R.id.list_row_img);
    Bitmap bm = null;
    try {
         URL aURL = new URL("http://image10.bizrate-images.com/resize?sq=60&uid=2216744464");
         URLConnection conn = aURL.openConnection();
         conn.connect();
         InputStream is = conn.getInputStream();
         BufferedInputStream bis = new BufferedInputStream(is);
         bm = BitmapFactory.decodeStream(bis);
         img.setImageBitmap(bm);
         bis.close();
         is.close();

         } catch (Exception e) {
            Log.v("EXCEPTION", "Error getting bitmap", e);
         }
}

when I run i get nothing on the device. only a gray screen and no exception happens.

note that i added this permission in the manifest file

<uses-permission android:name="android.permission.INTERNET" />

can anyone help me please ?

like image 767
Rana Osama Avatar asked Nov 30 '22 23:11

Rana Osama


1 Answers

try this you can exeecute it by

      new DownloadImageTask((ImageView)  im1).execute(url here);

    private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
    ImageView bmImage;

    public DownloadImageTask(ImageView bmImage) {
        this.bmImage = bmImage;
    }

    protected Bitmap doInBackground(String... urls) {
        String urldisplay = urls[0];
        Bitmap mIcon11 = null;
        try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            mIcon11 = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return mIcon11;
    }


/*    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
        showProgressDialog();
    }*/

    protected void onPostExecute(Bitmap result) {
        //pDlg.dismiss();
        bmImage.setImageBitmap(result);
    }}
like image 105
Athul Harikumar Avatar answered Dec 05 '22 00:12

Athul Harikumar