Wednesday, August 29, 2012

ImageView from URL


public class ImageLoadActivity extends Activity{

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
     
        LinearLayout m_linear = new LinearLayout(this);
        m_linear.setOrientation(LinearLayout.VERTICAL);
     
        ImageView i = new ImageView(this);
        m_linear.addView(i);
     
        new DownloadImage(i).execute("http://www.mobisights.com/wp-content/uploads/2012/08/001028312.jpg");

        setContentView(m_linear);
    }
 
    private class DownloadImage extends AsyncTask<String, Void, Bitmap> {
        ImageView image;

        public DownloadImage(ImageView image) {
            this.image = image;
        }

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

        protected void onPostExecute(Bitmap result) {
            image.setImageBitmap(result);
        }
    }
}


No comments:

Post a Comment