2

Please give me some suggestions how to pass object between fragment and activity.

In my project, there is one FragmentActivity to show and edit customer profile. Multiple tabs will be contained in this activity to show contact info, address... The customer info will be preload as one class in the activity. My question is how could I pass this object to each fragment or tab? Once updated, how could I pass back to activity?

Do I must to implement the Parcelable interface in my customer class to pass by bundle?

Each tab will be dynamic created, is possible to get the fragment instance to modify view directly? If yes, once tab switch, is fragment destroyed?

Thanks

Myron

Jose Kurian
  • 703
  • 7
  • 10
Myron
  • 21
  • 1
  • 1
  • 2
  • From personal experience, I would say re-grab the information from your database, as you might create an edit button on one tab that changes the database and forget to update local variables, creates inconsistencies. Personal opinion. – LuckyMe Jun 24 '13 at 16:09
  • Thanks for your suggestion. For my scenario, the profile would be saved only when the save button clicked in the activity. So, temporary save and re-grab from database would add lots of extra work. – Myron Jun 24 '13 at 17:18

2 Answers2

2

No doubt: best solution is to call an activity method from the fragment:

Here an example with a Bitmap Object.

In ACTIVITY:

define your method:

public Bitmap getMyBitmap() {
    return myBitmap;
}

In FRAGMENT:

1 - Define your activity

private Activity_Main myActivity;

2 - Link your activity

@Override
public void onAttach(Activity myActivity) {
    super.onAttach(myActivity);
    this.activity= (Activity_Main) myActivity;
}

3 - Call your method!

myActivity.getMyBitmap()

Quick and easy!

Alecs
  • 2,900
  • 1
  • 22
  • 25
  • This is not the best solution, it's inefficient, better to use an interface to avoid leaks and memory problems – Pontus Backlund Jul 08 '14 at 10:10
  • 1
    @PontusBacklund - Sorry, I didn't understand "it's inefficient". He is adding activity reference in fragment using onAttach(). If he removes that reference in onDettach() by simply myActivity=null; there will be no leaks. Also, in cases where user needs to have access other objects which will be modified by app based on current state, i feel this is best approach. Also this is what google developers also recommended. – Vipin Sharma Jan 02 '15 at 06:17
  • @VipinSharma can you point out any example or documentation that goodle developers actually recommended said approach? – user65721 Mar 19 '15 at 14:03
  • @user65721 Extremely sorry for late response. I checked code example given on http://developer.android.com/guide/components/fragments.html Creating event callbacks to the activity – Vipin Sharma Nov 15 '15 at 07:40
  • This is a poor design and it breaks one of the critical role of fragments: being reusable, by any kind of activities. – Simon Ninon May 03 '18 at 21:41
0

You need to know how interfaces work and how to set tags to a fragment as well as how you find a specific fragment by tag. You should read this...

http://developer.android.com/training/basics/fragments/communicating.html

To send objects to you fragments this are the basics. On the activity....

        // Create fragment and give it an argument for the selected article
        ArticleFragment newFragment = new ArticleFragment();
        Bundle args = new Bundle();
        args.putInt(ArticleFragment.ARG_POSITION, position);
        newFragment.setArguments(args);

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

        // Replace whatever is in the fragment_container view with this fragment,
        // and add the transaction to the back stack so the user can navigate back
        transaction.replace(R.id.fragment_container, newFragment);
        transaction.addToBackStack(null);

        // Commit the transaction
        transaction.commit();

On the fragment...

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

    ScrollView scroller = new ScrollView(getActivity());
    TextView text = new TextView(getActivity());
    int padding = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
            4, getActivity().getResources().getDisplayMetrics());
    text.setPadding(padding, padding, padding, padding);
    scroller.addView(text);
    text.setText(Shakespeare.DIALOGUE[getShownIndex()]);
    return scroller;
}

where getShownIndex is....

 public int getShownIndex() {
    return getArguments().getInt("index", 0);
}

If you wanna communicate from the fragment to the activity then you need interfaces.

jpardogo
  • 5,636
  • 2
  • 23
  • 27
  • Do I need to add "R.id.fragment_container" in my activity to get the instance of each dynamic created fragment? For the interface is ok, but how to pass objects between activity and fragment? – Myron Jun 24 '13 at 17:36
  • R.id.fragment_container is the id of the container of your fragment. It is used to be a FrameLayout on your activity layout. To pass custom objects is the same way but you have to Serialize or Parcelable, it is answered in here : http://stackoverflow.com/questions/10836525/passing-objects-in-to-fragments – jpardogo Jun 24 '13 at 18:32