Android通过url设置ImageButton背景

时间:2013-04-24 17:35:19

标签: java android android-asynctask imagebutton

我正在尝试通过网址将背景图片添加到ImageButton。

我已经像这样修改了google android文档中的downloadimagetask。

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

        public DownloadImageButtonTask(ImageButton 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;
        }

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

我收到错误::引起:java.lang.NullPointerException:println需要一条消息

在这一行:: Log.e(“Error”,e.getMessage());

我将此asynctask称为

new DownloadImageButtonTask((ImageButton) findViewById(R.id.my_image_btn))
            .execute("any image url");

1 个答案:

答案 0 :(得分:1)

设置 尝试设置

if( e.getMessage()!=null)
{
Log.e("Error", e.getMessage());
e.printStackTrace();
}

或只是

String exception= (e.getMessage()!=null)?ex.getMessage():"Exception occured";
 Log.e("Error", exception);