Search code examples
androidxamarinsearchview

_adapater does not exist in the current context


protected override void OnCreate (Bundle bundle)
    {
        base.OnCreate (bundle);

        // Set our view from the "main" layout resource
        SetContentView (Resource.Layout.Main);
        var product = new[] {

            "India","Nokia","Dhurv","Gohil","Patel","Sony","Bhaumik","Umang","Riya","Afghanistan","America"

        };


        var _listView = FindViewById<ListView>(Resource.Id.MylistView);
        var _adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, product);
        _listView.Adapter = _adapter;

    }


    public override bool OnCreateOptionsMenu (IMenu menu) 
    {
        MenuInflater.Inflate (Resource.Layout.Menu,menu);



        var item = menu.FindItem(Resource.Id.action_search);
        var searchView = MenuItemCompat.GetActionView (item);

        var _searchView = searchView.JavaCast<SearchView>();

        _searchView.QueryTextChange += (s, e) => _adapter.Filter.InvokeFilter(e.NewText);


        _searchView.QueryTextSubmit += (s, e) =>
        {
            // Handle enter/search button on keyboard here
            Toast.MakeText(this, "Searched for: " + e.Query, ToastLength.Short).Show();
            e.Handled = true;
        };


        return true;
    }

I got the error:

_adapter does not exist in current context (in OnCreateOptionsMenu)

How to solve this error?

I have not used AppCompat for the SearchView. Is code okay ? Is there anyway to solve this ?


Solution

  • You cannot access _adapter in OnCreateOptionsMenu because it is only known inside OnCreate. To access it in other methods of your class you need to make it a class member. Maybe somewhat like this:

    class MyClass
    {
        ArrayAdapter<String> _adapter = null;
        ...
        protected override void OnCreate (Bundle bundle)
        {
            base.OnCreate (bundle);
            // ... the rest of your code
            _adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, product);
            // ...
        }
    
        protected override void OnCreateOptionsMenu(IMenu menu)
        {
            // ... other stuff
            _searchView.QueryTextChange += (s, e) => _adapter.Filter.InvokeFilter(e.NewText);
            // ...
        }
    }
    

    Mind that there is no var in front of _adapter = ... in OnCreate.