My app will successfully build the SQLite database and insert data but when viewing it's empty apart from the column headings.
Permissions in manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
QuoteDatabaseHandler
creates columns ID
and QUOTE
:
val QUOTEDATABASE = "QUOTE DATABASE"
val QUOTETABLE = "QUOTE_TABLE"
val COL_ID = "ID"
val COL_QUOTE = "QUOTE"
class QuoteDatabaseHandler (context: Context) : SQLiteOpenHelper (context, QUOTEDATABASE, null, 4) {
override fun onCreate(db: SQLiteDatabase?) {
val createTable = ("CREATE TABLE $QUOTETABLE (COL_ID INTEGER PRIMARY KEY AUTOINCREMENT,COL_QUOTE TEXT)")
db?.execSQL(createTable)}
Insert function:
fun insertQuote (quote:String){
val database = this.writableDatabase
val contentValues = ContentValues()
contentValues.put(COL_ID, 1)
contentValues.put(COL_QUOTE, quote)
database.insert(QUOTETABLE, null, contentValues)
database.close() }
dbHelper
is called within Oncreate
:
val dbHelper = QuoteDatabaseHandler(this)
Along with the insert method:
dbHelper.insertQuote("Example Quote 1")
CodePudding user response:
Your CREATE TABLE
statement is wrong because it creates the table with columns named COL_ID
and COL_QUOTE
and not the correct names ID
and QUOTE
.
Use string interpolation for the column names:
val createTable = "CREATE TABLE $QUOTETABLE ($COL_ID INTEGER PRIMARY KEY AUTOINCREMENT, $COL_QUOTE TEXT)"
You will also have to uninstall the app from the device and rerun to recreate the table with the correct column names.