app crashes when going back from gallery without selecting any image

前端 未结 3 1298
迷失自我
迷失自我 2021-01-29 09:39

when ever i am not selecting any image after opening the gallery and goin back my app crashes. plz help me out guys. this is a program to upload image to server selecting from a

相关标签:
3条回答
  • 2021-01-29 09:47

    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.

    0 讨论(0)
  • 2021-01-29 10:02

    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;
    
    0 讨论(0)
  • 2021-01-29 10:03

    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

    0 讨论(0)
提交回复
热议问题