S
S
sanke462017-11-18 10:57:54
Java
sanke46, 2017-11-18 10:57:54

What is the correct way to write SQLiteOpenHelper with one parameter [Kotlin]?

Gives an error , First time I write SQLite on kotlin and did not find a solution to the problem

class DataBase(context: Context?, name: String?, factory: SQLiteDatabase.CursorFactory?, version: Int) : SQLiteOpenHelper(context, name, factory, version) {

    val DATABASE_VERSION = 1
    val DATABASE_NAME = "Name"
    private val TABLE_NAME = "DeviceName"

    private val KEY_NAME = "name"

    private val TEXT_TYPE = " TEXT"
    private val SQL_CREATE_ENTRIES = "CREATE TABLE " + TABLE_NAME + " (" + KEY_NAME + TEXT_TYPE  + " )"
    private val SQL_DELETE_ENTRIES = "DROP TABLE IF EXISTS " + DATABASE_NAME

    override fun onCreate(sqLiteDatabase : SQLiteDatabase?) {
        sqLiteDatabase?.execSQL(SQL_CREATE_ENTRIES)
    }

    override fun onUpgrade(sqLiteDatabase : SQLiteDatabase?, p1: Int, p2: Int) {
        sqLiteDatabase?.execSQL(SQL_DELETE_ENTRIES)
        onCreate(sqLiteDatabase)
    }

    fun addDevice(device: String) {
        val db = this.writableDatabase
        val values = ContentValues()
        values.put(KEY_NAME, device)
        db.insert(TABLE_NAME, null, values)
        db.close()
    }

    fun getNameDevice() : String {

        val selectQuery = "SELECT * FROM " + DATABASE_NAME
        val db = this.writableDatabase
        val cursor = db.rawQuery(selectQuery, null)
        var device : String

        device = cursor.getString(0)
        cursor.close()

        return device
    }

    override fun getWritableDatabase(): SQLiteDatabase {
        return super.getWritableDatabase()
    }
}

// MainActivity
        var db : DataBase
        var nameDevice : String
        db = DataBase(this, "Name", null, 1)
        db.addDevice("Samsung A5")
        nameDevice = db.getNameDevice()
        println("!!!!!!!!!!!!" + nameDevice + "!!!!!!!!!!!!!!")

mistake :
java.lang.RuntimeException: Unable to start activity while compiling: SELECT * FROM Name

Answer the question

In order to leave comments, you need to log in

1 answer(s)
1
1001001, 2017-11-18
@sanke46

At a minimum, you forgot to move the cursor to the starting position
and also the data from the database, not the table, drag val selectQuery = "SELECT * FROM " + DATABASE_NAME

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question