Bobby_th Bobby_th - 10 months ago 51
Android Question

Android Fragment waiting on another Fragment's data

I have question about fragments updating values to each other.

I have a fragment called

UserFragment
and another called
CarsFragment
. UserFragment gets the user data and the carFragment gets multiple cars for the user owns. I then need to save this.

So, first, in the userFragment, I will have user details. Then, before I want to save the details, I will need to know if the car details has been populated/provided before saving the user data as a whole. Once provided, I can save it.

public class UserFragemnt extends Fragment {


private EditText mUserName;
private EditText mUserOccupation;
private String [] muserCars = null;

...//onCreate
mUserName= (EditText) view.findViewById(R.id.UserName)
mUserOccupation= (EditText) view.findViewById(R.id.UserOccupation)

if (userCar != null){ //so here i want to be sure the data is set by the carFragment
//call saveUserdata()
}

//this function gets called by the main activity
public void getUserCarsString [] userCars){
muserCars = userCars;
}
}


So the question is, What is the best way for the carFrament to get me/set the data, so that when I go to save it, I have the data? So one thing to note in this question is, userFragment needs to wait on the data before saving.

I have read about having an interface, then defining it in the main activity. I did it as such with a conditional check to see if the car details are updated. I don't think this is the best way. I followed this example: http://developer.android.com/training/basics/fragments/communicating.html

Also briefly read about Binding data variable:http://developer.android.com/tools/data-binding/guide.html

Thanks

Answer

When attaching your Fragments to an Activity make sure to assign them their own unique tags.

getSupportFragmentManager()
  .beginTransaction()
  .add(R.id.content, new CarsFragment(), "CARS")
  .commit();

Once you have them you can reference one Fragment from the other using:

CarsFragment cars = (CarsFragment) getFragmentManager().findFragmentByTag("CARS");

You can now expose some additional method in your CarsFragment that will return any information you need inside the UserFragment - like getSelectedUserCar(). You can use a result of that method later on to decide whether you want to proceed with saving user's data.