ViewPager2 的 Fragment 的 ArrayList 在我从 NavigationView 切换另一个片段后为 null。我该如何解决这个问题?

ArrayList of Fragment of ViewPager2 is null after I switched another fragment from NavigationView. How can I solve this problem?

提问人:Xoszagas 提问时间:5/18/2023 最后编辑:DinuxXoszagas 更新时间:5/19/2023 访问量:48

问:

我正在制作一个 Android 项目。我创建了一个如下:RecyclerViewViewPager2

  1. 屏幕截图 1

  2. 屏幕截图 2

我切换到 or .然后,我返回并单击按钮。我一点击按钮,应用程序就崩溃了。错误是 .GallerySlideshowHomeClear BoxnullPointerException

我的适配器代码:

public class MyAdapter extends FragmentStateAdapter {
    private ArrayList<Fragment> fragmentList = new ArrayList<>();

    public MyAdapter(@NonNull FragmentActivity fragmentActivity) {
        super(fragmentActivity);
    }

    public MyAdapter(@NonNull Fragment fragment) {
        super(fragment);
    }

    public MyAdapter(@NonNull FragmentManager fragmentManager, @NonNull Lifecycle lifecycle) {
        super(fragmentManager, lifecycle);
    }

    @NonNull
    @Override
    public Fragment createFragment(int position) {
        return fragmentList.get(position);
    }

    @Override
    public int getItemCount() {
        return fragmentList.size();
    }

    public void addFragment(Fragment fragment) {
        fragmentList.add(fragment);
    }
}

我的片段代码:

public class OneFragment extends Fragment {
    Button button;
    RecyclerView recyclerView;
    BoxAdapter adapter;
    private List<Box> boxList;
    private LinearLayout linearLayout;
    int t;

    public OneFragment(int k) {
        t = k;
        Log.d("QQQ", "OneFragment constructor called");
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view;
        view = inflater.inflate(R.layout.fragment_one, container, false);
        linearLayout = view.findViewById(R.id.linearlayout);
        button = view.findViewById(R.id.click);
        recyclerView = view.findViewById(R.id.recyclerview);
        boxList = new ArrayList<>();
       
        for(int i=0; i<t; i++) {
            boxList.add(new Box(i+1, Mode.NOTCHECKED));
        }
        adapter = new BoxAdapter(getActivity(), boxList);
        recyclerView.setAdapter(adapter);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getActivity(), "You clicked me. T= "+t, Toast.LENGTH_SHORT).show();
            }
        });
        return view;
    }

    public void clearBox() {
        boxList.clear();
        adapter.notifyDataSetChanged();
    }

    public int getBoxSize() {
        if(boxList == null) {
            return -1;
        } else {
            return boxList.size();
        }
    }
}

我的家片段代码:

public class HomeFragment extends Fragment {

    private FragmentHomeBinding binding;
    private Button button;
    private ViewPager2 viewPager2;
    private MyAdapter myAdapter;
    private OneFragment oneFragment;
    private TwoFragment twoFragment;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        HomeViewModel homeViewModel = new ViewModelProvider(this).get(HomeViewModel.class);

        binding = FragmentHomeBinding.inflate(inflater, container, false);
        View root = binding.getRoot();   
        button = binding.clearbox;
        viewPager2 = binding.viewpager;

        int q;
        q = new Random().nextInt(10 - 1 + 1) + 1;
       
        oneFragment = new OneFragment(q);
        twoFragment = new TwoFragment();

        myAdapter = new MyAdapter(getChildFragmentManager(), getLifecycle());

        myAdapter.addFragment(oneFragment);
        myAdapter.addFragment(twoFragment);
        myAdapter.notifyDataSetChanged();
        viewPager2.setAdapter(myAdapter);      

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                oneFragment.clearBox();  // app crashed on this line. Null pointer after returned from Gallery or Slideshow. Why?                
            }
        });

        return root;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}

我得到的错误:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.navbartest2, PID: 18771
    java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.navbartest2.adapter.BoxAdapter.notifyDataSetChanged()' on a null object reference
        at com.example.navbartest2.fragment.OneFragment.clearBox(OneFragment.java:82)
        at com.example.navbartest2.ui.home.HomeFragment$1.onClick(HomeFragment.java:72)
        at android.view.View.performClick(View.java:8160)
        at android.widget.TextView.performClick(TextView.java:16222)
        at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1211)
        at android.view.View.performClickInternal(View.java:8137)
        at android.view.View.access$3700(View.java:888)
        at android.view.View$PerformClick.run(View.java:30236)
        at android.os.Handler.handleCallback(Handler.java:938)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:246)
        at android.app.ActivityThread.main(ActivityThread.java:8653)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130)

任何帮助都是值得赞赏的。

java android-fragments nullpointerexception

评论

0赞 Amanpreet Kaur 5/18/2023
您能否添加错误日志以进行更多澄清
0赞 Xoszagas 5/18/2023
完整项目在这里:drive.google.com/file/d/1M0BwonXUjY8IrSAtQWS6SlBquMB28W75/...
0赞 Amanpreet Kaur 5/19/2023
您可以将您的项目上传到 GitHub 并共享链接,这样您就可以轻松地从存储库中查看更改

答:

0赞 Dharmeet Soni 5/18/2023 #1

当我尝试解决我所理解的问题时,当您只调用 oneFragment 的构造函数时,您的对象没有被调用。因此,我建议您尝试将以下代码放入 oneFragment 的构造函数中。 尝试在构造函数上添加此代码并可以检查。 还添加了 try catch 以防止 clearBox 方法上出现空指针等的不需要的情况,以便调用它。

public OneFragment(int k) { boxList = new ArrayList<>(); for(int i=0; i<t; i++) {boxList.add(new Box(i+1, Mode.NOTCHECKED));} }

评论

0赞 Xoszagas 5/18/2023
当我从幻灯片或图库返回时,OneFragment 的适配器和 OneFragment 的 recyclerView 为 null。
0赞 Xoszagas 5/18/2023
完整项目在这里:drive.google.com/file/d/1M0BwonXUjY8IrSAtQWS6SlBquMB28W75/...