在MainActivity中加入一個EditText和Button
利用Button控制資料的排序方式
button.setOnClickListener{
when(mode){
0 ->{
//以咖啡的名字排序
val notes = db.rawQuery("SELECT * FROM Notes ODER BY name", null)
}
else ->{{
//以沖煮的方式排序
val notes = db.rawQuery("SELECT * FROM Notes ODER BY ways", null)
}
}
notes.moveToFirst()
item.clear()
for (i in 0 until notes.count) {
item.add( Notes( notes.getLong(0), notes.getString(1), notes.getInt(2), notes.getInt(3), notes.getInt(4), notes.getString(5), notes.getString(6)) )
notes.moveToNext()
adapter.notifyDataSetChanged()
}
}
SQL語法中,使用ODER BY
可以讓資料以欄位值排序
TextChangedListener
可以監聽文字的元件變化,有三個要override的方法
editText.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(p0: Editable?) {
}
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
}
override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
}
})
在beforeTextChanged加入搜尋的語法
val notes = db.rawQuery("SELECT * FROM Notes WHERE name LIKE ${editText.text}", null)
notes.moveToFirst()
item.clear()
for (i in 0 until notes.count) {
item.add( Notes( notes.getLong(0), notes.getString(1), notes.getInt(2), notes.getInt(3), notes.getInt(4), notes.getString(5), notes.getString(6)) )
//移動到下一筆資料
notes.moveToNext()
//更新RecyclerView
adapter.notifyDataSetChanged()
}