0

I am trying to use SearchView in app bar. When i run it gives the following error:

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: in.backtogodhead, PID: 1876
                  java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.SearchView.setSearchableInfo(android.app.SearchableInfo)' on a null object reference
                      at in.backtogodhead.MainActivity.onCreateOptionsMenu(MainActivity.java:590)
                      at android.app.Activity.onCreatePanelMenu(Activity.java:2823)
                      at android.support.v4.app.FragmentActivity.onCreatePanelMenu(FragmentActivity.java:328)
                      at android.support.v7.view.WindowCallbackWrapper.onCreatePanelMenu(WindowCallbackWrapper.java:93)
                      at android.support.v7.app.AppCompatDelegateImplBase$AppCompatWindowCallbackBase.onCreatePanelMenu(AppCompatDelegateImplBase.java:332)
                      at android.support.v7.app.AppCompatDelegateImplV9.preparePanel(AppCompatDelegateImplV9.java:1370)
                      at android.support.v7.app.AppCompatDelegateImplV9.doInvalidatePanelMenu(AppCompatDelegateImplV9.java:1650)
                      at android.support.v7.app.AppCompatDelegateImplV9$1.run(AppCompatDelegateImplV9.java:134)
                      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:5254)
                      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:903)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

The following are the details:

/res/xml/searchable.xml

<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
    android:label="@string/app_name"
    android:hint="@string/search_hint" >
</searchable>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="test.test">

    <application
        android:label="@string/app_name"
        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity">

            <meta-data android:name="android.app.default_searchable"
                android:value="test.test.SearchActivity" />


            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

        </activity>

        <activity
            android:name=".SearchActivity"
            android:label="@string/title_activity_search"
            android:theme="@style/AppTheme">

            <intent-filter>
                <action android:name="android.intent.action.SEARCH" />
            </intent-filter>
            <meta-data android:name="android.app.searchable"
                android:resource="@xml/searchable"/>

        </activity>

    </application>

</manifest>

/menu/menu_main.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools" >
    <item android:id="@+id/search"
        android:title="search_title"
        android:icon="@android:drawable/ic_search_category_default"
        app:showAsAction="ifRoom"
        app:actionViewClass="android.support.v7.widget.SearchView" />

</menu>

my MainActivity.java

public class MainActivity extends AppCompatActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Here shows the MainActivity content

    }


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater menuInflater = getMenuInflater();
    menuInflater.inflate(R.menu.menu_main, menu);
    SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView();
    SearchManager searchManager =
            (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    searchView.setSearchableInfo(
            searchManager.getSearchableInfo(getComponentName()));
    return true;
}

My SearchActivity.java

public class SearchActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);

        // Get the intent, verify the action and get the query
        Intent intent = getIntent();
        if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
            String query = intent.getStringExtra(SearchManager.QUERY);
            Toast tag = Toast.makeText(getApplicationContext(), "Testing",Toast.LENGTH_SHORT);
            tag.show();
        }
    }


}

styles.xml

<resources>

    <!-- Base application theme. -->
    <style name="AppBaseTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="android:windowDisablePreview">true</item>
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

    <style name="AppTheme" parent="AppBaseTheme">
        <item name="actionOverflowMenuStyle">@style/OverflowMenu</item>
    </style>

</resources>

progaurd-rulses.pro

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

In my question i am doing everything right but still its showing the error. SO i am not able to figure it out

Santhosh
  • 9,965
  • 20
  • 103
  • 243
  • There is typo in your code. Your `Menu` xml is named as `menu.xml` but you are using `menu_main` in your `onCreateOptionMenu()`. – Aditya Mar 03 '18 at 05:15
  • 1
    You don't find that `SearchView` with `findViewById()`. You call `findItem()` on the `Menu`, then `getActionView()` on the `MenuItem`. – Mike M. Mar 03 '18 at 05:24
  • I have edited my question with ` SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView(); – Santhosh Mar 03 '18 at 06:14
  • OK, then what happened? That's all good now for the NPE. – Mike M. Mar 03 '18 at 06:23
  • Still its showing Searchview = null. Last 2 days i am checking all the solutions. I dont know why its not getting the searchview – Santhosh Mar 03 '18 at 06:28
  • Are you certain it's the exact same Exception? The stack trace didn't change at all? Did you try cleaning/rebuilding? I don't see how a style could cause this, but what happens if you temporarily remove the `actionOverflowMenuStyle` in your `AppTheme`? I just dropped your `MainActivity` code and XML into an empty project, and it works as expected. – Mike M. Mar 03 '18 at 06:37
  • I dont know it started working now. Even without the above change. I think there was some other typo error. – Santhosh Mar 03 '18 at 10:33

2 Answers2

0

See this will help you

@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options_menu, menu);

// Associate searchable configuration with the SearchView
SearchManager searchManager =
       (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView =
        (SearchView) menu.findItem(R.id.search).getActionView();
searchView.setSearchableInfo(
        searchManager.getSearchableInfo(getComponentName()));

return true;
  }

res/menu/options_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/search"
      android:title="@string/search_title"
      android:icon="@drawable/ic_search"
      android:showAsAction="collapseActionView|ifRoom"
      android:actionViewClass="android.widget.SearchView" />
</menu>

res/xml/searchable.xml

<?xml version="1.0" encoding="utf-8"?>

<searchable xmlns:android="http://schemas.android.com/apk/res/android"
    android:label="@string/app_name"
    android:hint="@string/search_hint" />

In Manifest file

<activity ... >
...
<meta-data android:name="android.app.searchable"
        android:resource="@xml/searchable" />

</activity>

<activity android:name=".SearchResultsActivity" ... >
...
<intent-filter>
    <action android:name="android.intent.action.SEARCH" />
</intent-filter>
...
</activity>
Akshay
  • 318
  • 1
  • 15
0

I think your problem is that you use

findViewById(R.id.search) which returns null

Instead you should use

MenuItem searchItem = menu.findItem(R.id.search);

and after

SearchView searchView = MenuItem.getActionView(searchItem);
Maciej Beimcik
  • 3,218
  • 1
  • 24
  • 26
  • I have edited my question with ` SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView();` – Santhosh Mar 03 '18 at 05:55