Search code examples
javaandroidandroid-fragmentsandroid-listviewnotifydatasetchanged

Get adapter from OnActivityCreate()


I am trying to call notifyDataSetChanged() on an adapter in a Fragment, from the MainActivity, in order to refresh the view/list after changing data. I create the adapter inside OnActivityCreate(), so I'm having trouble finding out how I can get the adapter, so that I can create a method to call that will have adapter.notifyDataSetChanged()

Fragment

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    String[] names = new String[] { "name1", "name1", "name1" };
    String[] values = new String[] { "value1", "value2", "value3" };
    MyArrayAdapter adapter = new MyArrayAdapter(getActivity(), names, values);
    setListAdapter(adapter);
}

I have tried creating a method in the Fragment and passing adapter to it but I'm not able to call that from the Main Activity. Also getListAdapter() isn't letting me call notifyDataSetChanged(). Very confused here, thank you!


Solution

  • Just make it visible for the entire Activity.

    ... MyClass {
    
        private MyArrayAdapter adapter;
    
        @Override
        public void onActivityCreated(Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);
    
            String[] names = new String[] { "name1", "name1", "name1" };
            String[] values = new String[] { "value1", "value2", "value3" };
            adapter = new MyArrayAdapter(getActivity(), names, values);
           setListAdapter(adapter);
        }
    
        // Another method
        private void myMethod() {
              adapter.notifyDataSetChanged();
        }
    }