首页 > 解决方案 > 如何通过可重用的 RecyclerView 适配器使用 SQLite 数据

问题描述

我希望使用已在 a 中声明的一些数据,Fragment以便将其显示为RecyclerView项目。问题在于,myList我知道存在类型不匹配。但是,我在 Fragment 的方法中创建了数据库表行,onCreateView因为我想将其DatabaseHandler用于未来的数据集。有没有一种可能的方法可以在 Fragment 中使用这些行,同时确保可以通过项目类属性fullName和/或过滤数据abbreviation?我想避免必须为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)
    }
}

数据库处理程序类

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
    }
}

标签: androiddatabasesqlitekotlinsqliteopenhelper

解决方案


  1. 初始化DatabaseHandler
  2. 使getCompany函数返回公司类型的列表数组
  3. 将它交给适配器,以按照您手动执行的方式显示它。

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);

推荐阅读