0
package com.yashas.blogapp.Activities;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.yashas.blogapp.R;

public class RegisterActivity extends AppCompatActivity {


    ImageView ImgUserPhoto;
    static int PReqCode = 1;
    static int REQUESCODE = 1;
    Uri pickedimgUri;

//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        if (resultCode == RESULT_OK && resultCode == REQUESCODE && data != null){
//            pickedimgUri = data.getData();
//            ImgUserPhoto.setImageURI(pickedimgUri);

//        }
//    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_regster);


        //inu views
        ImgUserPhoto = findViewById(R.id.regUserPhoto) ;
        ImgUserPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Build.VERSION.SDK_INT >=22) {
                    checkAndRequestForPermission();
                }
                else{
                    openGallery();
                }
            }
        });
    }

    private void openGallery() {
        //TODO: Open Gallery
        ActivityResultLauncher<Intent> activityResultLauncher;
        activityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                if (result.getResultCode() == RESULT_OK && result.getData() != null){
                    pickedimgUri = result.getData().getData();
                    ImgUserPhoto.setImageURI(pickedimgUri);
                }
            }
        });
        Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
        galleryIntent.setType("image/*");
//        startActivityForResult(galleryIntent, REQUESCODE);
        activityResultLauncher.launch(galleryIntent);
    }

    private void checkAndRequestForPermission() {
        if (ContextCompat.checkSelfPermission(RegisterActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
            if (ActivityCompat.shouldShowRequestPermissionRationale(RegisterActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)){
                Toast.makeText(RegisterActivity.this, "Please Allow the Required Permissions", Toast.LENGTH_SHORT).show();
            }
            else{
                ActivityCompat.requestPermissions(RegisterActivity.this,
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},PReqCode);
            }
        }
        else
            openGallery();
    }
}

The above is my code and my app is crashing when I use the activity result launcher. Kindly help me out with this. I was using it on activity start earlier, but it was depracated, and now with this, my app is crashing. As soon as I click the image to open the file manager, it crashes. I am trying to resolve this error since morning but it is not working out. It would be great help if someone helps me out with this.

Error stacktrace:

2022-01-14 17:05:49.205 9664-9664/com.yashas.blogapp E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.yashas.blogapp, PID: 9664
    java.lang.IllegalStateException: LifecycleOwner com.yashas.blogapp.Activities.RegisterActivity@2166eff is attempting to register while current state is RESUMED. LifecycleOwners must call register before they are STARTED.
        at androidx.activity.result.ActivityResultRegistry.register(ActivityResultRegistry.java:123)
        at androidx.activity.ComponentActivity.registerForActivityResult(ComponentActivity.java:682)
        at androidx.activity.ComponentActivity.registerForActivityResult(ComponentActivity.java:691)
        at com.yashas.blogapp.Activities.RegisterActivity.openGallery(RegisterActivity.java:67)
        at com.yashas.blogapp.Activities.RegisterActivity.checkAndRequestForPermission(RegisterActivity.java:93)
        at com.yashas.blogapp.Activities.RegisterActivity.access$000(RegisterActivity.java:24)
        at com.yashas.blogapp.Activities.RegisterActivity$1.onClick(RegisterActivity.java:55)
        at android.view.View.performClick(View.java:7448)
        at android.view.View.performClickInternal(View.java:7425)
        at android.view.View.access$3600(View.java:810)
        at android.view.View$PerformClick.run(View.java:28305)
        at android.os.Handler.handleCallback(Handler.java:938)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)

The above is the logcat when the app crashes.

ouflak
  • 2,458
  • 10
  • 44
  • 49
Yashas
  • 23
  • 1
  • 3
  • Does this answer your question? [Unfortunately MyApp has stopped. How can I solve this?](https://stackoverflow.com/questions/23353173/unfortunately-myapp-has-stopped-how-can-i-solve-this) – a_local_nobody Jan 14 '22 at 11:31
  • 2
    app crashes - find stack trace - research stack trace - change code - problem solved :) – a_local_nobody Jan 14 '22 at 11:31
  • no it does not help I still do not know how to resolve the issue – Yashas Jan 14 '22 at 11:47
  • Move your `registerForActivityResult()` call to be a field initializer. See [this](https://gitlab.com/commonsguy/cw-jetpack-java/-/blob/master/ContentEditor/src/main/java/com/commonsware/jetpack/contenteditor/MainActivity.java#L43-75), for example. – CommonsWare Jan 14 '22 at 11:57

1 Answers1

-1

You are registering the result launcher each time openGallery is called. Instead do the following

package com.yashas.blogapp.Activities;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.yashas.blogapp.R;

public class RegisterActivity extends AppCompatActivity {

    ImageView ImgUserPhoto;
    static int PReqCode = 1;
    static int REQUESCODE = 1;
    Uri pickedimgUri;
    
    ActivityResultLauncher<Intent> activityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
        @Override
        public void onActivityResult(ActivityResult result) {
            if (result.getResultCode() == RESULT_OK && result.getData() != null){
                pickedimgUri = result.getData().getData();
                ImgUserPhoto.setImageURI(pickedimgUri);
            }
        }
    });

//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        if (resultCode == RESULT_OK && resultCode == REQUESCODE && data != null){
//            pickedimgUri = data.getData();
//            ImgUserPhoto.setImageURI(pickedimgUri);

//        }
//    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_regster);


        //inu views
        ImgUserPhoto = findViewById(R.id.regUserPhoto) ;
        ImgUserPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Build.VERSION.SDK_INT >=22) {
                    checkAndRequestForPermission();
                }
                else{
                    openGallery();
                }
            }
        });
    }

    private void openGallery() {
        //TODO: Open Gallery
        Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
        galleryIntent.setType("image/*");
//        startActivityForResult(galleryIntent, REQUESCODE);
        activityResultLauncher.launch(galleryIntent);
    }

    private void checkAndRequestForPermission() {
        if (ContextCompat.checkSelfPermission(RegisterActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
            if (ActivityCompat.shouldShowRequestPermissionRationale(RegisterActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)){
                Toast.makeText(RegisterActivity.this, "Please Allow the Required Permissions", Toast.LENGTH_SHORT).show();
            }
            else{
                ActivityCompat.requestPermissions(RegisterActivity.this,
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},PReqCode);
            }
        }
        else
            openGallery();
    }
}
LethalMaus
  • 798
  • 1
  • 8
  • 20