-2

I'm trying to download and show an image with Bitmap and ImageView. I'm using an AsyncTask which takes url arguments but I always get a

I'm trying to download and show an image with Bitmap and ImageView. I'm using an AsyncTask which takes url arguments but I always get a

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageBitmap(android.graphics.Bitmap)' on a null object reference

Code:

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;
    }
}
}
Aruj Sharma
  • 9
  • 1
  • 4

2 Answers2

4

Change sequence of line like this

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

    setContentView(R.layout.activity_main);

To

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

First you need to set contentview after find imageview

Munir
  • 2,548
  • 1
  • 11
  • 20
1

that because you trying to get the image from the view before you load the view , change the order load the view first and then get the Image

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    imageView=(ImageView)findViewById(R.id.myimg);  //imageView
}
Ali Faris
  • 17,754
  • 10
  • 45
  • 70