Answer the question
In order to leave comments, you need to log in
How to load ready sqlite db on android app?
A simple application written in Kotlin for Android with a SQLITE database. When running the application on another emulator, a new and empty database is created. How to sew a ready-made database into the application, already with certain data?
class SQLiteHelper(context: Context) :
SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION){
companion object{
private const val DATABASE_VERSION = 1
private const val DATABASE_NAME = "students.db"
private const val TBL_STUDENT = "tbl_student"
private const val ID = "id"
private const val NAME = "name"
private const val EMAIL = "email"
}
override fun onCreate(db: SQLiteDatabase?) {
val createTblStudent = ("CREATE TABLE " + TBL_STUDENT + "(" + ID
+ " INTEGER PRIMARY KEY, " + NAME + " TEXT," + EMAIL + " TEXT" + ")")
db?.execSQL(createTblStudent)
}
override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
db!!.execSQL("DROP TABLE IF EXISTS $TBL_STUDENT")
onCreate(db)
}
fun insertStudent(std: StudentModel): Long{
val db = this.writableDatabase
val contextValue = ContentValues()
contextValue.put(ID, std.id)
contextValue.put(NAME, std.name)
contextValue.put(EMAIL, std.email)
val success = db.insert(TBL_STUDENT, null, contextValue)
db.close()
return success
}
fun getAllStudent(): ArrayList<StudentModel>{
val stdList: ArrayList<StudentModel> = ArrayList()
val selectQuery = "SELECT * FROM $TBL_STUDENT"
val db = this.readableDatabase
val cursor: Cursor?
try{
cursor = db.rawQuery(selectQuery, null)
}catch (e: Exception){
e.printStackTrace()
db.execSQL(selectQuery)
return ArrayList()
}
var id: Int
var name:String
var email: String
if(cursor.moveToFirst()){
do{
id = cursor.getInt(cursor.getColumnIndex("id"))
name = cursor.getString(cursor.getColumnIndex("name"))
email = cursor.getString(cursor.getColumnIndex("email"))
val std = StudentModel(id = id, name = name, email = email)
stdList.add(std)
}while (cursor.moveToNext())
}
return stdList
}
fun updateStudents(std: StudentModel) : Int{
val db = this.writableDatabase
val contentValues = ContentValues()
contentValues.put(ID, std.id)
contentValues.put(NAME, std.name)
contentValues.put(EMAIL, std.email)
val success = db.update(TBL_STUDENT, contentValues, "id = " + std.id, null)
db.close()
return success
}
fun deleteStudentById(id: Int): Int{
val db = this.writableDatabase
val contentValues = ContentValues()
contentValues.put(ID,id)
val success = db.delete(TBL_STUDENT, "id=$id", null)
db.close()
return success
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question