gpt4 book ai didi

java - 访问 Fragment 内的适配器

转载 作者:行者123 更新时间:2023-12-01 09:00:51 25 4
gpt4 key购买 nike

我有一个主要的Activity.class,它通过ViewPager运行一个Fragment(不是FragmentActivity)。我有一个自定义适配器, fragment 内带有 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 内):

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() .

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

关于java - 访问 Fragment 内的适配器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41682640/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com