我有一个主要的Activity.class通过ViewPager运行一个Fragment(不是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

最佳答案

由于您说Fragment_Questions已经添加到ViewPager,所以请使用添加的Fragment_Questions对象的引用来调用updateAdapter()。

在下面给出的代码中,您只是在创建一个对象,而从未将其添加到viewpager中。因此,永远不会调用onCreateView方法,从而导致NullPointerException

10-08 13:48
查看更多