简体   繁体   English

如何在android中的recylerview中搜索数据

[英]How to search data in recylerview in android

All my code is running successful but I Want to add Searchview.我所有的代码都运行成功,但我想添加 Searchview。 I tried many method.我尝试了很多方法。

When edittext text change app crashed.当 edittext 文本更改应用程序崩溃时。

I also applied try cathed method but i am not seeing any error Just app crashed and go to main activty.我也应用了 try cathed 方法,但我没有看到任何错误只是应用程序崩溃并转到主要活动。 Here is my listadapter class code.这是我的 listadapter 类代码。

public class MyListAdapter extends RecyclerView.Adapter<MyListAdapter.ViewHolder> implements Filterable {
    ArrayList<MyListData> myListDataArrayList;
    String packaging = "";
    private MyListData[] listdata;
    private Context context;
    private CustomFilter filter;

    public MyListAdapter(ArrayList<MyListData> horizontalList, Context context) {
        this.myListDataArrayList = horizontalList;
        this.context = context;

    }

    // RecyclerView recyclerView;
    public MyListAdapter(MyListData[] listdata) {
        this.listdata = listdata;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);

        return new ViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, final int position) {

        final MyListData myListData = myListDataArrayList.get(position);

        holder.tv_hhid.setText("HHID : " + myListData.getHh_id());
        holder.tv_respid.setText("Resp_ID : " + myListData.getResp_id());
        holder.tv_firstname.setText(myListData.getFirst_name());
        //      holder.tv_firstname.setText(myListData.getFirst_name()+"  " + myListData.getLast_name());
        holder.tv_lastname.setText(myListData.getLast_name());

        holder.relativeLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //    Toast.makeText(view.getContext(), "click on item: " + myListData.getHh_id(), Toast.LENGTH_LONG).show();
                Intent intent = new Intent(view.getContext(), Section_Mandatory.class);
                intent.putExtra("hhid", myListData.getHh_id());
                intent.putExtra("resp_id", myListData.getResp_id());
                view.getContext().startActivity(intent);

            }
        });
    }

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

    @Override
    public Filter getFilter() {
        if (filter == null) {
            filter = new CustomFilter(myListDataArrayList, this);
        }

        return filter;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        public TextView tv_hhid, tv_respid, tv_firstname, tv_lastname;
        public RelativeLayout relativeLayout;

        public ViewHolder(View itemView) {
            super(itemView);
            this.tv_hhid = itemView.findViewById(R.id.tv_hhid);
            this.tv_respid = itemView.findViewById(R.id.tv_respid);
            this.tv_firstname = itemView.findViewById(R.id.tv_firstname);
            this.tv_lastname = itemView.findViewById(R.id.tv_lastname);
            relativeLayout = itemView.findViewById(R.id.relativeLayout);
        }
    }

    public class CustomFilter extends Filter {

        MyListAdapter adapter;
        List<MyListData> filterList;

        public CustomFilter(List<MyListData> filterList, MyListAdapter adapter) {
            this.adapter = adapter;
            this.filterList = filterList;

        }


        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            FilterResults results = new FilterResults();

            return results;
        }

        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {

            adapter.myListDataArrayList = (ArrayList<MyListData>) results.values;

            adapter.notifyDataSetChanged();
        }

    }

Here is My Getter and Setter Class.这是我的 Getter 和 Setter 类。

public class MyListData {
    private String hh_id;
    private String resp_id;
    private String first_name;
    private String last_name;

    ///public MyListData(String hh_id, String resp_id, String first_name, String last_name) {
    public MyListData() {
        this.hh_id = hh_id;
        this.resp_id = resp_id;
        this.first_name = first_name;
        this.last_name = last_name;
    }

    public String getHh_id() {
        return hh_id;
    }

    public void setHh_id(String hh_id) {
        this.hh_id = hh_id;
    }

    public String getResp_id() {
        return resp_id;
    }

    public void setResp_id(String resp_id) {
        this.resp_id = resp_id;
    }

    public String getFirst_name() {
        return first_name;
    }

    public void setFirst_name(String first_name) {
        this.first_name = first_name;
    }

    public String getLast_name() {
        return last_name;
    }

    public void setLast_name(String last_name) {
        this.last_name = last_name;
    }
}

Here Is My Activity Class.这是我的活动课。

public class Edit_Form extends AppCompatActivity {
    DatabaseAdapter databaseAccess;
    RecyclerView recyclerView;
    TextView textView;
    LinearLayoutManager manager;
    ArrayList<MyListData> myListDataArrayList;
    MyListAdapter adapter;
    EditText searchview;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit__form);
        recyclerView = findViewById(R.id.recyclerView);
        textView = findViewById(R.id.txtNoDataFound);
        searchview = findViewById(R.id.Search_view_);

        manager = new LinearLayoutManager(Edit_Form.this, RecyclerView.VERTICAL, false);
        recyclerView.setLayoutManager(manager);
        myListDataArrayList = new ArrayList<>();
        readData();


        searchview.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) {
                try {
                    String text = searchview.getText().toString().toLowerCase();
                    if (adapter != null) {
                        adapter.getFilter().filter(text);
                    }
                } catch (Exception e) {
                    Toast.makeText(Edit_Form.this, "" + e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    void readData() {
        Cursor cursor;
        databaseAccess = new DatabaseAdapter(Edit_Form.this);
        databaseAccess.Open();
        cursor = databaseAccess.editform();
        if (cursor != null && cursor.getCount() > 0) {
            recyclerView.setVisibility(View.VISIBLE);
            textView.setVisibility(View.GONE);
            if (cursor.moveToFirst()) {
                do {
                    String str_hhid = (cursor.getString(cursor.getColumnIndex("hhid_id")));
                    String str_Resp_id = (cursor.getString(cursor.getColumnIndex("resp_id")));
                    String str_first_name = (cursor.getString(cursor.getColumnIndex("q1_fname")));
                    String str_last_name = (cursor.getString(cursor.getColumnIndex("q1_lname")));

                    MyListData myListData = new MyListData();
                    myListData.setHh_id(str_hhid);
                    myListData.setResp_id(str_Resp_id);
                    myListData.setFirst_name(str_first_name);
                    myListData.setLast_name(str_last_name);
                    myListDataArrayList.add(myListData);
                } while (cursor.moveToNext());

                cursor.close();
            }
            if (myListDataArrayList != null && myListDataArrayList.size() > 0) {
                adapter = new MyListAdapter(myListDataArrayList, Edit_Form.this);
                recyclerView.setAdapter(adapter);
            }
        } else {
            textView.setVisibility(View.VISIBLE);
            recyclerView.setVisibility(View.GONE);
            //    Toast.makeText(Edit_Form.this, "No Data Found ", Toast.LENGTH_SHORT).show();
        }
    }
}

Here is my recyclerview xml activity.这是我的 recyclerview xml 活动。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white_color"
    android:orientation="vertical"
    tools:context=".Edit_Form.Edit_Form">

    <EditText
        android:id="@+id/Search_view_"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="20dp"
        android:layout_marginEnd="20dp"
        android:hint="Search"
        android:padding="20dp"
        android:textColorHint="#606060"
        android:textSize="18sp"
        android:textStyle="bold"
         />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginLeft="24dp"
        android:layout_marginTop="12dp"
        android:layout_marginRight="24dp"
        android:layout_marginBottom="12dp"
        android:visibility="gone" />

    <TextView
        android:id="@+id/txtNoDataFound"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:fontFamily="serif"
        android:gravity="center"
        android:text="No Data found."
        android:textColor="@color/colorPrimary"
        android:textSize="18sp"
        android:textStyle="bold"
        android:visibility="gone" />
</LinearLayout>

Here is my list item content xml activity..这是我的列表项内容 xml 活动..

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/relativeLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="4dp"
    android:orientation="vertical">


    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:background="@color/white_color"
        android:focusable="true"
        app:cardBackgroundColor="@color/white_color"
        app:cardCornerRadius="8dp"
        app:cardElevation="8dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="1dp"
            android:orientation="vertical">

            <androidx.cardview.widget.CardView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="0dp"
                android:background="@color/white_color"
                android:focusable="true"
                app:cardBackgroundColor="@color/white_color"
                app:cardCornerRadius="8dp"
                app:cardElevation="8dp">

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_marginLeft="10dp"
                    android:layout_marginTop="4dp"
                    android:layout_marginRight="10dp"
                    android:layout_marginBottom="5dp"
                    android:orientation="horizontal">

                    <TextView
                        android:id="@+id/tv_hhid"
                        android:layout_width="wrap_content"
                        android:layout_height="match_parent"
                        android:layout_marginLeft="8dp"
                        android:gravity="center"
                        android:paddingLeft="16dp"
                        android:paddingTop="4dp"
                        android:paddingRight="16dp"
                        android:paddingBottom="4dp"
                        android:text="HH ID :"
                        android:textAllCaps="false"
                        android:textColor="#96144C"
                        android:textSize="14sp"
                        android:textStyle="bold" />

                    <TextView
                        android:id="@+id/tv_respid"
                        android:layout_width="wrap_content"
                        android:layout_height="match_parent"
                        android:layout_marginLeft="8dp"
                        android:gravity="center"
                        android:paddingLeft="16dp"
                        android:paddingTop="4dp"
                        android:paddingRight="16dp"
                        android:paddingBottom="4dp"
                        android:text="Resp ID :"
                        android:textAllCaps="false"
                        android:textColor="#4CAF50"
                        android:textSize="14sp"
                        android:textStyle="bold" />
                </LinearLayout>
            </androidx.cardview.widget.CardView>

            <androidx.cardview.widget.CardView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="0.5dp"
                android:background="@color/white_color"
                android:focusable="true"
                app:cardBackgroundColor="@color/white_color"
                app:cardCornerRadius="8dp"
                app:cardElevation="8dp">

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_marginLeft="10dp"
                    android:layout_marginTop="4dp"
                    android:layout_marginRight="10dp"
                    android:layout_marginBottom="5dp"
                    android:orientation="horizontal">

                    <TextView
                        android:id="@+id/tv_firstname"
                        android:layout_width="wrap_content"
                        android:layout_height="match_parent"
                        android:layout_marginLeft="8dp"
                        android:gravity="center"
                        android:paddingLeft="16dp"
                        android:paddingTop="4dp"
                        android:paddingRight="16dp"
                        android:paddingBottom="4dp"
                        android:text="First Name :"
                        android:textAllCaps="false"
                        android:textColor="#96144C"
                        android:textSize="14sp"
                        android:textStyle="bold" />

                    <TextView
                        android:id="@+id/tv_lastname"
                        android:layout_width="wrap_content"
                        android:layout_height="match_parent"
                        android:gravity="center"
                        android:paddingTop="4dp"
                        android:paddingRight="16dp"
                        android:paddingBottom="4dp"
                        android:text="Last Name :"
                        android:textColor="#4CAF50"
                        android:textSize="14sp"
                        android:textStyle="bold" />
                </LinearLayout>
            </androidx.cardview.widget.CardView>
        </LinearLayout>

    </androidx.cardview.widget.CardView>

</RelativeLayout>

Thanks In Advance提前致谢

You can add this method inside your Activity/Fragment class您可以在 Activity/Fragment 类中添加此方法

   void filter(String text){
  ArrayList<ModelClass> model=new ArrayList<>();
    for(ModelClass name: model){
        //or use .equal(text) with you want equal match
        //use .toLowerCase() for better matches
        if(name.getName().toLowerCase().contains(text.toLowerCase())){
            model.add(name);
        }
    //update recyclerview
    adapter.updateList(model);

where ModelClass is your POJO class as MyListData in your case在你的情况下,ModelClass 是你的 POJO 类作为 MyListData

use this method like this像这样使用这种方法

 searchView.addTextChangedListener(new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            filter(s.toString());

            // TODO Auto-generated method stub
        }

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

            // TODO Auto-generated method stub
        }

        @Override
        public void afterTextChanged(Editable s) {

            // filter your list from your input
            //you can use runnable postDelayed like 500 ms to delay search text
        }
    });
    }

}

and add following method inside adapter :并在适配器中添加以下方法:

  public void updateList(List<ModelClass> list){
    modelList= list;
    notifyDataSetChanged();
}

I think you should set adapter.getFilter().filter(text) in onTextChanged method.我认为你应该在onTextChanged方法中设置adapter.getFilter().filter(text)

@Override  
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {  
  adapter.getFilter().filter(cs);   
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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