2 lantianyiming lantianyiming 于 2013.06.14 13:38 提问

imageView获取图片空指针异常

通过URL获取图片时,然后在imageView中设置,结果系统给我报出空指针异常。

请高手帮忙解决一下,谢谢。

public class DetailsActivity extends Activity {
    ImageView thumbnail = (ImageView) findViewById(R.id.btnThumbnail);
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.detail);

        final Bundle extras = getIntent().getExtras();
        String img = extras.getString("Thumbnail");
        new DownloadImageTask((ImageView) findViewById(R.id.btnThumbnail))
                .execute("http://mysite.com/images/"
                        + img);

        }
    class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {

        public DownloadImageTask(ImageView bmImage) {
            thumbnail = bmImage;
        }

        protected Bitmap doInBackground(String... urls) {
            String urldisplay = urls[0];
            Log.e("URL",urldisplay);
            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;
        }

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

}

2个回答

Jave_
Jave_   2013.06.14 14:47
已采纳

写法没问题,只不过thumbnail不应该在外部去查找指向他的id
ImageView thumbnail = (ImageView) findViewById(R.id.btnThumbnail);
改成:
ImageView thumbnail即可

cj6585256
cj6585256   2013.06.14 14:04
private ImageView imageView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageView = (ImageView) findViewById(R.id.imageView);
        new DownloadImageTask()
        .execute("http://imgstatic.baidu.com/img/image/shouye/liushishi1.jpg");
    }

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

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


        @Override
        protected Bitmap doInBackground(String... urls) {
             String urldisplay = urls[0];
                Log.e("URL",urldisplay);
                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;
        }

    }

这样写没发现什么问题,你那写法有问题

cj6585256
cj6585256 这样成员变量ImageView 就不为null了
4 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!