androidandroid-sqliteandroid-search

How to Search Inserted Data with Edit Text


RecordListActivity.Java

//        query 
String select = "Select name, phone from RECORD Where(name like " + "'%name%'" +
                ")";
            Cursor cursor2 = mSQLiteHelper.searchData(select);
            if (cursor2.getCount() > 0 ){
                Toast.makeText(RecordListActivity.this, "Not Found", Toast.LENGTH_SHORT).show();
            }

// SearchView

mSearchView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                Log.d("data", charSequence.toString());
            }

            @Override
            public void onTextChanged(CharSequence charSequence2, int i, int i1, int i2) {



            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

database

public Cursor searchData(String sql2){

        SQLiteDatabase database = this.getReadableDatabase();
        return database.rawQuery(sql2,null);


    }

Model

private int id;
    private String name;
    private String phone;

    public Model(int id, String name, String phone) {
        this.id = id;
        this.name = name;
        this.phone = phone;
    }

    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 getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

my goal is to search the listview by phrases. When a keyword is entered in the search (EditText), I want the listview to be filtered accordingly. I already have the EditText ready there, while, I am new that's why don't know how to do that, please help me? thanks

Search(Edittext), it takes keyword but doesn't show what I have given in the input


Solution

  • This code (for onTextChanged callback) can display contacts by name:

    String select = "SELECT * FROM RECORD WHERE name LIKE '"+charSequence2+"%'";
    Cursor cursor = mSQLiteHelper.searchData(select);
    
    mList.clear();
    while(cursor.moveToNext()) {
       int id = cursor.getInt(0);
       String name = cursor.getString(1);
       String phone = cursor.getString(2);
       mList.add(new Model(id,name,phone));
    }
    
    mAdapter.notifyDataSetChanged();