app crashes when going back from gallery without selecting any image

◇◆丶佛笑我妖孽 提交于 2019-12-02 14:15:14

You can handle it this way:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 1 && resultCode == RESULT_OK && data != null) {
        //your code
    }
    else {
        //alert of "No image was selected"
    }
}

Don't perform any operation on data if its null. So it won't give a crash.

Hope it helps.

Add below line in your code. If the operation is cancelled, you will not get RESULT_OK

public void onActivityResult(int requestCode, int resultCode, Intent data) {

if (resultCode != RESULT_OK) 
      return;

Try this, add if(resultCode == RESULT_OK) :

 @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode == RESULT_OK){ //<-- Add this
        if (requestCode == 1 ) {
            //Bitmap photo = (Bitmap) data.getData().getPath(); 

            Uri selectedImageUri = data.getData();
            imagepath = getPath(selectedImageUri);
            Bitmap bitmap=BitmapFactory.decodeFile(imagepath);
            imageview.setImageBitmap(bitmap);
         //   messageText.setText("Uploading file path:" +imagepath);
        }
        }
    }

In your current code , even if the result code is not OK its executing data.getData() which is null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!