androidandroid-intentonactivityresult

App closed when pressing back button from activity results intent


StartActivityForResults is deprecated. So I'm using new using new getting result from activity method to select PDF files. All working fine but if intent starts from my app to select file and if back button pressed from that intent, app closes.

ActivityResultLauncher<String> mGetContent = registerForActivityResult(new GetContent(),
    new ActivityResultCallback<Uri>() {
        @Override
        public void onActivityResult(Uri uri) {
            // Handle the returned Uri
        }
});

@Override
public void onCreate(@Nullable savedInstanceState: Bundle) {
    // ...

    Button selectButton = findViewById(R.id.select_button);

    selectButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            // Pass in the mime type you'd like to allow the user to select
            // as the input
            mGetContent.launch("application/pdf");
        }
    });
}

Any help please...


Solution

  • After a lot of struggle I found that if we press back button with out selecting any file the activity results will returns null. So we should check if activity results not equal to null and then do some operations.

    ActivityResultLauncher<String> mGetContent = registerForActivityResult(new GetContent(),
        new ActivityResultCallback<Uri>() {
            @Override
            public void onActivityResult(Uri uri) {
               if(uri!=null){
                // Handle the returned Uri
               }
            }
    });