【问题标题】:Trouble setting up search view in android在android中设置搜索视图时遇到问题
【发布时间】:2016-07-11 20:29:49
【问题描述】:

我正在关注docs,了解如何设置 UI 以在 android 中使用搜索视图。我从字面上复制并粘贴了他们,我得到了java.lang.NullPointerException。

堆栈跟踪:

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)

可搜索的.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;
}

是什么导致了 nullPointerexception,我该如何解决?

【问题讨论】:

  • 发现重复,请看here

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


【解决方案1】:

尝试将 getComponentName() 替换为 (this, YourActivity.class)

【讨论】:

  • getSearchableInfo(ComponentName componentName) 不接受 (this, YourActivity.class) 作为参数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多