使用AsyncTask将图像从url设置为ImageView

时间:2013-06-13 15:47:14

标签: android android-asynctask android-imageview android-image

我的网站上有一张图片,我想在我的ImageView上设置。我需要使用异步任务。我是这样做的。但 new getThumbnail().execute(stringThumbnail);正在向我提出错误getThumbnail cannot be resolved to a type。我在这里做错了什么?

final ImageView thumbnail = (ImageView) findViewById(R.id.btnThumbnail);
String stringThumbnail = "myImage.jpg";
new getThumbnail().execute(stringThumbnail);        

        class getThumbnail extends AsyncTask<String, Void, Void> {

            protected Void doInBackground(String... data) {
                String thumb = data[0];
                try {
                  Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL("http://mySite.com/images/" + thumb).getContent());

                } catch (MalformedURLException e) {
                  e.printStackTrace();
                } catch (IOException e) {
                  e.printStackTrace();
                }
                return null;
            }

            protected void onPostExecute(Bitmap img) {
                // TODO: check this.exception 
                // TODO: do something with the feed
                thumbnail.setImageBitmap(img); 
            }
         }

1 个答案:

答案 0 :(得分:2)

问题出在异步任务中,就像这样使用它

public class MainActivity extends Activity {

    private ImageView mThumbnail;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mThumbnail = (ImageView) findViewById(R.id.btnThumbnail);
        String stringThumbnail = "myImage.jpg";
        new getThumbnail().execute(stringThumbnail);

    }

    class getThumbnail extends AsyncTask<String, Void, Bitmap> {

        protected Bitmap doInBackground(String... data) {
            String thumb = data[0];
            Bitmap bitmap = null;
            try {
                Log.d("TEST", "do in background");
                bitmap = BitmapFactory
                        .decodeStream((InputStream) new URL(
                                "http://mySite.com/images/" + thumb)
                                .getContent());

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return bitmap;
        }

        protected void onPostExecute(Bitmap img) {
            Log.d("TEST", "post execute");
            mThumbnail.setImageBitmap(img);
        }
    }

}

还要确保btnThumbnail是imageView。前缀btn令人困惑,并且还声明了权限

<uses-permission android:name="android.permission.INTERNET"/>
manifest.xml中的