'I am trying to upload picture through my emulator in android using img picker but it shows error and I can't find out why, says null object reference

[error can be seen in image][1]

Here is my code I am trying to upload picture through my emulator in android using img picker but it shows error and I can't find out why, says null object reference

It show error on last line where I have made the code bolder.

package com.example.fyp;

public class HouseOwner extends Fragment {

TextView textView;
CircleImageView circleImageView;
ImageView imageView;
int SELECT_IMAGE_CODE=1;



@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

   

 /*   TextView textView = view.findViewById(R.id.search);
    textView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            startActivity(new Intent(startActivity();));*//*
        }
    });*/

    ImageView imageView = view.findViewById(R.id.pick);
    CircleImageView circleImageView = view.findViewById(R.id.add);
    circleImageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent,"title"),SELECT_IMAGE_CODE);
        }
    });


}

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

    if (requestCode==1){

        assert data != null;
        Uri uri= data.getData();
       **imageView.setImageURI(uri);** 

    }
}

}



Solution 1:[1]

The problem is image view is null at this line

imageView.setImageURI(uri);

Because you make image view as global variable but don't initialize it you make a new one in onViewCreated method .. you should change it on onViewCreated to be from

ImageView imageView = view.findViewById(R.id.pick);

to

imageView = view.findViewById(R.id.pick);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mohamed Saleh