Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Call onActivityResult() from dialog fragment

Tags:

android

When I was using a dialog fragment inside a activity then onActivityResult() is calling correctly but now i have changed activity to fragment due to my requirement . In that case images are not loading to imageview from camera and gallery.....

Code i was using to call in dialog fragment is...

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

Code used in fragment ........

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{                                                                                // Load the images from gallery and camera
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
        Uri selectedImage = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };

        Cursor cursor = getActivity().getContentResolver().query(selectedImage,
                filePathColumn, null, null, null);
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();

        ImageView imageView = (ImageView) getActivity().findViewById(R.id.icon);
        imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));

    }
    else if (requestCode == TAKE_REQUEST && resultCode == Activity.RESULT_OK) {
        pic = (Bitmap) data.getExtras().get("data");
        icon.setImageBitmap(pic);

    }
}

Code used for fragment transaction is ....

 MyDialogFragment myDialogFragment = new MyDialogFragment();
            myDialogFragment.show(getActivity().getFragmentManager(), "DialogFragment");

Over all code of dialog fragment.........

 public class MyDialogFragment extends DialogFragment implements View.OnClickListener {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(DialogFragment.STYLE_NORMAL, R.style.MY_DIALOG);
    }

    @Override
    public void onStart() {
        super.onStart();
        Dialog d = getDialog();

        if (d!=null){
            int width = ViewGroup.LayoutParams.MATCH_PARENT;
            int height = ViewGroup.LayoutParams.MATCH_PARENT;
            d.getWindow().setLayout(width, height);
        }
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.my_fragment, container, false);

        ImageButton FAB=(ImageButton)root.findViewById(R.id.imagesave);
        FAB.setOnClickListener(this);

        LinearLayout linearbutton=(LinearLayout)root.findViewById(R.id.linearbutton);

        LinearLayout linearLayout=(LinearLayout)root.findViewById(R.id.linear);
        linearLayout.setOnClickListener(this);

        ImageButton text=(ImageButton)root.findViewById(R.id.imageText);
        text.setOnClickListener(this);

        ImageButton pencil=(ImageButton)root.findViewById(R.id.imagePencil);
        pencil.setOnClickListener(this);

        ImageButton gallery=(ImageButton)root.findViewById(R.id.imageGallery);
        gallery.setOnClickListener(this);

        ImageButton camera=(ImageButton)root.findViewById(R.id.imageCamera);
        camera.setOnClickListener(this);

        return root;
    }

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.imagesave: {
                getDialog().dismiss();
                pDialog = new ProgressDialog(getActivity());
                pDialog.setTitle("Saving");
                pDialog.setMessage("please wait..............");
                pDialog.setCancelable(false);
                pDialog.show();

                FAB.setVisibility(View.INVISIBLE);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        pDialog.dismiss();
                        FAB.setVisibility(View.VISIBLE);
                       //Toast.makeText(getActivity(), "File saved successfully", Toast.LENGTH_SHORT).show();
                    }
                }, 2000);


                radioGroup.setVisibility(View.INVISIBLE);
                linearLayout.setVisibility(View.INVISIBLE);
                imagesize.setVisibility(View.INVISIBLE);
                clear.setVisibility(View.INVISIBLE);

                RelativeLayout content = (RelativeLayout) getActivity().findViewById(R.id.relative);
                content.setDrawingCacheEnabled(true);
                Bitmap bitmap = content.getDrawingCache();

                File myDir = new File("/sdcard/MyCollection");
                myDir.mkdirs();
                Random generator = new Random();
                int n = 10000;
                n = generator.nextInt(n);
                String fname = "Image-" + n + ".jpg";
                File file = new File(myDir, fname);
                if (file.exists()) file.delete();
                FileOutputStream outStream;
                try {
                    outStream = new FileOutputStream(file);
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
                    outStream.flush();
                    outStream.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                i = 0;
                break;
            }
            case R.id.linear: {
                getDialog().dismiss();
                break;
            }
            case R.id.imageText:
            {
                editText.setVisibility(View.VISIBLE);
                relativeLayout.setVisibility(View.INVISIBLE);
                imagesize.setVisibility(View.INVISIBLE);
                radioGroup.setVisibility(View.VISIBLE);
                clear.setVisibility(View.INVISIBLE);
                linearLayout.setVisibility(View.VISIBLE);
                InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
                Toast.makeText(getActivity(), "You have selected text ", Toast.LENGTH_SHORT).show();
                getDialog().dismiss();
                break;
            }

            case R.id.imagePencil: {
                getDialog().dismiss();

                clear.setVisibility(View.VISIBLE);
                relativeLayout.setVisibility(View.VISIBLE);
                imagesize.setVisibility(View.INVISIBLE);
                radioGroup.setVisibility(View.INVISIBLE);
                linearLayout.setVisibility(View.INVISIBLE);
                Toast.makeText(getActivity(),"You have selected pencil ",Toast.LENGTH_SHORT).show();
                i=0;
                break;
            }

            case R.id.imageGallery: {
                getDialog().dismiss();
                clear.setVisibility(View.INVISIBLE);
                relativeLayout.setVisibility(View.INVISIBLE);
                radioGroup.setVisibility(View.INVISIBLE);
                linearLayout.setVisibility(View.INVISIBLE);
                imagesize.setVisibility(View.VISIBLE);

                final Fragment callingFragment = getActivity().getFragmentManager().findFragmentById();
                Intent in = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                callingFragment.startActivityForResult(in, RESULT_LOAD_IMAGE);



                Toast.makeText(getActivity(), "You have selected gallery", Toast.LENGTH_SHORT).show();

                break;
            }

            case R.id.imageCamera: {
                getDialog().dismiss();
                relativeLayout.setVisibility(View.INVISIBLE);
                clear.setVisibility(View.INVISIBLE);
                radioGroup.setVisibility(View.INVISIBLE);
                linearLayout.setVisibility(View.INVISIBLE);
                imagesize.setVisibility(View.VISIBLE);
                startActivityForResult(new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE), TAKE_REQUEST);
                Toast.makeText(getActivity(), "You have selected camera", Toast.LENGTH_SHORT).show();
                break;
            }
        }
    }

}
like image 904
Soni Kumar Avatar asked Jan 08 '23 10:01

Soni Kumar


2 Answers

You need to call the activity from your fragment. Change your call to:

Intent in = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
yourFragment.startActivityForResult(in, RESULT_LOAD_IMAGE);

UPDATE:

In your dialog fragment write something like this:

final Fragment callingFragment = getActivity().getFragmentManager().findFragmentById();
Intent in = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
callingFragment.startActivityForResult(in, RESULT_LOAD_IMAGE);

Depending on your setup you may need to getSupportFragmentManager() and/or method findFragmentByTag(). It depends on how and where you added your fragment.

UPDATE 2:

final Fragment homeFragment = (HomeFragment)getActivity().getFragmentManager().findFragmentById(R.id.containerView);
Intent in = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
homeFragment.startActivityForResult(in, RESULT_LOAD_IMAGE);
like image 124
Thomas R. Avatar answered Feb 01 '23 13:02

Thomas R.


If the parent activity is also overriding onActivityResult then all calls to startActivityForResult will return to the parent activity. Now, to pass that call down to all fragments in the activity is by calling the base class' implementation.

In other words, if your activity (and its fragments) need onActivityResult all you need to do is call the base activity onActivityResult

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {

    //this makes sure the child fragments receive this event
    super.onActivityResult(requestCode, resultCode, data);
    ...

}
like image 24
Leo Avatar answered Feb 01 '23 14:02

Leo