onActivityResult() not called when Activity started from Fragment

前端 未结 3 1548
北恋
北恋 2020-12-05 09:49

I have an issue with importing a picture from the Album in Android, because the onActivityResult() method is never called.

This is the code that I wrote

相关标签:
3条回答
  • 2020-12-05 10:30

    To have onActivityResult() called in the fragment, you should call the fragment's version of startActivityForResult(), not the activity's. So in your fragment's code, replace

    getActivity().startActivityForResult(galleryIntent, PICK_IMAGE);
    

    with

    startActivityForResult(galleryIntent, PICK_IMAGE);
    
    0 讨论(0)
  • 2020-12-05 10:47

    With this code:

    Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    getActivity().startActivityForResult(galleryIntent, PICK_IMAGE);
    

    The onActivityResult must be in the Activity that contains the Fragment. From there you can call any method of the fragment, not in the fragment.

    MyFragment myFragment = (MyFragment) getSupportFragmentManager().findFragmentById(R.id.fragment);
    myFragment .onCameraResult(requestCode, resultCode, intent);
    

    to do there whatever you want

    0 讨论(0)
  • 2020-12-05 10:50

    Try this Snippet :

        Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
        intent.setType("image/*");
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 1);
    
    
        @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
    
            case 1:
                if(requestCode == 1 && data != null && data.getData() != null){
                    Uri _uri = data.getData();
    
                    if (_uri != null) {
                        Cursor cursor = getContentResolver().query(_uri, new String[] { android.provider.MediaStore.Images.ImageColumns.DATA }, null, null, null);
                        cursor.moveToFirst();
                        final String imageFilePath = cursor.getString(0);
                        File photos= new File(imageFilePath);
                        imageView.setImageBitmap(bitmap);
                        cursor.close();
                    }
                }
                super.onActivityResult(requestCode, resultCode, data);
            }
        }   
    
    0 讨论(0)
提交回复
热议问题