Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I update ListView in another Fragment?

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.

like image 700
Guy Avatar asked Dec 01 '25 07:12

Guy


1 Answers

I am assuming that function populateListView() is a function of the Fragment containing the ListView. You are calling populateListView() on every call to onPageSelected. Should you not check what is the position that is being selected. Anyway the populateListView() method should be a public method of the Fragment containing ListView. And You Can Instantiate The Fragment from the Viewpager adapter in the Activity and than call this method. In That way the listView should not be null.

@Override
public void onPageSelected(int position) {
ListViewFragment frag=(ListViewFragment)adapter.instantiateItem(viewPager, 1);
//here adapter is the ViewPager Adapter and you must supply the viewpager that    contains 
//the fragments and also the position of the fragment to instantiate. 
//For example 0 or 1 etc.
frag.populateListView(getApplicationContext());
aBar.setSelectedNavigationItem(position);
}
like image 65
mkhan Avatar answered Dec 03 '25 22:12

mkhan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!