Home > Software design >  How to use Context in Fragment using Android Kotlin?
How to use Context in Fragment using Android Kotlin?

Time:03-23

I want to read data from SQLite database. I want get that data in fragment. But I am unable to get that data. here is my code of Fragment:-

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

here is my code for storing and reading SQLite data:-

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

I want to read data in recylerview. I am getting problem with this which is use for context. Can someone please help me?

CodePudding user response:

This is probably not the answer you're looking for, but have you considered using the Room wrapper with SQLite? It will make your job easier.

Room with RecyclerView sample: here

CodePudding user response:

Replace:

  val dbHandler = FilesDatabase(this)

with:

  val dbHandler = FilesDatabase(requireActivity())
  • Related