I'm writing a game where every player has his own tab. Every Tab is an instance from PlaceholderFragment. I thought it would be easy to implement the dynamic count of tabs and fragments but now I don't really know how to get the input data from each instance to the ParentActivity. Maybe I should mention that I want to work with java 7 (SDK version min < 24)
I'm using the interface right know, but the problem is, that the user needs to press the menu item "save data" in the Activity to save the data, but the interface is defined in the fragment.
It is important to me that I firstly collect the data from each fragment before saving it becuase afterwards I want to transform the given data lists to a string and save this string in the database (otherwise I would not save a whole game but just a player).
I know that i could define more columns in the database but i have a dynamic number of player and rounds per player.
convert Array to String:
private void mergeAll(ArrayList<ArrayList<Integer>> list) {
ArrayList<String> wholeList = new ArrayList<>();
for(ArrayList<Integer> partList : list) {
for(int i = 0; i < partList.size(); i++) {
wholeList.add(partList.get(i).toString());
}
}
StringBuilder sb = new StringBuilder();
for(String s : wholeList) {
sb.append(s);
sb.append("\t");
}
playerAsString = sb.toString();
}
Fragment Interface
public static PlaceholderFragment newInstance(int index) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle bundle = new Bundle();
bundle.putInt("player", index);
fragment.setArguments(bundle);
return fragment;
}
public interface FragmentToActivity {
void communicate(String data);
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
try {
mCallback = (FragmentToActivity) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString()
+ " must implement FragmentToActivity");
}
}
@Override
public void onDetach() {
mCallback = null;
super.onDetach();
}
private void sendData(String comm)
{
mCallback.communicate(comm);
}
Activity:
@Override
public void communicate(String data) {
Log.i("got it", data);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_saveData:
//here i want to collect the strings from each fragment and save it to the database
return true;
...
}
return super.onOptionsItemSelected(item);
}
Is there any other way? As far as I know PlaceholderFragments doesn't have fragment tags or ids so I just can loop and get the String i need.