【发布时间】:2017-01-16 18:16:27
【问题描述】:
我有一个主 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_QuestionsFragment? -
调用fragment的Activity.class里面。
public void openQuestion { adding Fragment_Questions }。 openQuestion 在 xml-layout 中被onClick="openQuestion"调用
标签: java android android-studio android-fragments