訪問適配器我有一個主Activity.class運行片段(不FragmentActivity)通過ViewPager
。我有一個自定義適配器與recyclerview列表中的片段。在Fragment外部和內部訪問適配器存在問題。所以:內片段
該代碼完全適用:
private List<MyQuestionList> theList;
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
recyclerView = (RecyclerView) theview.findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
theList = new ArrayList<>();
requestQueue = Volley.newRequestQueue(getContext());
adapter = new MyQuestionsAdapter(theList, getContext());
recyclerView.setAdapter(adapter);
updateAdapter(); // <-- ATTENTION PLEASE, I'VE CALLED THE FUNCTION INSIDE THE FRAGMENT
}
public void updateAdapter(){ // <-- METHOD IS PUBLIC
removeItem(0);
}
***** And there is located parser's method where items are fetching from server
and adding to recyclerview via adapter successfully.
But the code is too long, and anyway there is nothing interesting :) *****
private void removeItem(int item){
theList.remove(item);
adapter.notifyDataSetChanged();
}
但是,當我從主Activity.class調用相同的方法(updateAdapter)這樣的(不是在運行片段內):
Fragment_Questions frau = new Fragment_Questions();
frau.updateAdapter();
代碼不起作用。下面是日誌:
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.Object java.util.List.remove(int)' on a null object reference
在哪裏添加'Fragment_Questions'片段? –
在調用片段的Activity.class中。 'public void openQuestion {added Fragment_Questions}'。通過onClick =「openQuestion」'' – HEISENBERG