Trouble setting up search view in android

时间:2016-07-11 20:29:49

标签: java android nullpointerexception android-menu android-search

I am following the docs on how to set up the UI to use the search view in android. I have literally copied and pasted from them and I get a java.lang.NullPointerException.

Stacktrace:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.SearchView.setSearchableInfo(android.app.SearchableInfo)' on a null object reference
    at com.hb.birthpay.activity.FindFriendActivity.onCreateOptionsMenu(FindFriendActivity.java:75)

searchable.xml:

<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
            android:label="@string/app_name"
            android:hint="Search people" />

fragment_find_friend_menu.xml:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto">

    <item android:id="@+id/action_search"
          android:title="Search"
          android:icon="@drawable/ic_search_black_24dp"
          app:showAsAction="collapseActionView|ifRoom"
          android:actionViewClass="android.widget.SearchView" />

</menu>

FindFriendActivity.java:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.fragment_find_friend_menu, menu);

    // Associate searchable configuration with the SearchView
    SearchManager searchManager =
            (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    SearchView searchView =
            (SearchView) menu.findItem(R.id.action_search).getActionView();
    searchView.setSearchableInfo(
            searchManager.getSearchableInfo(getComponentName()));
    return true;
}

What is causing the nullPointerexception and how do I fix it?

1 个答案:

答案 0 :(得分:0)

尝试用(this,YourActivity.class)

替换getComponentName()