setSearchableInfo(searchManager.getSearchableInfo)空指针异常

时间:2015-07-03 01:43:22

标签: java android xml android-studio android-search

我根据文档和其他问题检查并仔细检查了我的清单。我无法理解为什么setSearchableInfo返回NullPointerException

MainActivity.java

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);

    SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView();

    // current activity is not searchable activity
    ComponentName cn = new ComponentName(this, SearchResultsActivity.class);
    searchView.setSearchableInfo(searchManager.getSearchableInfo(cn));

    return true;
}

的AndroidManifest.xml

<activity
        android:name=".MainActivity"
        android:label="@string/title_main_activity">
        <intent-filter>
            <action android:name="com.csgiusa.treatmentmanager.csgitreatmentmanager.RoomEditDetailed" />
            <category android:name="android.intent.category.DEFAULT" />
            <action android:name="android.intent.action.SEARCH" />
        </intent-filter>
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.csgiusa.treatmentmanager.csgitreatmentmanager.MainActivity" />
        <meta-data
            android:name="android.app.default_searchable"
            android:value=".SearchResultsActivity" />
    </activity>

    <activity
        android:name=".SearchResultsActivity"
        android:label="@string/title_activity_search_results">

        <intent-filter>
            <action android:name="android.intent.action.SEARCH" />
        </intent-filter>

        <meta-data
            android:name="android.app.searchable"
            android:resource="@xml/searchable" />

    </activity>

Searchable.xml

<searchable xmlns:android="http://schemas.android.com/apk/res/android"
    android:label="@string/app_name"
    android:hint="@string/app_name" >
</searchable>

menu_main.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"         tools:context=".MainActivity">
<item android:id="@+id/action_settings"
    android:title="@string/action_settings"
    android:orderInCategory="100" app:showAsAction="never" />
<item android:id="@+id/search"
    android:title="@string/search"
    android:icon="@drawable/ic_search"
    app:showAsAction="collapseActionView|ifRoom"
    android:actionViewClass="android.widget.SearchView" />

1 个答案:

答案 0 :(得分:4)

您使用的是AppCompat和AppCompatActivity吗?如果是,您应该使用SearchView的AppCompat版本(support.v7包中的那个)并使用app:actionViewClass而不是android:actionViewClass在菜单中定义它。

然后使用以下方法检索它:

SearchView searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.search));