几天来,我一直在努力使用 android 的搜索功能。无法确定错误。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_exclude_list);
.......
SearchView searchView = (SearchView)findViewById(R.id.options_menu_main_search);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
if(null!=searchManager ) {
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
}
handleIntent(getIntent());
}
@Override
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
handleIntent(intent);
}
private void handleIntent(Intent intent) {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
Log.i("q",query);
}
}
可搜索的.xml
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:hint="@string/search_hint"
android:includeInGlobalSearch="false"
android:label="@string/app_name"
android:searchSettingsDescription="@string/search_hint" />
菜单.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<!-- Search, should appear as action button -->
<item
android:id="@+id/options_menu_main_search"
android:actionViewClass="android.support.v7.widget.SearchView"
android:icon="@drawable/ic_action_search"
android:showAsAction="always"
android:title="Search"/>
</menu>
显现
<activity
android:name="com.xyz.Exclude_list"
android:label="@string/title_activity_exclude_list"
android:screenOrientation="portrait"
android:launchMode="singleTop">
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
<action android:name="android.intent.action.VIEW" />
</intent-filter>
<meta-data
android:name="android.app.searchable"
android:resource="@xml/searchable"
android:value=".app.Search"
/>
</activity>
错误
Caused by: java.lang.NullPointerException
at com.xyz.Exclude_list.onCreate(Exclude_list.java:64)
第 64 行:searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
如果我删除
SearchView searchView = (SearchView)findViewById(R.id.options_menu_main_search);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
if(null!=searchManager ) {
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
}
搜索正在工作,但当我在搜索中输入时,我无法获取/记录任何查询。