简体   繁体   中英

How to filter data in a recycler view

I am fetching data from a server in a recycler view.In a layout file I have an EditText field on top and below it I have a recycler view. I want to filter data based on what I have written in EditText field. My problem is as I start typing in EditText field it shows no data in recycler and as I removes everything in EditText field it shows everything. Why it is happening even if I have data present in recycler view with the same name I have entered in EditText field.

This is my code below:

Home.java

public class Home extends Fragment {

String myValue;
RecyclerView recycle;
ArrayList<LoadHomeBooks> list;
HomeBookAdapter adapter;
EditText search;


private static final String URL = "https://www.example.com";

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

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_home, container, false);

    recycle = view.findViewById(R.id.recycle);
    refresh = view.findViewById(R.id.refresh);
    search = view.findViewById(R.id.search);

    list = new ArrayList<>();

    recycle.setHasFixedSize(true);
    recycle.setLayoutManager(new LinearLayoutManager(getActivity()));

    OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(22, TimeUnit.SECONDS)
            .readTimeout(22, TimeUnit.SECONDS)
            .writeTimeout(22, TimeUnit.SECONDS)
            .build();

    RequestBody formBody = new FormBody.Builder().add("city", myValue).build();

    Request request = new Request.Builder().url(URL).post(formBody).build();

    client.newCall(request).enqueue(new Callback() {

        @Override
        public void onResponse(Call call, final Response response) throws IOException {

            if (getActivity() != null) {

                getActivity().runOnUiThread(new Runnable() {

                    @Override
                    public void run() {

                        try {

                            JSONArray jsonArray = new JSONArray(response.body().string());


                            for (int i = jsonArray.length() - 1; i > -1; i--) {

                                JSONObject object = jsonArray.getJSONObject(i);

                                String str1 = object.getString("Book_name");


                                LoadHomeBooks model = new LoadHomeBooks(str1);

                                list.add(model);
                            }

                             adapter = new HomeBookAdapter(list, getActivity());

                            recycle.setAdapter(adapter);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }


        }

        @Override
        public void onFailure(Call call, final IOException e) {

            if (getActivity() != null) {

                getActivity().runOnUiThread(new Runnable() {

                    @Override
                    public void run() {

                      TastyToast.makeText(getActivity(), e.getMessage(), TastyToast.LENGTH_LONG, TastyToast.ERROR).show();
                    }
                });

            }

        }

    });

  search.addTextChangedListener(new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {

            ArrayList<LoadHomeBooks> filterBooks = new ArrayList<>();

            for(LoadHomeBooks books: list){

                String name = books.getbName().toLowerCase();

                if(name.contains(s)){

                    filterBooks.add(books);
                }

                adapter.setFilter(filterBooks);
            }
        }
    });

    return view;
 }

}

HomeBookAdapter.java

public class HomeBookAdapter extends RecyclerView.Adapter<HomeBookAdapter.ViewHolder> {

ArrayList<LoadHomeBooks> list;
Context context;

public HomeBookAdapter(ArrayList<LoadHomeBooks> list,Context context){

    this.list = list;
    this.context = context;
}

@NonNull
@Override
public HomeBookAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {

    View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.home_book_layout,viewGroup,false);

    return new ViewHolder(v);
}

@Override
public void onBindViewHolder(@NonNull HomeBookAdapter.ViewHolder viewHolder, int i) {

    LoadHomeBooks model = list.get(i);

    viewHolder.homeBookName.setText(model.getbName());

}

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

public class ViewHolder extends RecyclerView.ViewHolder{

    TextView homeBookName;

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

        homeBookName = itemView.findViewById(R.id.homeBookName);
    }
}

public void setFilter(ArrayList<LoadHomeBooks> filterBooks){

    list = new ArrayList<>();
    list.addAll(filterBooks);
    notifyDataSetChanged();

  } 
}

LoadHomeBooks.java

public class LoadHomeBooks {

String bName;

public LoadHomeBooks(){

 }

public LoadHomeBooks(String bName){

    this.bName = bName;

 }

public String getbName() {
    return bName;
 }

public void setbName(String bName) {
    this.bName = bName;
 }

}

Someone please let me know what I am doing wrong. Any help would be appreciated.

THANKS

for(LoadHomeBooks books: list){

                String name = books.getbName().toLowerCase();

                if(name.contains(s)){

                    filterBooks.add(books);
                }

                adapter.setFilter(filterBooks); //Place this line outside forloop
            }

Move this code outside the for Loop

adapter.setFilter(filterBooks);

Because adapter is calling set Filter after each iteration.

Also I would request you to move network request to Activity instead of Fragment using interface.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM