【问题标题】:Error when trying to sort the RecyclerView尝试对 RecyclerView 进行排序时出错
【发布时间】:2021-03-28 11:07:25
【问题描述】:

我有一个RecyclerViewitem,我需要通过单击LinerLayout 打开一个DialogFragment,并且在DialogFragment 中有一个Button,我的RecyclerView 将通过单击排序.

现在我单击按钮使应用程序崩溃并出现错误:

    java.lang.NullPointerException: Attempt to read from field 'java.lang.String[] com.example.test.Attraction.FragmentAttractionRecyclerView.mArraysNames' on a null object reference
        at com.example.test.Attraction.DialogSort.sortArray_type(DialogSort.java:36)
        at com.example.test.Attraction.DialogSort.lambda$onCreateView$0$DialogSort(DialogSort.java:29)
        at com.example.test.Attraction.-$$Lambda$DialogSort$hNUzI3gzFGpf0diQdPCF44sgutU.onClick(lambda)
        at android.view.View.performClick(View.java:5692)
        at android.view.View$PerformClick.run(View.java:22596)

如何解决?我怀疑问题出在sortArray_type 不在Fragment 本身中。

RecyclerView所在的Fragment

public class FragmentAttractionRecyclerView extends Fragment {
    private static final String TAG = "FragmentAttractionRecyclerView";
    private RecyclerView mRec;
    public AdapterAttractions adapter;
    public ArrayList<ItemAttractions> exampleList;
    private RecyclerView.LayoutManager mLayoutManager;
    public String[] mArraysNames;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
        mArraysNames  = new String[]{"Baby островок", "Виражи", "Вокруг света", "5D кинотеатр"};
        OnBackPressedCallback callback = new OnBackPressedCallback(true) {
            @Override
            public void handleOnBackPressed() {
                Intent homeIntent = new Intent(Intent.ACTION_MAIN);
                homeIntent.addCategory(Intent.CATEGORY_HOME);
                homeIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(homeIntent);
            }
        };

        requireActivity().getOnBackPressedDispatcher().addCallback(this, callback);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_attraction_test_2, container, false);
    }
    @SuppressLint({"InflateParams", "LongLogTag"})
    @Override
    public void onViewCreated(@NonNull final View view, @Nullable Bundle savedInstanceState) {
        createExampleList();
        buildRecyclerView();

        LinearLayout dialog_button = requireView().findViewById(R.id.dialog_button);

        dialog_button.setOnClickListener(v -> {
            Log.d(TAG, "onClick: opening dialog");
            DialogSort dialog = new DialogSort();
            dialog.show(getFragmentManager(), "DialogSort");
        });


        SearchView searchView = requireView().findViewById(R.id.searchView);
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                adapter.getFilter().filter(newText);
                return false;
            }
        });
    }

    public void createExampleList() {
        exampleList = new ArrayList<>();
        exampleList.add(new ItemAttractions(R.mipmap.unnamed, R.drawable.ic_kid, "Baby островок", "Детский", "60₽", 0));
        exampleList.add(new ItemAttractions(R.mipmap.unnamed, R.drawable.ic_kid, "Виражи", "Детский", "80₽", 1));
        exampleList.add(new ItemAttractions(R.mipmap.unnamed, R.drawable.ic_kid, "Вокруг света", "Детский", "50₽", 2));
        exampleList.add(new ItemAttractions(R.mipmap.unnamed, R.drawable.ic_interactive, "5D кинотеатр", "Интерактивный", "120₽", 3));
        exampleList.add(new ItemAttractions(R.mipmap.unnamed, R.drawable.ic_family, "Кокосовый страйк", "Детско-семейный", "85₽", 4));
        exampleList.add(new ItemAttractions(R.mipmap.unnamed, R.drawable.ic_extreme, "Компас", "Экстримальный", "100₽", 5));
        exampleList.add(new ItemAttractions(R.mipmap.unnamed, R.drawable.ic_extreme, "Лабиринт \"Тарзан\"", "", "", 6));
        exampleList.add(new ItemAttractions(R.mipmap.unnamed, R.drawable.ic_extreme, "Лови волну", "", "", 7));
        exampleList.add(new ItemAttractions(R.mipmap.unnamed, R.drawable.ic_extreme, "Лучный тир \"Робин Гуд\"", "", "", 8));
        exampleList.add(new ItemAttractions(R.mipmap.unnamed, R.drawable.ic_extreme, "Муравейник", "", "", 9));
        exampleList.add(new ItemAttractions(R.mipmap.unnamed, R.drawable.ic_extreme, "Полный улёт", "", "", 10));
        exampleList.add(new ItemAttractions(R.mipmap.unnamed, R.drawable.ic_extreme, "Попрыжек", "", "", 11));
        exampleList.add(new ItemAttractions(R.mipmap.unnamed, R.drawable.ic_extreme, "Предел эмоций", "", "", 12));
    }

    public void buildRecyclerView() {
        mRec = requireView().findViewById(R.id.attraction_recycler);
        adapter = new AdapterAttractions(exampleList);
        mLayoutManager = new LinearLayoutManager(getContext());
        mRec.setLayoutManager(mLayoutManager);
        mRec.setAdapter(adapter);
    }
}

DialogFragment

public class DialogSort extends DialogFragment  {
    FragmentAttractionRecyclerView fragmentAttractionRecyclerView;
    ImageView img;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.dialog_sort, container, false);
        img = view.findViewById(R.id.img);
        img.setOnClickListener(v -> {
            {
                sortArray_type();
                sortArrayList_type();
            }
        });
        return view;
    }
    private void sortArray_type() {
        Arrays.sort(fragmentAttractionRecyclerView.mArraysNames);
        fragmentAttractionRecyclerView.adapter.notifyDataSetChanged();
    }
    private void sortArrayList_type() {
        Collections.sort(fragmentAttractionRecyclerView.exampleList, (o1, o2) -> o1.get_attraction_type().compareTo(o2.get_attraction_type()));
        fragmentAttractionRecyclerView.adapter.notifyDataSetChanged();
    }
}

【问题讨论】:

    标签: android sorting android-recyclerview dialog


    【解决方案1】:

    我在 onCreate 中定义了数组“mArraysNames”。试试吧。您也可以在 onViewCreated 中定义它。

    public class FragmentAttractionRecyclerView extends Fragment {
            private static final String TAG = "FragmentAttractionRecyclerView";
            private RecyclerView mRec;
            public AdapterAttractions adapter;
            public ArrayList<ItemAttractions> exampleList;
            private RecyclerView.LayoutManager mLayoutManager;
            //public String[] mArraysNames;
            public static String[] mArraysNames = new String[]{"Baby островок", "Виражи", "Вокруг света", "5D кинотеатр"};
    
            @Override
            public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setRetainInstance(true);
                /*mArraysNames  = new String[]{"Baby островок", "Виражи", "Вокруг света", "5D кинотеатр"};*/
                OnBackPressedCallback callback = new OnBackPressedCallback(true) {
                    @Override
                    public void handleOnBackPressed() {
                        Intent homeIntent = new Intent(Intent.ACTION_MAIN);
                        homeIntent.addCategory(Intent.CATEGORY_HOME);
                        homeIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(homeIntent);
                    }
                };
        
                requireActivity().getOnBackPressedDispatcher().addCallback(this, callback);
            }
        
            @Override
            public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
                return inflater.inflate(R.layout.fragment_attraction_test_2, container, false);
            }
            @SuppressLint({"InflateParams", "LongLogTag"})
            @Override
            public void onViewCreated(@NonNull final View view, @Nullable Bundle savedInstanceState) {
                createExampleList();
                buildRecyclerView();
        
                ImageView sort_alphabet = requireView().findViewById(R.id.sort_alphabet);
        
                LinearLayout dialog_button = requireView().findViewById(R.id.dialog_button);
        
                dialog_button.setOnClickListener(v -> {
                    Log.d(TAG, "onClick: opening dialog");
                    DialogSort dialog = new DialogSort();
                    dialog.show(getFragmentManager(), "DialogSort");
                });
        
                sort_alphabet.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        sortArray_type();
                        sortArrayList_type();
                    }
                });
        
                SearchView searchView = requireView().findViewById(R.id.searchView);
                searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
                    @Override
                    public boolean onQueryTextSubmit(String query) {
                        return false;
                    }
        
                    @Override
                    public boolean onQueryTextChange(String newText) {
                        adapter.getFilter().filter(newText);
                        return false;
                    }
                });
            }
        
            public void createExampleList() {
                exampleList = new ArrayList<>();
                exampleList.add(new ItemAttractions(R.mipmap.unnamed, R.drawable.ic_kid, "Baby островок", "Детский", "60₽", 0));
                exampleList.add(new ItemAttractions(R.mipmap.unnamed, R.drawable.ic_kid, "Виражи", "Детский", "80₽", 1));
                exampleList.add(new ItemAttractions(R.mipmap.unnamed, R.drawable.ic_kid, "Вокруг света", "Детский", "50₽", 2));
                exampleList.add(new ItemAttractions(R.mipmap.unnamed, R.drawable.ic_interactive, "5D кинотеатр", "Интерактивный", "120₽", 3));
                exampleList.add(new ItemAttractions(R.mipmap.unnamed, R.drawable.ic_family, "Кокосовый страйк", "Детско-семейный", "85₽", 4));
                exampleList.add(new ItemAttractions(R.mipmap.unnamed, R.drawable.ic_extreme, "Компас", "Экстримальный", "100₽", 5));
                exampleList.add(new ItemAttractions(R.mipmap.unnamed, R.drawable.ic_extreme, "Лабиринт \"Тарзан\"", "", "", 6));
                exampleList.add(new ItemAttractions(R.mipmap.unnamed, R.drawable.ic_extreme, "Лови волну", "", "", 7));
                exampleList.add(new ItemAttractions(R.mipmap.unnamed, R.drawable.ic_extreme, "Лучный тир \"Робин Гуд\"", "", "", 8));
                exampleList.add(new ItemAttractions(R.mipmap.unnamed, R.drawable.ic_extreme, "Муравейник", "", "", 9));
                exampleList.add(new ItemAttractions(R.mipmap.unnamed, R.drawable.ic_extreme, "Полный улёт", "", "", 10));
                exampleList.add(new ItemAttractions(R.mipmap.unnamed, R.drawable.ic_extreme, "Попрыжек", "", "", 11));
                exampleList.add(new ItemAttractions(R.mipmap.unnamed, R.drawable.ic_extreme, "Предел эмоций", "", "", 12));
            }
        
            public void buildRecyclerView() {
                mRec = requireView().findViewById(R.id.attraction_recycler);
                adapter = new AdapterAttractions(exampleList);
                mLayoutManager = new LinearLayoutManager(getContext());
                mRec.setLayoutManager(mLayoutManager);
                mRec.setAdapter(adapter);
            }
            private void sortArray_type() {
                Arrays.sort(mArraysNames);
                adapter.notifyDataSetChanged();
            }
        
            private void sortArrayList_type() {
                Collections.sort(exampleList, (o1, o2) -> o1.get_attraction_type().compareTo(o2.get_attraction_type()));
                adapter.notifyDataSetChanged();
            }
        }
    

    【讨论】:

    • 我更新了问题,问题是sortArray_type在`DialogSort`中
    • 还是不行。错误:java.lang.NullPointerException: Attempt to read from field 'com.example.test.Attraction.AdapterAttractions com.example.test.Attraction.FragmentAttractionRecyclerView.adapter' on a null object reference at com.example.test.Attraction.DialogSort.sortArray_type(DialogSort.java:37) at com.example.test.Attraction.DialogSort.lambda$onCreateView$0$DialogSort(DialogSort.java:29) at com.example.test.Attraction.-$$Lambda$DialogSort$hNUzI3gzFGpf0diQdPCF44sgutU.onClick(lambda)
    • 您可以尝试使用“mArraysNames”,方法是将这些数据保存在静态类中,方法是从那里调用它。但这不是推荐的方法。
    • 不行,有什么办法吗?
    • 可以进行空控制检查。如果为 Null,则包含数据。:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多