简体   繁体   中英

Android Fragment null pointer when fetching view

I have been hitting a wall with Fragments and triggering a view refresh when the adapter changes for a listview inside the fragment. Right now I have:

  • A main activity which holds the FragmentManager
  • The activity creates fragments based on position through the FragmentPagerAdapter.getItem method
  • A subsequent activity or button press causes the data behind one of the Fragments to change
  • The activity calls the refresh method on the custom Fragment class to trigger the data refresh
  • The refresh method fetches the ListView object in the fragment
    • This is where the Null exception occurs

The refresh method is below:

public void refresh() {
  groups = new Select()
    .from(Group.class)
    .execute();

  listView = (ListView)getActivity().findViewById(R.id.overview_container);
  // Never get here
  groupAdapter.clear();
  groupAdapter.setItems(groups);
  listView.invalidateViews();   
}

The setup is

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
  view = inflater.inflate(R.layout.fragment_overview, container, false);

  groups = new Select()
    .from(Group.class)
    .execute();

  listView = (ListView)view.findViewById(R.id.overview_container);
  listView.setAdapter(new GroupAdapter(view.getContext(), R.layout.time_view, groups));     
  return view;
}

Is there something fundamental I am missing here? Is there an easier pattern here like listeners that can work around this issue? I just can't seem to get the view to return anything but null - even if I store it.

I was fetching the Fragment via the FragmentManager and converting to a raw interface to run the interface method - this seems to have returned an unexpected version which wasn't necessarily the active Fragment thus causing the problems I was having.

Instead I have kept references myself to the generated Fragments so I can reference them at will.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM