Nazanin Nasab
Nazanin Nasab

Reputation: 625

Call method of a fragment from another fragment in different activities

I have a MainActivity hosted a fragment called FragmentOne and there is another Activity named DetailPagerActivity hosted another fragment called DetailFragment

i want to use a method from DetailFragment in FragmentOne .. how can i do this? i tried to use FragmentManager and so on, but failed

i want to call getDetailReport() from DeatilFragment in onSwiped > FragmentOne

here is my FragmentOne :

public class FragmentOne extends Fragment {

private RecyclerView mDetailRecyclerView;
private DetailAdapter mAdapter;
private boolean mNumberVisible;

private View view;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true); }

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

    mDetailRecyclerView = (RecyclerView)
            view.findViewById(R.id.detail_recycler_view);
        ..
        ..
    return view;
}

@Override
public void onResume() {
    super.onResume();
    updateUI();
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putBoolean(SAVED_NUMBER_VISIBLE, mNumberVisible);
}


private class DetailHolder extends RecyclerView.ViewHolder
        implements View.OnClickListener, View.OnLongClickListener {
    private TextView mTitleTextView;
    private Detail mDetail;
    private RatingBar mRatingBar;

    public DetailHolder(LayoutInflater inflater, ViewGroup parent) {
        super(inflater.inflate(R.layout.list_item_detail,
                parent, false));

        itemView.setOnClickListener(this);
        itemView.setOnLongClickListener(this);
        mTitleTextView = (TextView) itemView.findViewById(R.id.detail_title);
        mRatingBar = (RatingBar) itemView.findViewById(R.id.ratingBar);

    }

    public void bind(Detail detail) {
        mDetail = detail;
        mTitleTextView.setText(mDetail.getTitle());
        mRatingBar.setRating(mDetail.getRate()); }

    @Override
    public void onClick(View view) {
        Intent intent = DetailPagerActivity.newIntent(getActivity(),
                mDetail.getId());
        startActivity(intent); }

        return true;
    }
}


private class DetailAdapter extends RecyclerView.Adapter<DetailHolder> {
    private List<Detail> mDetails;

    public DetailAdapter(List<Detail> details) {
        mDetails = details;
    }

    @Override
    public DetailHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater layoutInflater =
                LayoutInflater.from(getActivity());

        return new DetailHolder(layoutInflater, parent);
    }

    @Override
    public void onBindViewHolder(DetailHolder holder, int position) {
        Detail detail = mDetails.get(position);
        holder.bind(detail);
    }

    @Override
    public int getItemCount() {
        return mDetails.size();
    }

    public void setDetails(List<Detail> details) {
        mDetails = details;


        ////////////////////////////////////////////////////////////////////////////////////////////////////////
        ItemTouchHelper.SimpleCallback simpleCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) {
            private Detail mDetail;

            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                return false;
            }

            @Override
            public void onSwiped(final RecyclerView.ViewHolder viewHolder, int direction) {
                final int position = viewHolder.getAdapterPosition(); //get position which is swipe

                    if (direction == ItemTouchHelper.LEFT) {    //if swipe left

                        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); //alert for confirm to delete
                        builder.setMessage("Are you sure to delete?");    //set message

                        builder.setPositiveButton("REMOVE", new DialogInterface.OnClickListener() { //when click on DELETE
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                                Intent i = new Intent(Intent.ACTION_SEND);
                                i.setType("text/plain");
                                i.putExtra(Intent.EXTRA_TEXT, getDetailReport());
                                i.putExtra(Intent.EXTRA_SUBJECT,
                                        getString(R.string.detail_report_subject));
                                i = Intent.createChooser(i, getString(R.string.send_report));
                                startActivity(i);

                                //////////////////////////////////////////////////////
//                                mAdapter.notifyItemRemoved(position);    //item removed from recylcerview
//                                DetailLab.get(getActivity()).deleteDetail(mDetail);
//                                updateUI();
//                                updateNumbers();
                                dialog.dismiss();
//                                return;
                            }
                        }).setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {  //not removing items if cancel is done
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                        builder.show();  //show alert dialog
                    }
                }
            };
            ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleCallback);
            itemTouchHelper.attachToRecyclerView(mDetailRecyclerView); //set swipe to recylcerview

        }
    }
}

and this is my DetailFargment:

public class DetailFragment extends Fragment {

private static final String ARG_DETAIL_ID = "detail_id";
private static final String DIALOG_DATE = "DialogDate";
private static final String DIALOG_PHOTO = "DialogPhoto";

private static final int REQUEST_DATE = 0;
private static final int REQUEST_PHOTO = 2;

..
..

public static DetailFragment newInstance (UUID detailId) {
    Bundle args = new Bundle();
    args.putSerializable(ARG_DETAIL_ID, detailId);

    DetailFragment fragment = new DetailFragment();
    fragment.setArguments(args);
    return fragment;
}

@Override
public void onCreate (Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);

    UUID detailId = (UUID) getArguments().getSerializable(ARG_DETAIL_ID);
    mDetail = DetailLab.get(getActivity()).getDetail(detailId);

    mPhotoFile = DetailLab.get(getActivity()).getPhotoFile(mDetail);
}

@Override
public void onPause() {
    super.onPause();

    DetailLab.get(getActivity()).updateDetail(mDetail);
}

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


     ..
     ..

    /////////////////////////// Report Button
    mReportButton = (Button) v.findViewById(R.id.detail_report);
    mReportButton.setOnClickListener(new View.OnClickListener() {
        public void onClick (View v) {

            Intent i = new Intent(Intent.ACTION_SEND);
            i.setType("text/plain");
            i.putExtra(Intent.EXTRA_TEXT, getDetailReport());
            i.putExtra(Intent.EXTRA_SUBJECT,
                    getString(R.string.detail_report_subject));
            i = Intent.createChooser(i, getString(R.string.send_report));
            startActivity(i);
        }
    });
..
..
    return v;
}

@Override
public void onResume() {
    super.onResume();
}

//////////////////////////////////// REPORT
private String getDetailReport() {
    String dateFormat = "EEE, MMM dd";
    String dateString = DateFormat.format(
            dateFormat, mDetail.getDate()).toString();

    String rateString = null;

    String report = getString(R.string.detail_report,
            mDetail.getTitle(), dateString,
            rateString, rateString
            );

    return report;
}
..
..}

Upvotes: 1

Views: 1171

Answers (1)

jt-gilkeson
jt-gilkeson

Reputation: 2721

You should move the getDetailsReport() out of the fragment and into some sort of data/utility class - then you can call it from both places. Data should be separate from the UI especially if you need to use it in more than one Activity/Fragment.

If you want to communicate between unrelated activities/fragments, the easiest way is to use a Broadcast / BroadcastReceiver. This is usually used to notify the other activity/fragment that something needs to be updated - as opposed to trying to query the other activity/fragment for data. Usually the fragment/activity will update if it receives a broadcast or be in a good state if it is initialized from scratch.

The issue you will run into when making activities/fragment rely on other activities/fragment is that the one not being shown can be cleaned up - so you can't rely on the action actually happening.

Upvotes: 2

Related Questions