searchView.setSearchableInfo(searchInfo) 每次都给出 NPE 并且找不到原因

searchView.setSearchableInfo(searchInfo) gives NPE every time and cannot find cause

 @Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);

    MenuItem searchItem = menu.findItem(R.id.menu_search);
    android.widget.SearchView searchView = (android.widget.SearchView) searchItem.getActionView();

    SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    SearchableInfo searchInfo = searchManager.getSearchableInfo(getComponentName());
    if(searchInfo != null) {
        searchView.setSearchableInfo(searchInfo);
    }
    //searchView.setIconifiedByDefault(false);

    return true;
}

这是我放置 searchView.setSearchableInfo(searchInfo) 但给我 NPE 错误的菜单创建代码。

完整堆栈跟踪:

11-25 13:53:15.223    1693-1693/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.NullPointerException
            at vt.parthvora.task5maps.MapsActivity.onCreateOptionsMenu(MapsActivity.java:221)
            at android.app.Activity.onCreatePanelMenu(Activity.java:2505)
            at android.support.v4.app.FragmentActivity.onCreatePanelMenu(FragmentActivity.java:262)
            at android.support.v7.internal.view.WindowCallbackWrapper.onCreatePanelMenu(WindowCallbackWrapper.java:85)
            at android.support.v7.app.AppCompatDelegateImplBase$AppCompatWindowCallbackBase.onCreatePanelMenu(AppCompatDelegateImplBase.java:241)
            at android.support.v7.app.AppCompatDelegateImplV7.preparePanel(AppCompatDelegateImplV7.java:1247)
            at android.support.v7.app.AppCompatDelegateImplV7.doInvalidatePanelMenu(AppCompatDelegateImplV7.java:1527)
            at android.support.v7.app.AppCompatDelegateImplV7.access0(AppCompatDelegateImplV7.java:90)
            at android.support.v7.app.AppCompatDelegateImplV7.run(AppCompatDelegateImplV7.java:128)
            at android.os.Handler.handleCallback(Handler.java:725)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:5041)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
            at dalvik.system.NativeStart.main(Native Method)

尝试使用此代码设置搜索视图。我从我的一个项目中复制粘贴了这段代码。你可以用 EditText 或任何你想要的替换 AutoCompleteTextView

menu_main.xml

xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="audioplayer.ui.MainActivity">
<item
    android:id="@+id/action_search"
    android:orderInCategory="100"
    android:title="@string/action_search"
    android:icon="@drawable/search"
    app:showAsAction="always|collapseActionView" />
</menu>

将此代码放入您的主 activity

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

        MenuItem menuItem = menu.getItem(0).setActionView(R.layout.search_view);
        search = (AutoCompleteTextView) menuItem.getActionView().findViewById(
                R.id.search_txt);
        search.setFocusableInTouchMode(true);
        search.requestFocus();
        final ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                MainActivity.this, android.R.layout.simple_list_item_1,
                songNames);
        search.setAdapter(adapter);

        search.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                    long arg3) {
                // TODO Auto-generated method stub
                InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

                in.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY);
                // do what ever you want

            }
        });
        search.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView view, int actionId,
                                          KeyEvent event) {
                // TODO Auto-generated method stub
                if (actionId == EditorInfo.IME_ACTION_GO) {

                    if (search.getText().toString().length() > 0) {
                        startActivity(new Intent(MainActivity.this,
                                SearchActivity.class).putExtra("keyword",
                                search.getText().toString()));
                        overridePendingTransition(R.anim.slide_in_left,
                                R.anim.slide_out_left);
                        return true;
                    }

                }
                return false;
            }
        });

        ImageView imgClear = (ImageView) menuItem.getActionView().findViewById(
                R.id.clear_search);
        imgClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                search.setText("");
                InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                im.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT,
                        InputMethodManager.HIDE_IMPLICIT_ONLY);
            }
        });
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_search:
                InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                im.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT,
                        InputMethodManager.HIDE_IMPLICIT_ONLY);
                break;
        }
        return super.onOptionsItemSelected(item);
    }

这是我的 search_view 布局

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/primary">

        <AutoCompleteTextView
            android:id="@+id/search_txt"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_margin="@dimen/five_dp"
            android:drawableLeft="@drawable/abc_ic_search_api_mtrl_alpha"
            android:ems="10"
            android:hint="@string/action_search"
            android:imeOptions="actionGo"
            android:inputType="textAutoComplete"
            android:singleLine="true"
            android:visibility="visible" />


        <ImageButton
            android:id="@+id/clear_search"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:focusable="true"
            android:background="@drawable/button_selector"
            android:layout_margin="@dimen/five_dp"
            android:padding="5dp"
            android:src="@drawable/abc_ic_clear_mtrl_alpha"
            android:visibility="visible" />

    </RelativeLayout>
</RelativeLayout>