1

I have an activity that contains two fragments. I would like to pass data (an ArrayAdapter and an ArrayList) between the two fragments. User operations in Fragment 1 modifies both datatypes, which then need to be passed onto Fragment 2. Similarly, user operations in Fragement 2 also modify the two datatypes, which then need to be passed back to Fragment 1.

Can you please guide on the most elegant way to do it? I have been looking into parcelable and interface. Since, I do not have much experience with Java (let alone android) I was not able to discern the limitations of two approach.

user1124702
  • 1,015
  • 4
  • 12
  • 22

2 Answers2

0

I'd suggest holding a reference to your data object in each fragment (as I'm sure you are) and do something like the following:

public void onResume()
{
    mDataObject = getFragmentManager.getFragmentByTag("Fragment1").getDataObject1();
    super.onResume();
}

you can run this in Frag 1 and Frag 2 and it should update the model. If you have sub objects you will need to compare them and determine if the sub-objects are different in a function something like this.

public void determineIfDifferent(DataObject mData1) 
{
    Field mData1Fields[] = mData1.getClass().getFields();
    Field mData2Fields[] = mData2.getClass().getFields();

    for (int i = 0; i < mData1Fields.length; i++)
    {           
        try 
        {
            if (mDataFields[i].get(mData) != null && tempFields[i].get(PS)!= null)
            {
                String mDataValue =  mDataFields[i].get(mData).toString().trim();
                String tempValue =  tempFields[i].get(PS).toString().trim();

                if (!mDataValue.equals(tempValue))
                {   
                    differenceList.add(tempValue);
                }
            }
        }
        catch (IllegalArgumentException e) 
        {
            Logger.logStackTrace(getClass().getSimpleName(), e);
        }
        catch (IllegalAccessException e) 
        {
            Logger.logStackTrace(getClass().getSimpleName(), e);
        }
    }
}

This obviously can be modified if the type is not a String - this is just what I had at hand

chris-tulip
  • 1,840
  • 1
  • 15
  • 22
  • Thank you for the responses. I was able to accomplish passing the data by holding an object (as suggested in answer 1) in the activity class, and using getters and setters to make changes when the data from fragments needs to be passed. Another important aspect that I learned through other questions is that the getActivity() always needs to be type cast to the activity class name. The reason for this, according to the documentation, is that the many activities can have the same fragment class as a subactivity. – user1124702 Dec 26 '12 at 15:31
-1

You can put them into Intent.putExtra() and vice versa

Festus Tamakloe
  • 11,231
  • 9
  • 53
  • 65