如何使用 Android Kotlin 在 Fragment 中使用上下文?

How to use Context in Fragment using Android Kotlin?

我想从 SQLite 数据库中读取数据。我想在片段中获取该数据。但是我无法获取该数据。这是我的片段代码:-

class AuditFragment : Fragment() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_audit, container, false)

        val id = "LAW_TABLE_DATABASE"

        view.findViewById<FloatingActionButton>(R.id.fb_audit).setOnClickListener {
            val intent = Intent(requireContext(), Datafunction::class.java)
            intent.putExtra("id", id)
            startActivity(intent)
        }
        getAuditListFromDB()

        return view
    }

    private fun getAuditListFromDB() {

        val dbHandler = FilesDatabase(this)

        val getAuditFilesList = dbHandler.getAUDITFileslist()

        if (getAuditFilesList.size > 0) {
            recycle_audit.visibility = View.VISIBLE
            no_data_audit.visibility = View.GONE
            setupAuditFilesRecyclerView(getAuditFilesList)
        } else {
            recycle_audit.visibility = View.GONE
            no_data_audit.visibility = View.VISIBLE
        }
    }


    private fun setupAuditFilesRecyclerView(happyPlacesList: ArrayList<FilesData>) {

        recycle_audit.layoutManager = LinearLayoutManager(this)
        recycle_audit.setHasFixedSize(true)

        val placesAdapter = DatafunctionAdapter(this, happyPlacesList)
        recycle_audit.adapter = placesAdapter
    }
}

这是我存储和读取 SQLite 数据的代码:-

class FilesDatabase(context: Context) :
    SQLiteOpenHelper(context, AC_TABLE_DB, null, DATABASE_VERSION) {

    companion object{
        private const val DATABASE_VERSION = 1
        private const val AC_TABLE_DB = "AC_TABLE_DATABASE"
        private const val TABLE_FILES_DATABASE ="FILES_TABLE"

        private const val KEY_ID = "_id"
        private const val KEY_TITLE = "title"
        private const val KEY_DATE = "date"
        private const val KEY_FILE_PATH = "filepath"
        private const val KEY_FILE_NAME = "filename"
    }


    override fun onCreate(db: SQLiteDatabase?) {
        val CREATE_TABLE = ( "CREATE TABLE " + TABLE_FILES_DATABASE + "("
                + KEY_ID + " INTEGER PRIMARY KEY,"
                + KEY_TITLE + " TEXT, "
                + KEY_DATE + " TEXT, "
                + KEY_FILE_PATH + " TEXT, "
                + KEY_FILE_NAME + " TEXT)")
        db?.execSQL(CREATE_TABLE)
    }

    override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
        db!!.execSQL("DROP TABLE IF EXISTS $TABLE_FILES_DATABASE")
        onCreate(db)
    }

    fun addFilesdatabase(filesdata: FilesData): Long {
        val db = this.writableDatabase

        val contentValues = ContentValues()
        contentValues.put(KEY_TITLE, filesdata.title)
        contentValues.put(KEY_DATE, filesdata.date)
        contentValues.put(KEY_FILE_PATH, filesdata.filepath)
        contentValues.put(KEY_FILE_NAME, filesdata.fileName)

        // Inserting Row
        val result = db.insert(TABLE_FILES_DATABASE, null, contentValues)
        //2nd argument is String containing nullColumnHack

        db.close() // Closing database connection
        return result
    }

    @SuppressLint("Range")
    fun getAUDITFileslist():ArrayList<FilesData> {
        val filesDatalist:ArrayList<FilesData> = ArrayList()

        val selectQuery ="SELECT * FROM $AC_TABLE_DB"

        val db = this.readableDatabase

        try {
            val cursor: Cursor = db.rawQuery(selectQuery, null)
            if (cursor.moveToFirst()) {
                do {
                    val filedata = FilesData(
                        cursor.getInt(cursor.getColumnIndex(KEY_ID)),
                        cursor.getString(cursor.getColumnIndex(KEY_TITLE)),
                        cursor.getString(cursor.getColumnIndex(KEY_DATE)),
                        cursor.getString(cursor.getColumnIndex(KEY_FILE_PATH)),
                        cursor.getString(cursor.getColumnIndex(KEY_FILE_NAME))
                    )
                    filesDatalist.add(filedata)
                } while (cursor.moveToNext())
            }
            cursor.close()
        } catch (e: SQLiteException) {
            db.execSQL(selectQuery)
            return ArrayList()
        }
        return filesDatalist
    }
}

我想在recylerview 中读取数据。 我遇到了用于上下文的问题。 有人可以帮我吗?

这可能不是您要找的答案,但您是否考虑过将 Room 包装器与 SQLite 一起使用?它会让你的工作更轻松。

带有 RecyclerView 示例的房间:here

替换:

  val dbHandler = FilesDatabase(this)

与:

  val dbHandler = FilesDatabase(requireActivity())