settheline
settheline

Reputation: 3383

ActionBarActivity with SearchView

I have a working search implementation using the Search Widget like so inside of an activity that extends from Activity:

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

    SearchManager searchManager = 
            (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    SearchView searchView = 
            (SearchView) menu.findItem(R.id.action_search).getActionView();

    if(null!=searchManager) {
        searchView.setSearchableInfo(
                searchManager.getSearchableInfo(getComponentName()));
    }
    return true;
}

When changing the activity to extend ActionBarActivity, I get this null pointer:

10-10 15:51:49.044: E/AndroidRuntime(19406): java.lang.NullPointerException
10-10 15:51:49.044: E/AndroidRuntime(19406):    at com.example.myapp.SearchResultsActivity.onCreateOptionsMenu(SearchResultsActivity.java:114)
10-10 15:51:49.044: E/AndroidRuntime(19406):    at android.app.Activity.onCreatePanelMenu(Activity.java:2546)
10-10 15:51:49.044: E/AndroidRuntime(19406):    at android.support.v4.app.FragmentActivity.onCreatePanelMenu(FragmentActivity.java:224)
10-10 15:51:49.044: E/AndroidRuntime(19406):    at android.support.v7.app.ActionBarActivity.superOnCreatePanelMenu(ActionBarActivity.java:232)
10-10 15:51:49.044: E/AndroidRuntime(19406):    at android.support.v7.app.ActionBarActivityDelegateICS.onCreatePanelMenu(ActionBarActivityDelegateICS.java:146)
10-10 15:51:49.044: E/AndroidRuntime(19406):    at android.support.v7.app.ActionBarActivity.onCreatePanelMenu(ActionBarActivity.java:199)
10-10 15:51:49.044: E/AndroidRuntime(19406):    at android.support.v7.app.ActionBarActivityDelegateICS$WindowCallbackWrapper.onCreatePanelMenu(ActionBarActivityDelegateICS.java:293)
10-10 15:51:49.044: E/AndroidRuntime(19406):    at com.android.internal.policy.impl.PhoneWindow.preparePanel(PhoneWindow.java:436)

I do have other ActionBarActivities that work perfectly (though not with a search widget) in my app and I did a project clean with no results. Why am I getting this null pointer in this case?

Upvotes: 0

Views: 1307

Answers (2)

Odaym
Odaym

Reputation: 1858

Here is the complete solution behind what ianhanniballake mentioned above

You have to set OnQueryTextListener on the searchView that you get from MenuItemCompat and then open the activity yourself with the search term that is passed to you from the listener. Tested and works

Upvotes: 0

ianhanniballake
ianhanniballake

Reputation: 199805

For ActionBarActivity, you need to use MenuItemCompat.getActionProvider() along with android.support.v7.widget.SearchView (not the framework SearchView) as per the Action Bar Action View guide.

Upvotes: 1

Related Questions