如何将SQLite数据与可重用的RecyclerView适配器一起使用
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何将SQLite数据与可重用的RecyclerView适配器一起使用相关的知识,希望对你有一定的参考价值。
我正在寻找使用在Fragment
中声明的一些数据,因此它可以显示为RecyclerView
项目。问题出在myList
,我知道存在类型不匹配。但是,我在Fragment的onCreateView
方法中创建了数据库表行,因为我想在将来的数据集中使用相同的DatabaseHandler
。是否有可能在片段中使用这些行,同时确保数据可以通过项类属性fullName
和/或abbreviation
进行过滤?我想避免为我将要创建的每个数据集创建一个新的DatabaseHandler
。
类型不匹配|必需:MutableList |发现:DatabaseHandler
项目类
data class Companies (val id: Int, val fullName: String, val abbreviation: String)
片段类
class MyFragment : androidx.fragment.app.Fragment() {
private var mAdapter: MyListAdapter? = null
private lateinit var mRecyclerView: androidx.recyclerview.widget.RecyclerView
private var mTwoPane: Boolean = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.layout_recyclerview, container, false)
mTwoPane = (activity as androidx.fragment.app.FragmentActivity).findViewById<View>(R.id.detail_container) != null
mRecyclerView = view.findViewById<RecyclerView>(R.id.recyclerView_list)
mRecyclerView.setHasFixedSize(true)
mRecyclerView.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(this.activity)
mRecyclerView.addItemDecoration(androidx.recyclerview.widget.DividerItemDecoration(Objects.requireNonNull<Context>(context), LinearLayout.VERTICAL))
val companyA = Companies(1, "GlaxoSmithKline plc", "GSK")
val companyB = Companies(2, "Hiscox Ltd", "HSX")
val companyC = Companies(3, "InterContinental Hotels Group plc", "IHG")
val companyD = Companies(4, "Marks & Spencer Group plc", "MKS")
val companyE = Companies(5, "FTSE 150", "")
val companyF = Companies(6, "FTSE 250", "")
val myList = DatabaseHandler(this.context!!)
myList.insertData(companyA)
myList.insertData(companyB)
myList.insertData(companyC)
myList.insertData(companyD)
myList.insertData(companyE)
myList.insertData(companyF)
mRecyclerView.adapter = mAdapter
mAdapter = MyListAdapter(activity!!, myList, mTwoPane)
return view
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
val mInflater = Objects.requireNonNull<androidx.fragment.app.FragmentActivity>(activity).menuInflater
mInflater.inflate(R.menu.menu_search, menu)
val searchitem = menu.findItem(R.id.action_search)
val searchView = searchitem.actionView as SearchView
searchView.maxWidth = Integer.MAX_VALUE
searchView.queryHint = Objects.requireNonNull<Context>(context).getText(R.string.searchhint_stopname)
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String): Boolean {
return false
}
override fun onQueryTextChange(newText: String): Boolean {
mAdapter!!.filter.filter(newText)
return false
}
})
super.onCreateOptionsMenu(menu, inflater)
}
}
DatabaseHandler类
class DatabaseHandler(context: Context) : SQLiteOpenHelper(context, DatabaseHandler.DB_NAME, null, DatabaseHandler.DB_VERSION) {
override fun onCreate(db: SQLiteDatabase) {
val createTable = "CREATE TABLE $TABLE_NAME ($COL_ID INTEGER PRIMARY KEY, $COL_NAME TEXT, $COL_ABBREVIATION TEXT);"
db.execSQL(createTable)
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
val dropTable = "DROP TABLE IF EXISTS $TABLE_NAME"
db.execSQL(dropTable)
onCreate(db)
}
fun insertData(companies: Companies): Boolean {
val db = this.readableDatabase
val values = ContentValues()
values.put(COL_ID, companies.id)
values.put(COL_NAME, companies.fullName)
values.put(COL_ABBREVIATION, companies.abbreviation)
val _success = db.insert(TABLE_NAME, null, values)
db.close()
Log.v("Insertion complete", "Record Inserted Successfully")
return (Integer.parseInt("$_success") != -1)
}
fun getCompany(_id: Int): Companies {
val companies = Companies(_id, "", "")
val db = writableDatabase
val selectQuery = "SELECT * FROM $TABLE_NAME WHCOL_$COL_ID = $_id"
val cursor = db.rawQuery(selectQuery, null)
if (cursor != null) {
cursor.moveToFirst()
while (cursor.moveToNext()) {
val id = Integer.parseInt(cursor.getString(cursor.getColumnIndex(COL_ID)))
val fullName = cursor.getString(cursor.getColumnIndex(COL_NAME))
val abbreviation = cursor.getString(cursor.getColumnIndex(COL_ABBREVIATION))
}
}
cursor.close()
return companies
}
companion object {
private const val DB_VERSION = 1
private const val DB_NAME = "MyCompanies"
private const val TABLE_NAME = "Companies"
private const val COL_ID = "Id"
private const val COL_NAME = "Name"
private const val COL_ABBREVIATION = "Abbreviation"
}
}
MyListAdapter类
class MyListAdapter(private val mCtx: Context,
private val myList: MutableList<Companies>,
private val mTwoPane: Boolean) : androidx.recyclerview.widget.RecyclerView.Adapter<MyListAdapter.CompanyViewHolder>(), Filterable {
private var myListFull = myList.toMutableList()
private val companyFilter = object : Filter() {
override fun performFiltering(constraint: CharSequence?): Filter.FilterResults {
val filteredList = ArrayList<Companies>()
when {
constraint == null || constraint.isEmpty() -> filteredList.addAll(myListFull)
else -> {
val filterPattern = constraint.toString().toLowerCase().trim { it <= ' ' }
for (item in myListFull) {
when {
item.companyName!!.toLowerCase().contains(filterPattern) ->
filteredList.add(item)
}
}
}
}
val results = Filter.FilterResults()
results.values = filteredList
return results
}
override fun publishResults(constraint: CharSequence?, results: Filter.FilterResults?) {
myList.clear()
myList.addAll(results!!.values as List<Companies>)
notifyDataSetChanged()
}
}
inner class CompanyViewHolder(itemView: View) : androidx.recyclerview.widget.RecyclerView
.ViewHolder(itemView) {
var tvTitle: TextView = itemView.findViewById(R.id.tv_RVItem)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CompanyViewHolder {
val inflater = LayoutInflater.from(mCtx)
val v = inflater.inflate(R.layout.recyclerview_item_textview, parent, false)
return CompanyViewHolder(v)
}
override fun onBindViewHolder(holder: CompanyViewHolder, position: Int) {
val product = myList[holder.adapterPosition]
holder.tvTitle.text = product.companyfuName
}
override fun getItemCount(): Int {
return myList.size
}
override fun getFilter(): Filter {
return companyFilter
}
}
答案
- 初始化
DatabaseHandler
- 使
getCompany
函数返回公司类型的列表或数组 - 将它提供给适配器,以便按照您手动执行的方式显示它。
Java代码如下所示:
// My recycler view
RecyclerView rv = (RecyclerView) findViewById(R.id.RVCategory);
LinearLayoutManager llm = new LinearLayoutManager(this);
rv.setLayoutManager(llm);
// My data helper
MDBHelper mDBHelper = new DbHelper(this);
// I gave the returned list to the list in the `Activity`
List = mDBHelper.GetCompany();
// Then I gave it to the adapter
Adapter_Category adapter = new Adapter_Category(CategoryList, inflater);
rv.setAdapter(adapter);
以上是关于如何将SQLite数据与可重用的RecyclerView适配器一起使用的主要内容,如果未能解决你的问题,请参考以下文章
我们如何在Android中重用已经在IOS中创建的Sqlite文件[重复]