'how implement search view from menu in fragments?

I am trying to implement search in my fragment but its not working. no results shown up with search text. Also all the items are gone from the view when search text is removed and does not load the items on clicking menu item again from bottom navigation bar. I am very new to android development and struggling with searchview Please suggest the solutions. TIA here is my code

Fragment class

public class Cust_Home extends Fragment{

RecyclerView recview_cust;
DatabaseReference data;
Adap cust_adapter;
ArrayList<model> cust_menu;


private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";


private String mParam1;
private String mParam2;

public Cust_Home() {
    // Required empty public constructor
}


public static Cust_Home newInstance(String param1, String param2) {
    Cust_Home fragment = new Cust_Home();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v= inflater.inflate(R.layout.fragment_cust__home, container, false);
    setHasOptionsMenu(true);
    recview_cust = v.findViewById(R.id.Cust_menu);
    data = FirebaseDatabase.getInstance().getReference("FoodMenu");
    recview_cust.setHasFixedSize(true);
    recview_cust.setLayoutManager(new LinearLayoutManager(getContext()));
    cust_menu = new ArrayList<>();
    cust_adapter = new Adap(getContext(),cust_menu);
    recview_cust.setAdapter(cust_adapter);

    data.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {

            for(DataSnapshot dataSnapshot : snapshot.getChildren()){



                model md = dataSnapshot.getValue(model.class);
                cust_menu.add(md);
            }
            cust_adapter.notifyDataSetChanged();

        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {

        }
    });
    return v;

}




@Override
public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
       inflater.inflate(R.menu.search_menu,menu);
       MenuItem item = menu.findItem(R.id.action_search);
       //SearchView searchView = (SearchView) item.getActionView();
       SearchView searchView = (SearchView) item.getActionView();
       searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
           @Override
           public boolean onQueryTextSubmit(String query) {
               return false;
           }

           @Override
           public boolean onQueryTextChange(String newText) {
               cust_adapter.getFilter().filter(newText);
               return false;
           }
       }) ;


    super.onCreateOptionsMenu(menu, inflater);

}


}```

Adapter class


    Context context;
    List<model> list;
    List<model> listfull;



    public Adap(Context context, List<model> list) {
        this.context = context;
        this.list = list;
        this.listfull= new ArrayList<>(list);

    }


    @NonNull
    @Override
    public myViewholder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(context).inflate(R.layout.singleitem,parent,false);
        return new myViewholder(v);
    }

    @Override
    public void onBindViewHolder(@NonNull myViewholder holder, int position) {

        model m = list.get(position);
        holder.fooditem.setText(m.getFoodItem());
        holder.price.setText("$"+m.getFoodPrice());
        holder.chefName.setText(m.getChefName());
        holder.cheflocation.setText(m.getChefAddress());


        //holder.ing.setText(m.getFoodIngredients());
        Glide.with(holder.img.getContext()).load(m.getImage()).into(holder.img);
     
        holder.img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AppCompatActivity activity = (AppCompatActivity)v.getContext();
                activity.getSupportFragmentManager().beginTransaction().replace(R.id.fragmentContainer,new Food_Details(m.getFoodItem(),m.getFoodDesc(),m.getFoodIngredients(),m.getImage(),m.getFoodPrice(),m.getFoodCal(),m.getChefName(),m.getItemID(),m.getUserid(),m.getChefPhoneNumber())).addToBackStack(null).commit();
            }
        });

    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    @Override
    public Filter getFilter() {
        return filterdata;
    }

    private Filter filterdata =new Filter() {
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            String searchText = constraint.toString().toLowerCase();
            List<model>templist = new ArrayList<>();
            if(searchText.length()==0 || searchText.isEmpty()){

                templist.addAll(listfull);
            }
            else {

                for ( model item:listfull){
                    if(item.getFoodItem().toLowerCase().contains(searchText)){

                        templist.add(item);
                    }

                }
            }
            FilterResults filterresults = new FilterResults();
            filterresults.values = templist;

            return filterresults;
        }

        @Override
        protected void publishResults(CharSequence constraint, FilterResults filterresults) {
            list.clear();
            list.addAll((Collection<? extends model>) filterresults.values);
            notifyDataSetChanged();

        }
    };


    public static class myViewholder extends RecyclerView.ViewHolder{

        TextView fooditem, price,chefName,cheflocation;
        ImageView img;
        //ImageButton delete;


        public myViewholder(@NonNull View itemView) {
            super(itemView);


            fooditem = itemView.findViewById(R.id.foodname);
            price = itemView.findViewById(R.id.foodprice);
            chefName = itemView.findViewById(R.id.foodchef);
            //desc = itemView.findViewById(R.id.foodesc);
            img = itemView.findViewById(R.id.foodimageurl);
            cheflocation = itemView.findViewById(R.id.foodlocation);

           


        }
    }

}

menu xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item android:id="@+id/action_search"
        android:title="Search"
        android:icon="@drawable/ic_baseline_search_24"
        app:showAsAction="always|collapseActionView"
        app:actionViewClass="android.widget.SearchView" />
</menu>


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source