我有一个主 Activity.class ,通过ViewPager
运行片段(不是FragmentActivity)。我在片段中有一个带有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
答案 0 :(得分:1)
由于您已说Fragment_Questions
已添加到ViewPager
,请使用添加的Fragment_Questions
对象的引用来调用updateAdapter()。
在下面给出的代码中,您只是创建一个对象,但从不将其添加到viewpager。因此,永远不会调用onCreateView
方法,这会导致NullPointerException
。