I am working on a project where I have to pass data between fragments. All the data is provided from my DatabaseHandler class
(SQLiteOpenHelper). I\'m writing t
I think you are facing a different problem.
You need to create the following components:
I'll outline a super simplified version.
Interface: This is simple:
public interface DataChangeListener {
void onDataChanged();
}
List Of Listeners: This is easy too… in your Controllers/Activities/Singletons or anywhere you need to perform actions and notify listeners…
protected List<DataChangeListener> mListeners = new ArrayList<DataChangeListener>();
public void addDataChangeListener(DataChangeListener listener) {
if (listener != null && !mListeners.contains(listener)) {
mListeners.add(listener);
}
}
public void removeDataChangeListener(DataChangeListener listener) {
if (listener != null) {
mListeners.remove(listener);
}
}
Then your fragments… (for example)
public class YourFragment extends Fragment implements DataChangeListener {
private SomeControllerForExample mController;
@Override
public void onPause() {
super.onPause();
mController.removeDataChangeListener(this);
}
@Override
public void onResume() {
super.onResume();
mController.addDataChangeListener(this);
}
}
So far, you register when you are resumed and remove when you're no longer visible.
You also need to implement the method…
@Override
public void onDataSetChanged() {
// DO WHATEVER YOU NEED TO DO
}
And finally, have a notify method in your controller (the same one which had the list)
private void notifyListeners(){
for (DataChangeListener listener : mListeners) {
if (listener != null) {
listener.onDataSetChanged();
}
}
}
This pattern applies to anything, it's a nice and simple way to have your UI notified that you have retrieved new data, that an adapter must be notified, etc.
Rethink your problem using something like this and things will be a lot easier.
Found a solution for now. Instead of communicating with the child fragment. I ended up reinstantiating the ViewPager every time an item was selected in the GridView (calls changeObj in infoFrag). I guess I should have used different keywords earlier to find the solution! :/ Replacing a fragment from ViewPager android