如何在基于 SQLite 的 recyclerview 中实现 searchview? - 安卓

Posted

技术标签:

【中文标题】如何在基于 SQLite 的 recyclerview 中实现 searchview? - 安卓【英文标题】:How to implement searchview in recyclerview which based on SQLite? - Android 【发布时间】:2021-11-05 06:45:11 【问题描述】:

我正在构建 android 应用程序,它将患者详细信息存储在 SQLite 数据库中,并在 recyclerview 中显示这些数据,现在我想为我的 recyclerview 添加 searchview,请帮助我实现这个。

我在 this youtube 教程系列 - https://youtube.com/playlist?list=PLSrm9z4zp4mGK0g_0_jxYGgg3os9tqRUQ 的帮助下从事这个项目

这是我的 MainActivity 类


import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity 

   RecyclerView recyclerView;
   FloatingActionButton add_button;

   MyDatabaseHelper myDB;
   ArrayList<String> _id, name, disease, medicine, mobile, address, day, month, year;
   CustomAdapter customAdapter;

   @Override
   protected void onCreate(Bundle savedInstanceState) 
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);

       recyclerView = findViewById(R.id.recyclerView);
       add_button = findViewById(R.id.add_button);
       add_button.setOnClickListener(new View.OnClickListener() 
           @Override
           public void onClick(View v) 
               Intent intent = new Intent(MainActivity.this, AddActivity.class);
               startActivity(intent);
           
       );

       myDB = new MyDatabaseHelper(MainActivity.this);
       _id = new ArrayList<>();
       name = new ArrayList<>();
       disease = new ArrayList<>();
       medicine = new ArrayList<>();
       mobile = new ArrayList<>();
       address = new ArrayList<>();
       day = new ArrayList<>();
       month = new ArrayList<>();
       year = new ArrayList<>();

       storeDataInArrays();

       customAdapter = new CustomAdapter(MainActivity.this, _id, name, disease, medicine, mobile, address, day, month, year);
       recyclerView.setAdapter(customAdapter);
       recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
   

   void storeDataInArrays()
       Cursor cursor = myDB.readAllData();
       if(cursor.getCount() == 0)
           Toast.makeText(this, "No data.", Toast.LENGTH_SHORT).show();
       else
           while (cursor.moveToNext())
               _id.add(cursor.getString(0));
               name.add(cursor.getString(1));
               disease.add(cursor.getString(2));
               medicine.add(cursor.getString(3));
               mobile.add(String.valueOf(cursor.getLong(4)));
               address.add(cursor.getString(5));
               day.add(cursor.getString(6));
               month.add(cursor.getString(7));
               year.add(cursor.getString(8));
           
       
   

这是我的 AddActivity 类

package com.example.myclinic;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class AddActivity extends AppCompatActivity 

    EditText name_input, disease_input, medicine_input, mobile_input, address_input, day_input, month_input, year_input;
    Button add_button;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add);

        name_input = findViewById(R.id.name_input);
        disease_input = findViewById(R.id.disease_input);
        medicine_input = findViewById(R.id.medicine_input);
        mobile_input = findViewById(R.id.mobile_input);
        address_input = findViewById(R.id.address_input);
        day_input = findViewById(R.id.day_input);
        month_input = findViewById(R.id.month_input);
        year_input = findViewById(R.id.year_input);

        add_button = findViewById(R.id.add_button);

        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
        String strDate = formatter.format(date);
        day_input.setText(strDate.substring(0,2));
        month_input.setText(strDate.substring(3,5));
        year_input.setText(strDate.substring(6,10));

        add_button.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View v) 

                if (TextUtils.isEmpty(name_input.getText().toString()) || TextUtils.isEmpty(disease_input.getText().toString())) 
                    name_input.setHint("Patient Name* (Mandatory)");
                    disease_input.setHint("Disease* (Mandatory)");
                    Toast.makeText(AddActivity.this,
                            "Failed!", Toast.LENGTH_SHORT).show();
                 else 
                    try 
                        MyDatabaseHelper myDB = new MyDatabaseHelper(AddActivity.this);
                        myDB.addPatient(name_input.getText().toString().trim(),
                                disease_input.getText().toString().trim(),
                                medicine_input.getText().toString().trim(),
                                Long.parseLong("0" + mobile_input.getText().toString().trim()),
                                address_input.getText().toString().trim(),
                                Integer.parseInt(day_input.getText().toString().trim()),
                                Integer.parseInt(month_input.getText().toString().trim()),
                                Integer.parseInt(year_input.getText().toString().trim()));
                     catch (Exception e) 
                        Toast.makeText(AddActivity.this, "Failed!", Toast.LENGTH_SHORT).show();
                    
                
            
        );

    

这里是 MyDatabaseHelper 类

package com.example.myclinic;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.google.android.material.shape.ShapeAppearanceModel;

public class MyDatabaseHelper extends SQLiteOpenHelper 

    private Context context;
    private static final String DATABASE_NAME = "PatientList.db";
    private static final int DATABASE_VERSION = 1;

    private static final String TABLE_NAME = "patients";
    private static final String COLUMN_ID = "_id";
    private static final String COLUMN_NAME = "name";
    private static final String COLUMN_DISEASE = "disease";
    private static final String COLUMN_MEDICINES = "medicines";
    private static final String COLUMN_MOBILE = "mobile";
    private static final String COLUMN_ADDRESS = "address";
    private static final String COLUMN_DAY = "day";
    private static final String COLUMN_MONTH = "month";
    private static final String COLUMN_YEAR = "year";

    public MyDatabaseHelper(@Nullable Context context) 
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.context = context;
    

    @Override
    public void onCreate(SQLiteDatabase db) 
        String query =
                "CREATE TABLE " + TABLE_NAME +
                        " (" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                        COLUMN_NAME + " TEXT, " +
                        COLUMN_DISEASE + " TEXT, " +
                        COLUMN_MEDICINES + " TEXT, " +
                        COLUMN_MOBILE + " INTEGER, " +
                        COLUMN_ADDRESS + " TEXT, " +
                        COLUMN_DAY + " INTEGER, " +
                        COLUMN_MONTH + " INTEGER, " +
                        COLUMN_YEAR + " INTEGER);";
        db.execSQL(query);

    

    @Override
    public void onUpgrade(SQLiteDatabase db, int i, int i1) 
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(db);
    

   void addPatient(String pname, String pdisease, String pmedicines, Long pmobile, String paddress, int pday, int pmonth, int pyear)
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv = new ContentValues();

        cv.put(COLUMN_NAME, pname);
        cv.put(COLUMN_DISEASE, pdisease);
        cv.put(COLUMN_MEDICINES, pmedicines);
        cv.put(COLUMN_MOBILE, pmobile.longValue());
        cv.put(COLUMN_ADDRESS, paddress);
       cv.put(COLUMN_DAY, pday);
       cv.put(COLUMN_MONTH, pmonth);
       cv.put(COLUMN_YEAR, pyear);
        long result = db.insert(TABLE_NAME, null, cv);
        if(result == -1) 
            Toast.makeText(context, "Failed!", Toast.LENGTH_SHORT).show();
        else
            Toast.makeText(context, "Added Successfully...", Toast.LENGTH_SHORT).show();
        
    

    Cursor readAllData()
        String query = "SELECT * FROM " + TABLE_NAME;
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = null;
        if(db != null) cursor = db.rawQuery(query, null);
        return cursor;
    




这里是 CustomAdapter 类

package com.example.myclinic;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.security.PrivateKey;
import java.util.ArrayList;

public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> 

    private Context context;
    private ArrayList _id, name, disease, medicine, mobile, address, day, month, year;

    CustomAdapter(Context context, ArrayList _id, ArrayList name, ArrayList disease,
                  ArrayList medicine, ArrayList mobile, ArrayList address, ArrayList day, ArrayList month, ArrayList year)
        this.context = context;
        this._id = _id;
        this.name = name;
        this.disease = disease;
        this.medicine = medicine;
        this.mobile = mobile;
        this.address = address;
        this.day = day;
        this.month = month;
        this.year = year;

    
    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) 
        LayoutInflater inflater = LayoutInflater.from(context);
        View view = inflater.inflate(R.layout.my_row, parent, false);
        return new MyViewHolder(view);
    

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) 
        holder.id_txt.setText(String.valueOf(_id.get(position)));
        holder.name_txt.setText(String.valueOf(name.get(position)));
        holder.disease_txt.setText(String.valueOf(disease.get(position)));
        holder.medicine_txt.setText(String.valueOf(medicine.get(position)));
        holder.mobile_txt.setText(String.valueOf(mobile.get(position)));
        holder.address_txt.setText(String.valueOf(address.get(position)));
        holder.day_txt.setText(String.valueOf(day.get(position)));
        holder.month_txt.setText(String.valueOf(month.get(position)));
        holder.year_txt.setText(String.valueOf(year.get(position)));
    

    @Override
    public int getItemCount() 
        return _id.size();
    

    public class MyViewHolder extends RecyclerView.ViewHolder 

        TextView id_txt, name_txt, disease_txt, medicine_txt, mobile_txt, address_txt, day_txt, month_txt, year_txt;
        public MyViewHolder(@NonNull View itemView) 
            super(itemView);
            id_txt = itemView.findViewById(R.id.id_txt);
            name_txt = itemView.findViewById(R.id.name_txt);
            disease_txt = itemView.findViewById(R.id.disease_txt);
            medicine_txt = itemView.findViewById(R.id.medicine_txt);
            mobile_txt = itemView.findViewById(R.id.mobile_txt);
            address_txt = itemView.findViewById(R.id.address_txt);
            day_txt = itemView.findViewById(R.id.day_txt);
            month_txt = itemView.findViewById(R.id.month_txt);
            year_txt = itemView.findViewById(R.id.year_txt);
        
    


【问题讨论】:

我认为将数据存储在数组中并不明智。只需使用包含所有信息的对象的单个数组即可。您可以使用 ORM(对象关系映射)来做到这一点。 感谢回复,其实我是java编程的初学者。你的评论是否意味着如果我想解决这个问题,那么我需要创建一个包含我所有数据的类,然后进行处理,这是你建议我的吗? 是的,如果是表/数据库中的一行数据,最好的表示是对象。您的解决方案基于该表的列,这需要大量自定义代码,因为它不是常见的用例。这里有一些库可能有助于处理行dzone.com/articles/… 谢谢先生,现在我实现了搜索功能,因为你的帮助,我真的很感激。现在我将发布对其他人有帮助的解决方案。 【参考方案1】:

为了在这个项目中实现搜索功能,正如@thinkgruen 建议的那样,我需要处理单个数组列表而不是多个数组列表,这就是为什么我创建了包含所有数据的单独类并制作了该类的数组列表,并实现了过滤器方法那个数组列表。

之后我浏览了这个 youtube 教程 - https://www.youtube.com/watch?v=CTvzoVtKoJ8

我在这里发布更改的代码,我将旧代码作为注释并将更改的代码标记为 //U 。因为你可以清楚地看到我做了什么改变。

首先这里是新类 - PatientList

package com.example.myclinic;

public class PatientList 

    private int _id;
    private String name;
    private String disease;
    private String medicine;
    private long mobile;
    private String address;
    private int day;
    private int month;
    private int year;
    private String serialid;


    public int getid() 
        return _id;
    
    public void setid(int _id) 
        this._id = _id;
    

    public String getname() 
        return name;
    
    public void setname (String name) 
        this.name = name;
    

    public String getdisease() 
        return disease;
    
    public void setdisease (String disease) 
        this.disease = disease;
    

    public String getmedicine() 
        return medicine;
    
    public void setmedicine (String medicine) 
        this.medicine = medicine;
    

    public long getmobile() 
        return mobile;
    
    public void setmobile (long mobile) 
        this.mobile = mobile;
    

    public String getaddress() 
        return address;
    
    public void setaddress (String address) 
        this.address = address;
    

    public int getday() 
        return day;
    
    public void setday(int day) 
        this.day = day;
    

    public int getmonth() 
        return month;
    
    public void setmonth(int month) 
        this.month = month;
    

    public int getyear() 
        return year;
    
    public void setyear(int year) 
        this.year = year;
    

    public String getserialid() 
        return serialid;
    
    public void setserialid (String serialid) 
        this.serialid = serialid;
    

    //constructor
    public PatientList(int _id, String name, String disease, String medicine, long mobile, String address, int day, int month, int year, String serialid)
        this._id = _id;
        this.name = name;
        this.disease = disease;
        this.medicine = medicine;
        this.mobile = mobile;
        this.address = address;
        this.day = day;
        this.month = month;
        this.year = year;
        this.serialid = serialid;
    



之后,在 Class - CustomAdapter


package com.example.myclinic;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

//U
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> implements Filterable 

    private Context context;
  //  private ArrayList _id, name, disease, medicine, mobile, address, day, month, year, serialid;
    private  List<PatientList> patientList = new ArrayList<>();      //U
    private List<PatientList> patientListAll = new ArrayList<>();


    CustomAdapter(Context context,/* ArrayList _id, ArrayList name, ArrayList disease,
                  ArrayList medicine, ArrayList mobile, ArrayList address, ArrayList day, ArrayList month, ArrayList year, ArrayList serialid, */
                  ArrayList<PatientList> patientList)
        this.context = context;
      /*
        this._id = _id;
        this.name = name;
        this.disease = disease;
        this.medicine = medicine;
        this.mobile = mobile;
        this.address = address;
        this.day = day;
        this.month = month;
        this.year = year;
        this.serialid = serialid;
        */

        this.patientList = patientList;   //U
        this.patientListAll = new ArrayList<>(patientList);

    
    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) 
        LayoutInflater inflater = LayoutInflater.from(context);
        View view = inflater.inflate(R.layout.my_row, parent, false);
        return new MyViewHolder(view);
    

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) 
        /*
        holder.id_txt.setText(String.valueOf(_id.get(position)));
        holder.name_txt.setText(String.valueOf(name.get(position)));
        holder.disease_txt.setText(String.valueOf(disease.get(position)));
        holder.medicine_txt.setText(String.valueOf(medicine.get(position)));
        holder.mobile_txt.setText(String.valueOf(mobile.get(position)));
        holder.address_txt.setText(String.valueOf(address.get(position)));
        holder.day_txt.setText(String.valueOf(day.get(position)));
        holder.month_txt.setText(String.valueOf(month.get(position)));
        holder.year_txt.setText(String.valueOf(year.get(position)));
        holder.serialid_txt.setText(String.valueOf(serialid.get(position)));
        */

        PatientList plist =  patientList.get(position);         //U
        holder.id_txt.setText(String.valueOf(plist.getid()));
        holder.name_txt.setText(String.valueOf(plist.getname()));
        holder.disease_txt.setText(String.valueOf(plist.getdisease()));
        holder.medicine_txt.setText(String.valueOf(plist.getmedicine()));
        holder.mobile_txt.setText(String.valueOf(plist.getmobile()));
        holder.address_txt.setText(String.valueOf(plist.getaddress()));
        holder.day_txt.setText(String.valueOf(plist.getday()));
        holder.month_txt.setText(String.valueOf(plist.getmonth()));
        holder.year_txt.setText(String.valueOf(plist.getyear()));
        holder.serialid_txt.setText(String.valueOf(plist.getserialid()));
    

    @Override
    public int getItemCount() 
        return patientList.size();
    

    //U
    @Override
    public Filter getFilter() 
        return filter;
    
//U
    Filter filter = new Filter() 
        @Override
        protected FilterResults performFiltering(CharSequence constaint) 

            List<PatientList> filteredList = new ArrayList<>();

            if (constaint.toString().isEmpty()) 
                filteredList.addAll(patientListAll);
             else 
                for (PatientList patient : patientListAll) 
                    if (patient.getname().toLowerCase().contains(constaint.toString().toLowerCase())
                            || patient.getserialid().toLowerCase().contains(constaint.toString().toLowerCase())
                            || patient.getaddress().toLowerCase().contains(constaint.toString().toLowerCase())) 
                        filteredList.add(patient);
                    
                
            

            FilterResults filterResults = new FilterResults();
            filterResults.values = filteredList;
            return filterResults;
        

        @Override
        protected void publishResults(CharSequence constraint, FilterResults filterResults) 
            patientList.clear();
            patientList.addAll((Collection<? extends PatientList>) filterResults.values);
            notifyDataSetChanged();
        
    ;



    public class MyViewHolder extends RecyclerView.ViewHolder 

        TextView id_txt, name_txt, disease_txt, medicine_txt, mobile_txt, address_txt, day_txt, month_txt, year_txt, serialid_txt;
        public MyViewHolder(@NonNull View itemView) 
            super(itemView);
            id_txt = itemView.findViewById(R.id.id_txt);
            name_txt = itemView.findViewById(R.id.name_txt);
            disease_txt = itemView.findViewById(R.id.disease_txt);
            medicine_txt = itemView.findViewById(R.id.medicine_txt);
            mobile_txt = itemView.findViewById(R.id.mobile_txt);
            address_txt = itemView.findViewById(R.id.address_txt);
            day_txt = itemView.findViewById(R.id.day_txt);
            month_txt = itemView.findViewById(R.id.month_txt);
            year_txt = itemView.findViewById(R.id.year_txt);
            serialid_txt = itemView.findViewById(R.id.serialid_txt);
        
    



类数据库助手

package com.example.myclinic;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.google.android.material.shape.ShapeAppearanceModel;

public class MyDatabaseHelper extends SQLiteOpenHelper 

    private Context context;
    private static final String DATABASE_NAME = "PatientList.db";
    private static final int DATABASE_VERSION = 1;

    private static final String TABLE_NAME = "patients";
    private static final String COLUMN_ID = "_id";
    private static final String COLUMN_NAME = "name";
    private static final String COLUMN_DISEASE = "disease";
    private static final String COLUMN_MEDICINES = "medicines";
    private static final String COLUMN_MOBILE = "mobile";
    private static final String COLUMN_ADDRESS = "address";
    private static final String COLUMN_DAY = "day";
    private static final String COLUMN_MONTH = "month";
    private static final String COLUMN_YEAR = "year";
    private static final String COLUMN_SERIALID = "serialid";

    public MyDatabaseHelper(@Nullable Context context) 
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.context = context;
    

    @Override
    public void onCreate(SQLiteDatabase db) 
        String query =
                "CREATE TABLE " + TABLE_NAME +
                        " (" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                        COLUMN_NAME + " TEXT, " +
                        COLUMN_DISEASE + " TEXT, " +
                        COLUMN_MEDICINES + " TEXT, " +
                        COLUMN_MOBILE + " INTEGER, " +
                        COLUMN_ADDRESS + " TEXT, " +
                        COLUMN_DAY + " INTEGER, " +
                        COLUMN_MONTH + " INTEGER, " +
                        COLUMN_YEAR + " INTEGER, " +
                        COLUMN_SERIALID + " TEXT);";
        db.execSQL(query);

    

    @Override
    public void onUpgrade(SQLiteDatabase db, int i, int i1) 
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(db);
    

   void addPatient(String pname, String pdisease, String pmedicines, Long pmobile, String paddress, int pday, int pmonth, int pyear, String pserialid)
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv = new ContentValues();

        cv.put(COLUMN_NAME, pname);
        cv.put(COLUMN_DISEASE, pdisease);
        cv.put(COLUMN_MEDICINES, pmedicines);
        cv.put(COLUMN_MOBILE, pmobile.longValue());
        cv.put(COLUMN_ADDRESS, paddress);
       cv.put(COLUMN_DAY, pday);
       cv.put(COLUMN_MONTH, pmonth);
       cv.put(COLUMN_YEAR, pyear);
       cv.put(COLUMN_SERIALID, pserialid);
        long result = db.insert(TABLE_NAME, null, cv);
        if(result == -1) 
            Toast.makeText(context, "Failed!", Toast.LENGTH_SHORT).show();
        else
            Toast.makeText(context, "Added Successfully...", Toast.LENGTH_SHORT).show();
        
    

    Cursor readAllData()
        String query = "SELECT * FROM " + TABLE_NAME;
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = null;
        if(db != null) cursor = db.rawQuery(query, null);
        return cursor;
    



MainActivity.Java 中的最终更改

package com.example.myclinic;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import androidx.appcompat.widget.SearchView;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity 

    RecyclerView recyclerView;
    FloatingActionButton add_button;

    MyDatabaseHelper myDB;
//    ArrayList<String> _id, name, disease, medicine, mobile, address, day, month, year, serialid;
    ArrayList<PatientList> patientList = new ArrayList<>(); //U
    CustomAdapter customAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        recyclerView = findViewById(R.id.recyclerView);
        add_button = findViewById(R.id.add_button);
        add_button.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View v) 
                Intent intent = new Intent(MainActivity.this, AddActivity.class);
                startActivity(intent);
            
        );

        myDB = new MyDatabaseHelper(MainActivity.this);
     /*
        _id = new ArrayList<>();
        name = new ArrayList<>();
        disease = new ArrayList<>();
        medicine = new ArrayList<>();
        mobile = new ArrayList<>();
        address = new ArrayList<>();
        day = new ArrayList<>();
        month = new ArrayList<>();
        year = new ArrayList<>();
        serialid = new ArrayList<>();
         */
        storeDataInArray();

        customAdapter = new CustomAdapter(MainActivity.this, patientList);
        recyclerView.setAdapter(customAdapter); 
        recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
    

/*
    void storeDataInArrays()
        Cursor cursor = myDB.readAllData();
        if(cursor.getCount() == 0)
            Toast.makeText(this, "No data.", Toast.LENGTH_SHORT).show();
        else
            while (cursor.moveToNext())
                _id.add(cursor.getString(0));
                name.add(cursor.getString(1));
                disease.add(cursor.getString(2));
                medicine.add(cursor.getString(3));
                mobile.add(String.valueOf(cursor.getLong(4)));
                address.add(cursor.getString(5));
                day.add(cursor.getString(6));
                month.add(cursor.getString(7));
                year.add(cursor.getString(8));
                serialid.add(cursor.getString(9));

            
        
     */

    void storeDataInArray()           //U
        Cursor cursor = myDB.readAllData();
        if(cursor.getCount() == 0)
            Toast.makeText(this, "No data.", Toast.LENGTH_SHORT).show();
        else
            while (cursor.moveToNext())
               patientList.add(new PatientList(cursor.getInt(0),
                       cursor.getString(1),
                       cursor.getString(2),
                       cursor.getString(3),
                       cursor.getLong(4),
                       cursor.getString(5),
                       cursor.getInt(6),
                       cursor.getInt(7),
                       cursor.getInt(8),
                       cursor.getString(9)));
            
        
    

 @Override        //U
    public boolean onCreateOptionsMenu(Menu menu)
    
        getMenuInflater().inflate(R.menu.mainmenu, menu);
        MenuItem item = menu.findItem(R.id.action_search);

        SearchView searchView = (SearchView)item.getActionView();
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() 
            @Override
            public boolean onQueryTextSubmit(String query) 
                return false;
            

            @Override
            public boolean onQueryTextChange(String newText) 
                customAdapter.getFilter().filter(newText);
                return false;
            
        );

        return  super.onCreateOptionsMenu(menu);
    



AddActivity 没有任何变化。 希望对您有所帮助。

【讨论】:

以上是关于如何在基于 SQLite 的 recyclerview 中实现 searchview? - 安卓的主要内容,如果未能解决你的问题,请参考以下文章

如何从基于 sqlite 的日期约束中提取数据

如何使用 sequelize 基于 sqlite3 中的“日期”列进行查询?

如何在sqlite中对表中的行进行排名?

iCloud 中基于 SQLite 的核心数据中的有序关系

Android RecyclerView单击长按事件:基于OnItemTouchListener +GestureDetector标准实现,封装抽取成通用工具类

如何在 sqlite 表中找到间隙?