新手求助,改造以前的谷歌记事本demo,为其添加一个SearchView,给SearchView加上监听器程序就停止运行,以下java代码只贴出onCreateOptionsMenu和 onOptionsItemSelected方法。第一次用searchView,出错了不知道该怎么改   以下为主activity类NotesList,问题出在这个类中,其他类就不贴出了
package com.example.android.notepad;import com.example.android.notepad.NotePad;import android.app.ListActivity;
import android.content.ClipboardManager;
import android.content.ClipData;
import android.content.ComponentName;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.support.v7.widget.SearchView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class NotesList extends ListActivity {
    SearchView mSearchView;    private static final String TAG = "NotesList";
    private static final String[] PROJECTION = new String[] {
            NotePad.Notes._ID, // 0
            NotePad.Notes.COLUMN_NAME_TITLE, // 1
            NotePad.Notes.COLUMN_NAME_CREATE_DATE
    };    private static final int COLUMN_INDEX_TITLE = 1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);        setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT);
        setContentView(R.layout.main_layout);        Intent intent = getIntent();        if (intent.getData() == null) {
            intent.setData(NotePad.Notes.CONTENT_URI);
        }
        getListView().setOnCreateContextMenuListener (this);
        Cursor cursor = managedQuery(
                getIntent().getData(),            // Use the default content URI for the provider.
                PROJECTION,                       // Return the note ID and title for each note.
                null,                             // No where clause, return all records.
                null,                             // No where clause, therefore no where column values.
                NotePad.Notes.DEFAULT_SORT_ORDER  // Use the default sort order.
        );
        String[] dataColumns = { NotePad.Notes.COLUMN_NAME_TITLE,NotePad.Notes.COLUMN_NAME_CREATE_DATE} ;        int[] viewIDs = { android.R.id.text1 ,android.R.id.text2};        // Creates the backing adapter for the ListView.
        SimpleCursorAdapter adapter
                = new SimpleCursorAdapter(
                this,                             // The Context for the ListView
                R.layout.noteslist_item,          // Points to the XML for a list item
                cursor,                           // The cursor to get items from
                dataColumns,
                viewIDs
        );
        setListAdapter(adapter);
    }    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.list_options_menu, menu);
//添加SearchView的代码开始
        MenuItem mMenuItem = menu.findItem(R.id.search);
        mSearchView=(android.support.v7.widget.SearchView) MenuItemCompat.getActionView(mMenuItem);
        mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener(){
            @Override
            public boolean onQueryTextSubmit(String query){
                return false;
            }
            @Override
            public boolean onQueryTextChange(String newText){
                return false;
            }
        });       // 添加SearchView的部分结束
        Intent intent = new Intent(null, getIntent().getData());
        intent.addCategory(Intent.CATEGORY_ALTERNATIVE);
        menu.addIntentOptions(Menu.CATEGORY_ALTERNATIVE, 0, 0,
                new ComponentName(this, NotesList.class), null, intent, 0, null);        return super.onCreateOptionsMenu(menu);
    }    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_add:                startActivity(new Intent(Intent.ACTION_INSERT, getIntent().getData()));
                return true;
            case R.id.menu_paste:                startActivity(new Intent(Intent.ACTION_PASTE, getIntent().getData()));
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
}菜单布局文件
<?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">
    <!--  This is our one standard application action (creating a new note). -->
    <item
        android:id="@+id/search"
        android:actionViewClass="android.support.v7.widget.SearchView"
        android:icon="@android:drawable/ic_menu_search"
        android:orderInCategory="100"
        android:title="搜索"
        android:showAsAction="always|collapseActionView" />
    <item android:id="@+id/menu_add"
          android:icon="@drawable/ic_menu_compose"
          android:title="@string/menu_add"
          android:alphabeticShortcut='a'
          android:showAsAction="always" />
    <!--  If there is currently data in the clipboard, this adds a PASTE menu item to the menu
          so that the user can paste in the data.. -->
    <item android:id="@+id/menu_paste"
          android:icon="@drawable/ic_menu_compose"
          android:title="@string/menu_paste"
          android:alphabeticShortcut='p' />
</menu>
以下报错信息
05-08 23:28:15.460 15959-15959/com.example.android.notepad E/AndroidRuntime: FATAL EXCEPTION: main
                                                                             Process: com.example.android.notepad, PID: 15959
                                                                             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
                                                                                 at com.example.android.notepad.NotesList.onCreateOptionsMenu(NotesList.java:98)
                                                                                 at android.app.Activity.onCreatePanelMenu(Activity.java:2820)
                                                                                 at com.android.internal.policy.impl.PhoneWindow.preparePanel(PhoneWindow.java:548)
                                                                                 at com.android.internal.policy.impl.PhoneWindow.doInvalidatePanelMenu(PhoneWindow.java:917)
                                                                                 at com.android.internal.policy.impl.PhoneWindow$1.run(PhoneWindow.java:258)
                                                                                 at android.os.Handler.handleCallback(Handler.java:739)
                                                                                 at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                 at android.os.Looper.loop(Looper.java:135)
                                                                                 at android.app.ActivityThread.main(ActivityThread.java:5221)
                                                                                 at java.lang.reflect.Method.invoke(Native Method)
                                                                                 at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
                                                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

解决方案 »

  1.   

    看这一篇文章,讲了基本用法http://javaexception.com/archives/82
      

  2.   

    常见的空指针异常,新手博客先看一下吧https://blog.csdn.net/weimingjue/article/details/87921494
    其中常见问题1就是解决空指针异常的
      

  3.   

     @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            MenuInflater inflater = getMenuInflater();
            inflater.inflate(R.menu.menu, menu);
    //添加SearchView的代码开始
            MenuItem mMenuItem = menu.findItem(R.id.search);
            SearchView mSearchView = (SearchView) mMenuItem.getActionView();
            mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
                @Override
                public boolean onQueryTextSubmit(String query) {
                    return false;
                }            @Override
                public boolean onQueryTextChange(String newText) {
                    return false;
                }
            });
            return true;
        }
    直接运行,没有报错!!!