旋转由于onQueryTextListener导致崩溃?

问题描述

我有一个球员列表搜索栏。当用户输入搜索栏时,它会过滤列表。注意,设备旋转时会崩溃。搜索视图的逻辑在单独的适配器中执行。有没有办法修改代码,使其在旋转时不会崩溃?我得到的错误
尝试在空对象引用上调用虚拟方法'android.widget.Filter com.example.android.prototype2.views.Playerlistadapter.getFilter()'

 //Assign the search view variable
        searchView = findViewById(R.id.search_users);
        //Set onQueryListener for when text is entered into the search bar
        searchView.setonQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override
            //When text is changed filter the results from the playerlist adapter
            public boolean onQueryTextChange(String newText) {
                adapter.getFilter().filter(newText);
                return false;
            }
        });

适配器逻辑在playerlistadapter

  private Filter exampleFilter = new Filter() {

        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            List<UserHelperClass> filteredList = new ArrayList<>();

            if (constraint == null || constraint.length() == 0) {
                filteredList.addAll(playerListFull);

            } else {
                //trim -empty spaces removed
                String filterPattern = constraint.toString().toLowerCase().trim();

                for (UserHelperClass player : playerListFull) {
                    if (player.getName().toLowerCase().contains(filterPattern)) {
                        filteredList.add(player);
                    }
                }
            }
            FilterResults results = new FilterResults();
            results.values = filteredList;
            return results;
        }


        @Override
        protected void publishResults(CharSequence constraint,FilterResults results) {
            playersList.clear();
            playersList.addAll((List) results.values);
            notifyDataSetChanged();

        }
    };

解决方法

我设法通过在adapter.getFilter()。filter(newText);之前添加if(adapter!= null)使其工作。