简体   繁体   中英

Can't Insert data into SQLite-Kotlin-Android

I try to run this code, every thing is OK. I checked every variable. It takes and pass data. The table was created in my database. After running there is no error messages. When i click insert button it give me (Failed) as i coded if insert data fail. The table is empty! I tried every thing but with out success!

package com.example.myapplication
class User{
var id:Int=0
var name:String=""
var age:Int=0
    constructor(name:String, age:Int){
        this.name=name
        this.age=age}
constructor(){}
}

package com.example.myapplication

import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.widget.Toast

val DATABASE_NAME="MyDB"
val TABLE_NAME="Users"
val COL_NAME="name"
val COL_AGE="age"
val COL_ID="id"
class DataBaseHandler(var context: Context):SQLiteOpenHelper(context, DATABASE_NAME,null,1) {
    override fun onCreate(db: SQLiteDatabase?) {
        val creatTable="CREATE TABLE "+ TABLE_NAME+" ("+
                COL_ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+
                COL_NAME+" VARCHAR(256),"+
                COL_AGE +" INTEGER)";
        db?.execSQL(creatTable)
    }

    override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
    }
    fun insertData(user:User){
        val db=this.writableDatabase
        var cv=ContentValues().apply {
            put(COL_NAME,user.name)
            put(COL_AGE,user.age) }
        var result=db?.insert(TABLE_NAME,null,cv)
  if (result==-1.toLong())
            Toast.makeText(context,"Failed", Toast.LENGTH_SHORT).show()
        else
          Toast.makeText(context,"Success",Toast.LENGTH_SHORT).show()
    }

    fun readData():MutableList<User>
    {
var list:MutableList<User> = ArrayList()
        val query="SELECT * FROM " + TABLE_NAME
        val db=this.readableDatabase
        val result= db.rawQuery(query,null)
       if(result.moveToNext()){
        do{
                var user=User()
                user.id=result.getString(result.getColumnIndex(COL_ID)).toInt()
                user.name=result.getString(result.getColumnIndex(COL_NAME))
                user.age=result.getString(result.getColumnIndex(COL_AGE)).toInt()
                list.add(user)
           }
              while (result.moveToNext())
         }
        result.close()
      db.close()
       return list
    }
}

package com.example.myapplication
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val context= this
        var db=DataBaseHandler(context)
        val etvName:TextView=findViewById(R.id.etvName)
        val etvAge:TextView=findViewById(R.id.etvAge)
        val btn_insert:Button = findViewById(R.id.btn_insert)
        btn_insert.setOnClickListener {
            if(etvName.text.toString().length>0 &&etvAge.text.toString().length>0){
                var user=User(etvName.text.toString(),etvAge.text.toString().toInt())
                db.insertData(user)
}
            else(Toast.makeText(context,"Please fill all data",Toast.LENGTH_SHORT).show())
        }
        val btn_read:Button
        btn_read=findViewById(R.id.btn_read)
        btn_read.setOnClickListener {
        var data=db.readData()
        val tvResult:TextView
        tvResult=findViewById(R.id.tvResult)
    for (i in 0..data.size-1){
        tvResult.append(data.get(i).id.toString() + "  " + data.get(i).name + "  " + data.get(i).age)
    }
}
    }
}
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <EditText
        android:id="@+id/etvName"
        android:layout_width="140dp"
        android:layout_height="71dp"
        android:text="Name"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.174"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.042" />
    <EditText
        android:id="@+id/etvAge"
        android:layout_width="138dp"
        android:layout_height="75dp"
        android:text=""
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.857"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.035"
        tools:text="Age" />
    <Button
        android:id="@+id/btn_insert"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="insert"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.495"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.169"
        tools:ignore="MissingConstraints" />
    <Button
        android:id="@+id/btn_read"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Display"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.123"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.256"
        tools:ignore="MissingConstraints" />
    <Button
        android:id="@+id/btn_update"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="update"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.256"
        tools:ignore="MissingConstraints" />

    <Button
        android:id="@+id/btn_delete"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="delete"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.879"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.256"
        tools:ignore="MissingConstraints" />
    <TextView
        android:id="@+id/tvResult"
        android:layout_width="368dp"
        android:layout_height="46dp"
        android:gravity="center"
        android:text="TextView"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.627"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.411" />
</androidx.constraintlayout.widget.ConstraintLayout>

I recommend you to use Room library, it's the easiest way to deal with database. Here's the link that you can learn on:

https://developer.android.com/codelabs/android-room-with-a-view-kotlin#0

And one thing, if you use kotlin, don't make constructor in your User class (i guess it's a model). just use data class, and it automatically create constructor in background.

data class User(var id:Int=0,
                var name:String="",
                var age:Int=0)

kotlin makes easy codes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM