imageView setImageBitmap()|空指针异常

时间:2018-01-25 14:16:13

标签: java android

我尝试使用Bitmap和ImageView下载并显示图像。我使用AsyncTask来获取url参数,但我总是得到一个

我尝试使用Bitmap和ImageView下载并显示图像。我使用AsyncTask来获取url参数,但我总是得到一个

java.lang.NullPointerException:尝试调用虚方法' void android.widget.ImageView.setImageBitmap(android.graphics.Bitmap)'在空对象引用上

代码:

public class MainActivity extends AppCompatActivity {

 ImageView imageView;

 public void images(View view)
 {

     ImageDownloader task=new ImageDownloader();
     Bitmap myImage;
     try
     {
         myImage=task.execute("https://upload.wikimedia.org/wikipedia/en/a/aa/Bart_Simpson_200px.png").get();

         imageView.setImageBitmap(myImage);     //Here is the part where i am
                                                //Getting exception
     }
     catch (InterruptedException e)
     {
         e.printStackTrace();
     }
     catch (ExecutionException e)
     {
         e.printStackTrace();
     }
 }



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    imageView=(ImageView)findViewById(R.id.myimg);  //imageView

    setContentView(R.layout.activity_main);

}



public class ImageDownloader extends AsyncTask<String,Void,Bitmap>{
    @Override
    protected Bitmap doInBackground(String... urls)
    {
        try {
            URL url=new URL(urls[0]);
            HttpsURLConnection connection=(HttpsURLConnection)url.openConnection();
            connection.connect();
            InputStream inputStream=connection.getInputStream();
            Bitmap bitmap= BitmapFactory.decodeStream(inputStream);
            return bitmap;


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

2 个答案:

答案 0 :(得分:4)

像这样改变行的顺序

imageView=(ImageView)findViewById(R.id.myimg);  //imageView

    setContentView(R.layout.activity_main);

 setContentView(R.layout.activity_main);
 imageView=(ImageView)findViewById(R.id.myimg);  //imageView

首先,您需要在找到imageview

后设置contentview

答案 1 :(得分:1)

因为您在加载视图之前尝试从视图中获取图像,所以更改顺序首先加载视图然后获取图像

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    imageView=(ImageView)findViewById(R.id.myimg);  //imageView
}