searchView空指针异常

在为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;
    }

你可能感兴趣的:(Android开发,Android,searchView)