You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

RecyclerView中SearchView的setOnQueryListener报错求助

Fixing SearchView Issues in RecyclerView

Let me walk through your code and help you resolve the errors and potential issues with your SearchView implementation for RecyclerView:

1. Fix the Syntax Error in onCreateOptionsMenu

The main error you're seeing is a syntax mistake in the setOnQueryTextListener block—you missed closing the onQueryTextSubmit method body properly before defining onQueryTextChange. Here's the corrected, clean version of your method:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.search_list, menu);
    final MenuItem myMenuItem = menu.findItem(R.id.search_contact);
    
    // Initialize SearchView consistently
    SearchManager manager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    SearchView searchView = (SearchView) myMenuItem.getActionView();
    
    // Keep your custom text color setup
    changedSearchViewTextColor(searchView);

    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            if (!searchView.isIconified()) {
                searchView.setIconified(true);
            }
            myMenuItem.collapseActionView();
            return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            newText = newText.toLowerCase().trim();
            final List<Contact_Object> filterModelList = filter(contacts, newText);
            adapter.setFilter(filterModelList);
            return true;
        }
    });

    return true;
}

Key fixes here:

  • Properly closed the onQueryTextSubmit method with } before moving to onQueryTextChange
  • Cleaned up redundant code calls for better readability
  • Added trim() to the query to ignore accidental whitespace input

2. Improve the Filter Method (Avoid Crashes)

Your current filter method assumes model.getName() is never null, which can cause crashes if a contact has no name. Add a null check to make it safe, plus an optional broader match if needed:

public List<Contact_Object> filter(List<Contact_Object> p, String query) {
    query = query.toLowerCase().trim();
    final List<Contact_Object> filterModeList = new ArrayList<>();
    
    for (Contact_Object model : p) {
        if (model.getName() != null) { // Guard against null names
            final String text = model.getName().toLowerCase();
            // Match start of name OR any substring (remove one if you prefer strict matching)
            if (text.startsWith(query) || text.contains(query)) {
                filterModeList.add(model);
            }
        }
    }
    return filterModeList;
}

3. Verify Adapter's setFilter Method

Make sure your Adapter's parentList is the actual data source used in onBindViewHolder. A typical working Adapter structure would look like this:

public class ContactAdapter extends RecyclerView.Adapter<ContactAdapter.ViewHolder> {
    private List<Contact_Object> parentList; // This is your main data list

    // Constructor to initialize the original data
    public ContactAdapter(List<Contact_Object> parentList) {
        this.parentList = parentList;
    }

    // Your setFilter method (keep this)
    public void setFilter(List<Contact_Object> listItem) {
        parentList = new ArrayList<>();
        parentList.addAll(listItem);
        notifyDataSetChanged();
    }

    // ... Rest of your Adapter code
    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        Contact_Object contact = parentList.get(position);
        // Bind contact data to your views here
    }

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

If your Adapter was using a different list variable instead of parentList, the filter won't update the RecyclerView correctly.

4. Quick Additional Checks

  • Ensure contacts (the original list passed to filter()) is initialized and not null before onQueryTextChange runs
  • Confirm adapter is properly initialized and attached to your RecyclerView before onCreateOptionsMenu is called
  • If using AndroidX, double-check your SearchView import is androidx.appcompat.widget.SearchView (not the old support library version)

After making these changes, your SearchView should work smoothly with RecyclerView filtering!

内容的提问来源于stack exchange,提问作者RahulSingh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 10:08:21