0

I have this search_widget.xml to server as the SearchView in a fragment:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:compat="http://schemas.android.com/apk/res-auto"
      xmlns:app="http://schemas.android.com/tools">
    <item android:id="@+id/search_questions"
          android:title="Search"
          android:icon="@drawable/search"
          compat:showAsAction="always"
          app:actionViewClass="android.support.v7.widget.SearchView"/>
</menu>

Now in my fragment I have this code below:

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater,
                             @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.search_activity_layout, container, false);
        listView = (ListView) rootView.findViewById(R.id.search_list_view);
        spinner = (ProgressBar) rootView.findViewById(R.id.progressBar);
        spinner.setVisibility(View.GONE);
        setHasOptionsMenu(true);
        return rootView;
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.search_widget, menu);
        MenuItem item = menu.findItem(R.id.search_questions);
        SearchView searchView = (SearchView) item.getActionView();

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                retrieveIdsOfDocuments(query);
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });
        super.onCreateOptionsMenu(menu, inflater);
    }

In the above code I am getting an error on the line searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { stating that Attempt to invoke virtual method 'void android.support.v7.widget.SearchView.setOnQueryTextListener(android.support.v7.widget.SearchView$OnQueryTextListener)' on a null object reference.

I have tried to look at other stackoverflow posts of adding a menu in a fragment but haven't gotten a solution that works.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245

2 Answers2

3

Are you using proguard? If so, add the following to your rules file:

-keep class android.support.v7.widget.SearchView { *; }

1

Updated answer:

In your search_widget.xml, the xmlns:app namespace is incorrect. Missed that before. Try setting it to the following:

xmlns:app="http://schemas.android.com/apk/res-auto"
novak
  • 442
  • 2
  • 9