0

I'm starting an Activity to pick a file and get the path from it. Therefore the "ActivivityResultLauncher" should be defined in onCreate() of MainActivity but I want it to define it in other non-activity classes, which I've already tried but I took null pointer exception error.

MainActivity Class

         public static ActivityResultLauncher<Intent> activityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                if(result.getResultCode() == Activity.RESULT_OK) {
                    if (result.getData() != null) {
                        String path = "/" + result.getData().getData().getPath().substring(result.getData().getData().getPath().indexOf(":") + 1);
                        //animHandler.openAttach();
                    }
                }
            }
        });
    }

PathHandler Class (a non-activity class)

    public void pathReceiver() {

        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        Uri uri = Uri.parse(String.valueOf(Environment.getExternalStorageDirectory()));
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setDataAndType(uri, "text/plain");
        MainActivity.activityResultLauncher.launch(intent);


        /* 
           I want to add the "public static ActivityResultLauncher..." definition into here.
        */
    }
LoreX
  • 11
  • 2
  • 1
    "I'm starting an Activity to pick a file and get the path from it" -- that's not a thing in Android, particularly the way that you are going about it. See [this](https://stackoverflow.com/questions/59123162/android-kotlin-getting-a-filenotfoundexception-with-filename-chosen-from-file-p) and [this](https://stackoverflow.com/questions/56308559/create-a-file-from-a-photo-uri-on-android) and [this](https://stackoverflow.com/questions/49221312/android-get-real-path-of-a-txt-file-selected-from-the-file-explorer), among others. – CommonsWare Dec 19 '22 at 22:17

0 Answers0