如何使用AsyncTask将存储为字符串url的图像设置为android中的图像视图

时间:2012-05-11 11:35:51

标签: android arraylist imageview

我已将图像视图布局放在xml布局文件中

<ImageView 
  android:id="@+id/imageData"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_marginLeft="10sp"
  android:layout_marginTop="10sp"
/>

并在我的代码中设置相同的..

ImageView imageData = (ImageView) findViewById(R.id.imageview);

现在这个imageData应该在活动启动时保存图像..这是我的代码......

public class TestImageClass extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.imagetable);
        ImageView mChart = (ImageView) findViewById(R.id.imageview);
        String testurl = "http://....some image name....jpg";
        mChart.setTag(testurl);
        new DownloadImagesTask().execute(mChart);


    }   
    public class DownloadImagesTask extends AsyncTask<ImageView, Void, Bitmap> {

        ImageView imageView = null;

        @Override
        protected Bitmap doInBackground(ImageView... imageViews) {
            this.imageView = imageViews[0];
            return download_Image((String)imageView.getTag());
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            imageView.setImageBitmap(result);
        }


        private Bitmap download_Image(String url) {

            Bitmap bm = null;
            try {
                Log.e("inside", "download image.....");
                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();
                Log.e("going out of", "download image.....");
            } catch (IOException e) {
                Log.e("Hub","Error getting the image from server : " + e.getMessage().toString());
            } 

            return bm;          
}
}
}

那么现在如何将这个位图对象“bm”设置为我的ImageView?

1 个答案:

答案 0 :(得分:0)

试试这个,

Drawable d;
        try {
            InputStream is = (InputStream) new URL("http://trivetts.iconnectgroup.com/Uploads/Pictures/noname.jpg").getContent();
            d = Drawable.createFromStream(is, "src name");
            imageView.setBackgroundDrawable(d);
        } catch (Exception e) {

        }