SearchView尝试在空引用上调用虚方法

时间:2017-05-26 03:01:22

标签: android android-fragments nullpointerexception

我将此search_widget.xml作为服务器作为片段中的SearchView:

<?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>

现在我的片段中有以下代码:

    @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);
    }

在上面的代码中,我在行searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {上收到错误,指出Attempt to invoke virtual method 'void android.support.v7.widget.SearchView.setOnQueryTextListener(android.support.v7.widget.SearchView$OnQueryTextListener)' on a null object reference

我试图查看在片段中添加菜单的其他stackoverflow帖子,但还没有找到有效的解决方案。

2 个答案:

答案 0 :(得分:3)

您是否正在使用proguard?如果是这样,请将以下内容添加到您的规则文件中:

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

答案 1 :(得分:2)

更新回答:

在search_widget.xml中,xmlns:app命名空间不正确。之前错过了。尝试将其设置为以下内容:

xmlns:app="http://schemas.android.com/apk/res-auto"