Search code examples
androidnullpointerexceptionimageviewonactivityresult

Android: NullPointerException with ImageView.setImageBitmap


I am trying to display picture in ImageView after browsing it from phone within onActivityResult method. I declared my ImageView just before OnCreate method, after I find it by its ID on layout and finally want to display the selected image. But imgPreview is still grey and I can see message "private field ImageView is never assigned". Though I don't get reference problem while setting up my Bitmap on imgPreview within onActivityResult.

When I am trying to debug this app, while returning into main activity from the pickup activity I get java.lang.NullPointerException. If I declared

ImageView imgPreview = (ImageView) findViewById(R.id.imageView);

additionally within OnActivityResult I don't get error. Can u explain me why that happens? Should I find imgPreview each time within method when I want to use it? Whole code piece is below.

public class MainActivity extends AppCompatActivity implements TaskComplete {

private static final int BROWSE_PIC_REQUEST_CODE = 300;
private ImageView imgPreview;

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


public void onClick3(View view) {

    Intent i = new Intent(
            Intent.ACTION_PICK,
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

    startActivityForResult(i, BROWSE_PIC_REQUEST_CODE);

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == BROWSE_PIC_REQUEST_CODE && resultCode == RESULT_OK) {

        Uri selectedImage = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };

        Cursor cursor = getContentResolver().query(selectedImage,
                filePathColumn, null, null, null);
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();

        BitmapFactory.Options options = new BitmapFactory.Options();

        options.inSampleSize = 4;


        try {

                 imgPreview.setImageBitmap(BitmapFactory.decodeFile(picturePath,options));}
        catch (Exception e) {
            Log.e("test",e.toString());
        }

     else { some code };



}

Solution

  • ImageView imgPreview = (ImageView) findViewById(R.id.imageView);
    

    Here you are re-declaring imgPreview. Remove ImageView from the beginning of that line and it should work. So:

    imgPreview = (ImageView) findViewById(R.id.imageView);
    

    then it will correctly refer to the class level imgPreview.