Search code examples
androidandroid-actionbarsearchview

I am trying to integrate SearchView in ActionBar error(MenuItem1 cannot be cast to android.widget.SearchView)


I am trying to integrate SearchView in ActionBar. I tried all tutorials but i cant still succeeded. This error keeps appearing all time (java.lang.ClassCastException: com.android.internal.view.menu.MenuItem1 cannot be cast to android.widget.SearchView).It will be very helpful if anyone could help me i have been looking this problem since two days ..

 import android.app.SearchManager;
 import android.support.v4.app.Fragment;//I have used Fragment
 import android.view.Menu;
 import android.view.MenuInflater;
 import android.view.MenuItem;
 import android.widget.SearchView;


    // Created Options Menu 
    public void onCreateOptionsMenu(Menu menu,MenuInflater inflater) {

        inflater.inflate(R.menu.activity_main_actionmenu, menu);

        SearchManager searchManager=(SearchManager)   

getActivity().getSystemService(Context.SEARCH_SERVICE);
SearchView searchView=(SearchView) menu.findItem(R.id.actionSearch);
// The error of java.lang.ClassCastException: com.android.internal.view.menu.MenuItem1 cannot  

 //be cast to android.widget.SearchView occur because of above line

searchView.setSearchableInfo(searchManager
        .getSearchableInfo(getActivity().getComponentName()));
super.onCreateOptionsMenu(menu,inflater);
}

MenuItem1.xml

<item
android:id="@+id/actionSearch"
android:actionViewClass="android.widget.SearchView"
// I think android.support.v4.app.Fragment doesnot support android.widget.SearchView
android:icon="@drawable/ic_action_search"
android:showAsAction="always"/>

Solution

  • Try to delete the import library android.widget.SearchView and when you pass the cursor to import it again, verified that you more options.

    The misconception is that doing the Cast (SearchManager) one object that is not your type, try this if you have worked

    SearchManager manager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    SearchView search = (SearchView) menu.findItem (R.id.actionSearch) .getActionView ();