H.fate H.fate - 2 months ago 6
Android Question

If i do not choose any picture and click back button, it crashed

Error message :

FATAL EXCEPTION: main
Process: com.example.keepair.myapplication, PID: 31796
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=66536, result=0, data=null} to activity {com.example.keepair.myapplication/com.example.keepair.myapplication.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.net.Uri android.content.Intent.getData()' on a null object reference


CODE :

mGetImageFromGalleryButton = (Button) view.findViewById(R.id.btn_getgallery);
mGetImageFromGalleryButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(ActivityCompat.checkSelfPermission(getActivity(),
Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
{
requestPermissions(
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
2000);
}
else {
startGallery();
}
}
});

private void startGallery() {
Intent cameraIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
cameraIntent.setType("image/*");
if (cameraIntent.resolveActivity(getActivity().getPackageManager()) != null) {
startActivityForResult(cameraIntent, 1000);
}
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == Activity.RESULT_OK) {
if(requestCode == 1000){
Uri returnUri = data.getData();
Bitmap bitmapImage = null;
try {
bitmapImage = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), returnUri);
} catch (IOException e) {
e.printStackTrace();
}
mImageview.setImageBitmap(bitmapImage);
}
returnUri = data.getData();
Glide.with(this)
.load(returnUri)
.override(1280, 1280)
.centerCrop()
.crossFade()
.into(mImageview);
}
else { #What is good for this space? }
}


My code is doing that if user click
mGetImageFromGalleryButton
in
GalleryFragment
, user would can go gallery and choose one picture, and then back to
GalleryFragment
with that picture's uri.

Question :
If a user click
mGetImageFromGalleryButton
and so go to gallery, but do not choose any picture and click android back button, the
Error message
i said above is happened. So, i think i have to modify if clause on
public void onActivityResult
. If what i think is right, What is good for
else { #What is good for this space? }
Would you help me?

Answer

The data is null when you do not select any image. That is why it is giving the error. Put a condition around your code if your data is not null.

E.g

if(data != null){

   //Proceed with your image crop etc

}