Null Pointer Exception when Drawing an image

天大地大妈咪最大 提交于 2019-12-12 01:58:56

问题


I am having a problem with setting an ImageView image to an image which has been fetched from a URL. Here is the method used to turn the URL into a Drawable object:

private Drawable LoadImage(String url){
            try
            {
                InputStream is = (InputStream) new URL(url).getContent();
                Drawable d = Drawable.createFromStream(is, "src");
                return d;
            }catch (Exception e) {
                System.out.println("Exc="+e);
                return null;
            }
    }

Here is the code to call the method:

Drawable drawable = LoadImage("www.myurl.com/image.jpg");
imageView.setImageDrawable(drawable); //here is where I think it goes wrong

It gives me a Null Pointer Exception but when I display the drawable.toString() variable in a text view I get something like this:

android.graphics.drawable.BitMapDrawable@43e5bb18

So it shows it's not returning null and fails when it tries to draw it. Am I missing something in the manifest or is there something wrong with my code?


回答1:


First of all... don't use System.out on Android. Use Log instead.

I assume your LoadImage function returns null.

Take a look at the documentation about what ddms and logcat is and than try to get some more information about what happens.



来源:https://stackoverflow.com/questions/4417552/null-pointer-exception-when-drawing-an-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!