onActivityResult not called in fragment android [d

2019-02-25 17:33发布

问题:

This question already has an answer here:

  • onActivityResult is not being called in Fragment 32 answers

This is my code to take picture from gallery.

public class FragmentLayout1 extends Fragment implements OnClickListener {

    View root;
    Context c;
    Button add_image;
    DialogAddImage image;
    RelativeLayout layout_image;
    String path;
    RunAnimations anima;


    public void setContext(Context c){
        this.c = c;
        Constants con = new Constants(c);   
    }

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        anima = new RunAnimations();
        image = new DialogAddImage((Activity) c);

        Bundle bun = new Bundle();
        path = bun.getString("path");

        root = inflater.inflate(R.layout.layout_1, container, false);
        add_image = (Button)root.findViewById(R.id.button2);
        add_image.setOnClickListener(this);

        layout_image = (RelativeLayout)root.findViewById(R.id.layout_image);

        if(!TextUtils.isEmpty(path)){
            Log.e("path", path);
             Drawable d = Drawable.createFromPath(path);
             layout_image.setBackground(d);
        }


        return root;


    }



    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        anima.loadAnimationView(c, R.anim.alpha_button, v);
        if(v == add_image){
            image.showDialog();
        }

    }


     //============= fungsi untuk menerima hasil pilihan user dalam kotak dialog ambil gambar=============
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.e("result", "Result");
        new ImageResult((Activity) c).resultOfImage(requestCode, resultCode, data, image.getUri(), false);
    }

in method on click , I've button add_image. add_image will show a dialog for user to take picture from camera or gallery And this is my dialog code

public class DialogAddImage{
    private Activity c;
    private Uri mImageCaptureUri;
    private Dialog dialog;
    AnimasiActivity aa;
    Button camera, galeri;

    public DialogAddImage(Activity c){
        this.c = c;

        aa = new AnimasiActivity(c);
        setDialog();
    }

    //untuk mendapatkan uri yang menyimpan informasi path file image
    public Uri getUri(){
        return mImageCaptureUri;
    }


    @SuppressWarnings("deprecation")
    private void setDialog(){       
        dialog = new Dialog(c);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);   
        dialog.setContentView(R.layout.dialog_add_image);           
        dialog.getWindow().setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(0));

        camera = (Button) dialog.findViewById(R.id.button1);
        galeri = (Button)dialog.findViewById(R.id.button2);

        //kalo user pilih dari kamera
        camera.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {           
                hideDialog();
                Intent intent    = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                String file_name = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date());
                File file = new File(Constants.path_image +file_name + ".jpg");
                mImageCaptureUri = Uri.fromFile(file);

                intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageCaptureUri);

                try {                        
                    intent.putExtra("return-data", true);
                    intent.putExtra("mImageCaptureUri", mImageCaptureUri);                            

                    aa.startForwardForResult(intent, Constants.PICK_FROM_CAMERA);
                } catch (Exception e) {
                    e.printStackTrace();   
                }  



            }
        });

        //kalo user pilih dari galery
        galeri.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View arg0) {                
                hideDialog();
                Intent intent = new Intent(); 
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);                   

                aa.startForwardForResult(intent, Constants.PICK_FROM_FILE);
            }

        });



    }

    public void showDialog(){

        dialog.show();
    }

    public void hideDialog(){
        dialog.dismiss();
    }


}

But when I've choose image from gallery , this image not showing in my fragment. And method onActivityResult never called, but why??? any solution , please

回答1:

Override onActivityResult in parent Activity i.e. parent of all fragment



回答2:

Make sure you call startActivityForResult() and not getActivity().startActivityForResult() from your fragment. refer onActivityResult is not being called in Fragment



回答3:

If you are overriding onActivityResult in your Activity then make sure you do call super.onActivityResult there too in order to propagate the result to your fragments.



回答4:

Also if you call startActivityForResult() from your fragment, then onActivityResult() will be called in your fragment. And if you call startActivityForResult() from your activity, then onActivityResult() will be called in your activity. Basically where you call startActivityForResult() is where onActivityResult() will be called.

Another thing, in Android the prefered way to create dialogs is to extend the DialogFragment class.



回答5:

Issue is very sensitive and little tricky the observation(fix) i have made for this as follows,

When u called Activity B from Activity A the source activity(A) instance should be in stack(memory) to invoke "onActivityResult" callback.

The issue explained with reason below,

Observation: From Material design back and NavUtils.navigateUpFromSameTask - the description of navigateUpFromSameTask as follows "Convenience method that is equivalent to calling navigateUpTo(sourceActivity, getParentActivityIntent (sourceActivity)). sourceActivity will be finished by this call"

remember sourceActivity (A) is removed from stack(memory) when used this method.

when there is no sourceActivity(A) no base instance(A) left to invoke "onActivityResult" callback.



回答6:

  1. You can simply override BaseActivity onActivityResult on fragment baseActivity.startActivityForResult.

  2. On BaseActivity add interface

    private OnBaseActivityResult baseActivityResult;

  3. On Fragment implements OnBaseActivityResult

Check my answer here



回答7:

I have a custom DialogFragment and I faced the same issue. No need to trigger it from the parent's method. You have to call startActivityForResult() and not getActivity().startActivityForResult() just like @umesh answered above.



回答8:

When you call startActivityForResult from a fragment, the result is sent back to your activity's onActivityResult. Instead use super.onactivityResult in your activity's onActivityResult and the result will instead be sent back to your fragment's onActivityResult. You can write your code here. Don't use getActivity.onactivityResult in your fragment's onActivityResultbecause it will refer to the activity's onActivityResult.