I have an Activity which holds a ViewPager
with 2 Fragments. One fragment is for adding items to ListView
and another fragment is holding the ListView
.
I've been trying for almost 3 days now without any positive results. How do I update the other fragment's ListView
from the first fragment?
I'm trying to call the method that updates ListView
from the Activity that holds ViewPager
but it doesn't work.
Calling the method from ViewPager
activity :
@Override
public void onPageSelected(int position) {
library.populateListView(getApplicationContext());
aBar.setSelectedNavigationItem(position);
}
This is the populateListView
method:
public void populateListView(Context context){
CustomListViewAdapter customAdapter = new CustomListViewAdapter(getDatabaseArrayList(context), getActivity());
if (lView != null)
{
lView.setAdapter(customAdapter);
}
customAdapter.notifyDataSetChanged();
}
However this doesn't work because the lView variable (ListView) is null because the fragment isn't shown at the moment when this is being called.
I am assuming that function
populateListView()
is a function of the Fragment containing theListView
. You are callingpopulateListView()
on every call toonPageSelected
. Should you not check what is the position that is being selected. Anyway thepopulateListView()
method should be a public method of the Fragment containingListView
. And You Can Instantiate The Fragment from theViewpager
adapter in the Activity and than call this method. In That way thelistView
should not be null.To do this safely, you have to keep your
listview
data in a higher levelParent-Activity
not thefragments
. Make yourMainActivity
classsingleton
class by making the constructorprivate
and create agetInstance
method that return the only initialized instance of your `MainActivity.This will allow you to keep your data instance safe from being re-initialized or lost. Then, in
onResume
of your fragment re-set the data (get it from theMainActivity
) to yourlistview
adapter
and callnotifyDataSetChanged()
method from theadapter
instance.This will do the trick.
Understand Fragments
Please see this link. I have gone in great detail explaining the concept of fragments.
Pay particular attention to the definition of rootview:
In the above case I defined a button for an on click listener, but you can just as easily define a ListView along with its appropriate methods.
Alternate Solution
A second method could be using getView or getActivity (check the communicating with activity section).
For example:
Please read this post for additional information.
Good Luck.