0

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?

Prasad v Bhagat
  • 436
  • 2
  • 11
  • Does this answer your question? [Using context in a fragment](https://stackoverflow.com/questions/8215308/using-context-in-a-fragment) – a_local_nobody Mar 22 '22 at 11:53
  • no. App is crashing after using it. – Prasad v Bhagat Mar 22 '22 at 12:03
  • `no. App is crashing after using it. ` that doesn't give me any information to go on, what does the stack trace say ? where is it crashing specifically ? this needs more info – a_local_nobody Mar 22 '22 at 13:27
  • When asking a question, people will be better able to provide help if you provide code that they can easily understand and use to reproduce the problem. This is referred to by community members as creating a [minimal, reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). – tjheslin1 Mar 22 '22 at 15:11

2 Answers2

1

Replace:

  val dbHandler = FilesDatabase(this)

with:

  val dbHandler = FilesDatabase(requireActivity())
Mario Huizinga
  • 780
  • 7
  • 14
0

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

Alula48
  • 37
  • 6
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 22 '22 at 15:10