欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

searchView空指针异常

程序员文章站 2024-03-07 19:40:15
...

在为SearchView加监听事件时出现以下问题

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method ‘void android.support.v7.widget.SearchView.setOnQueryTextListener(android.support.v7.widget.SearchView$OnQueryTextListener)’ on a null object reference

1.问题原因: 我在onCreate方法中获取了searchView,并为他设置了监听

searchView = (SearchView) findViewById(R.id.action_search);
        searchView.setOnQueryTextListener(new OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                if (!query.equals("") && !query.equals(null)) {
                    searchContent(query);
                } else {
                    Toast.makeText(MainActivity.this,"未输入",Toast.LENGTH_LONG).show();
                }
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });

2、解决:在actionBar或者toolBar中的onCreateOptionsMenu方法中获取searchView并设置监听

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_search,menu);

        MenuItem searchItem = menu.findItem(R.id.action_search);
        SearchView mSearchView = (SearchView) MenuItemCompat.getActionView(searchItem);
        mSearchView.setIconifiedByDefault(true);
        mSearchView.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        mSearchView.setMaxWidth(800);
        mSearchView.setOnQueryTextListener(new OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                if (!query.equals("") && !query.equals(null)) {
                    searchContent(query);
                } else {
                    Toast.makeText(MainActivity.this,"未输入",Toast.LENGTH_LONG).show();
                }
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });
        return true;
    }