从Url设置RelativeLayout的背景

时间:2014-06-30 19:29:31

标签: android bitmap android-drawable android-relativelayout

我想从URL获取图片,并设置为RelativeLayout的背景。我使用AsyncTask并尝试从Drawable创建BitmapDrawable。但我得到一个NullPointerException似乎无法找出原因?

   class DownloadBackgroundTask extends AsyncTask<String, Void, Bitmap> {
            RelativeLayout bmImage;
            View vi;

            public DownloadBackgroundTask(RelativeLayout bmImage, View vi) {
                this.bmImage = bmImage;
                this.vi = vi;
            }

            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) {
                    e.printStackTrace();
                }
                return mIcon11;
            }

            protected void onPostExecute(Bitmap result) {
                if (result != null)
                {
                    // null pointer exception here
                    Drawable d = new BitmapDrawable(vi.getContext().getResources(), result); 

                    bmImage.setBackground(d);
                }
                else
                {
                    bmImage.setBackgroundResource(R.drawable.logo);
                }
            }
        }

onCreateView():

    RelativeLayout rl = (RelativeLayout) rootView.findViewById(R.id.RelativeLayout1);
                new DownloadBackgroundTask(rl, rootView).execute("http://pctechmag.com/wp-content/uploads/2012/10/fifa13_messi.jpg");

0 个答案:

没有答案