Android Tutorial (Kotlin) – 30 – SQLite Database Creation and Insertion

Android Tutorial (Kotlin) – 30 – SQLite Database Creation and Insertion

Hi everyone, This is Vignesh from CodeAndroid In this video will see about SQLite Database Creating and Insertion If we want to store huge data and we need to do some searching or shorting we need to use SQLite Database Android natively supports SQLite Database we don’t need to add any other Library to use this To demonstrate this, I am Creating a new application namely SqliteExample with default configuration In this Example, I am going to store name and age in SQLite Database Open “activity_main.xml” Change to root Layout to LinearLayout and add orientation as vertical remove the views inside the root layout Inside Creating one more LinearLayout with width as “match_parent” and height as “wrap_content” Adding an EditText for name with margin and padding 10dp assigning id as “etvName” duplicate the EditText by Selecting the code and Press ctrl+d on your keyboard adding orientation as vertical for the LinearLayout change the second EditText id as etvAge Age must be number, So setting inputType as number Adding a Button, So that on click of this, we can insert the entered data into Database Setting margin and padding 10dp text as Insert and assigning id as “btn_insert” Creating new kotlin file to define the structure of User Object class User adding id, name and age attributes creating a constructor with name and age as parameters So that we can create a user object in single-line itself setting the parameters as attribute values to handle Database operations, we need a Handler class So Create a kotlin file We need some values like Database name,table name, column names etc. creating those variables. Create handler class as same as File Name with context as a parameter and, it extends SQLiteOpenHelper class inside we need to pass 4 parameters context, Database name, CursorFactory and Database version We are not going to use CursorFactory So passing null here. Giving Version as 1 we need to implement onCreate() and onUpgrade() from the base class This onCreate() will be executed, When the device doesn’t contain the Database So we need to create required tables here Here I am creating the table with id, name, and age as fields To execute query we need to use execSQL() Inside we need to pass the query string onUpgrade() will be executed, When we have a older version of Database You will get the oldVersion and currentVersion in this method itself using this we need to upgrade the table structure accordingly Creating a function insertData() to insert User object There are two types of SQLiteDatabase objects are there, 1.ReadableDatabase 2.WritableDatabase. Here we are going to Write the data into Database So get the WritableDatabse To insert into Database we need ConventValues So, create ConventValues inside we need to put our values cv.put “COL_NAME” should store cv.put “COL_AGE” should store user.age now we need to insert this ConventValues db.insert() inside we need to pass 3 parameters TABLE_NAME, null and ConventValues The second parameter is a String We need to pass any Column name here So that “null” will be stored in that column We don’t need any null column So we are passing null as Second Parameter this insert() will return rowID if the result is -1 then Some error is occurred so showing toast as “Failed” otherwise showing toast as “Success” Open “MainActivity.kt” setting the onclick listener for “btn_insert” if name and age-length is>0 then we need to insert the data into Database Otherwise showing error toast Otherwise showing error toast by passing the entered value inside the constructor and storing it into a variable called “user” creating the helper class object using this calling insertData() which we created early Let’s run the application. Entering the data and clicking on the “Insert” button we are getting toast as “Success” Which means the data is inserted successfully In next tutorial will see how to retrieve, update and delete the records from the database That’s all for this tutorial guys If you like this video, please give a thumbs up If you have any doubts, please put it in the comment section I will try to answer it Hope you like it I will see you in my next video Have a “GOOD DAY”

Daniel Ostrander

Related Posts

25 thoughts on “Android Tutorial (Kotlin) – 30 – SQLite Database Creation and Insertion

  1. Parth Aggarwal says:

    Thanks Bro for posting this video. I want more help in Kotlin. Can you help me on whatsapp. Please share your contact.

  2. Gustavo Ferri says:

    which day of the week do you put the videos?

  3. Dan Johnson says:

    This is a great tutorial!

  4. Ian Schoenrock says:

    Make sure that CREATE Table is not CREATE_TABLE. I made that mistake and it put me back an hour and a half. Needless to say I made a note of that.

  5. joel adela says:

    my app keeps on closing please help

  6. bhavin vala says:

    at com.example.user.sqliteexample.DataBaseHandler.onCreate(DataBaseHandler.kt:19)
    at com.example.user.sqliteexample.DataBaseHandler.insertData(DataBaseHandler.kt:28)
    at com.example.user.sqliteexample.MainActivity$onCreate$1.onClick(MainActivity.kt:20)
    my application keep closing

  7. Dan Naylor says:

    I am clicking "Insert" but I am getting "Failed", is my onCreate method not being called?

  8. bhavin vala says:

    com.example.user.sqliteexample E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.user.sqliteexample, PID: 3487
    android.database.sqlite.SQLiteException: AUTOINCREMENT is only allowed on an INTEGER PRIMARY KEY (code 1): , while compiling: CREATE TABLE Users(idINTEGER PRIMARY KEY AUTOINCREMENT,nameVARCHAR(256)ageINTEGER)
    at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
    at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(
    at android.database.sqlite.SQLiteConnection.prepare(
    at android.database.sqlite.SQLiteSession.prepare(
    at android.database.sqlite.SQLiteProgram.<init>(
    at android.database.sqlite.SQLiteStatement.<init>(
    at android.database.sqlite.SQLiteDatabase.executeSql(
    at android.database.sqlite.SQLiteDatabase.execSQL(
    at com.example.user.sqliteexample.DataBaseHandler.onCreate(DataBaseHandler.kt:19)
    at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(
    at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(
    at com.example.user.sqliteexample.DataBaseHandler.insertData(DataBaseHandler.kt:27)
    at com.example.user.sqliteexample.MainActivity$onCreate$1.onClick(MainActivity.kt:22)
    at android.view.View.performClick(
    at android.view.View$
    at android.os.Handler.handleCallback(
    at android.os.Handler.dispatchMessage(
    at android.os.Looper.loop(
    at java.lang.reflect.Method.invoke(Native Method)

  9. Anna Lu says:

    Voce e um deus

  10. Albertus Derry says:

    app keep stopping. tried to fetch the database from Device File Explorer to see whether table is created or not. Table not created, no matter how many times i tried to fix the sql command in "CREATE_TABLE". Any advice?

  11. Shreyas Waghmare says:

    How do i load the database from a .db file stored locally?

  12. kingo vid says:

    What if i wana create DB with multiple tables? like Table News, Table books

  13. Onur Aydeniz says:

    Thank You so much

  14. Евгений Моторин says:

    You forgot ";" in end createTable

  15. Random says:

    /? E/storaged: getDiskStats failed with result NOT_SUPPORTED and size 0
    /system_process E/memtrack: Couldn't load memtrack module it shows this error and keeps closing

  16. Anup Baghel says:

    You are great , efficient and fast thanks man.

  17. Sraavan reddy says:

    I feel you are under rated. You got so much of content Brother. All the best and Good Luck. Go ahead with other programming like iOS

  18. Mariah Medina says:

    Is it possible to create a table with more than three columns? Every time I try my application will not run.

  19. Muhammet Tan says:

    Great tutorial, very useful and clear

  20. Kyriafinis Bill says:

    I have a question I have around 7 variables in my class and I don't want to update them all at the same time in the data base do I need multiple insertData functions (one for every variable) and same for updating values ? Thanks in advance. Keep up the great tutorials!!

  21. Palak Pandya says:

    Hello sir thank u for ur video tutorial sir i m unable to run emulator plzz help me how shld i run my Android emulator sir reply it fast

  22. m.m. tmn says:

    ugh, i followed everything right, even made the two corrections you made(I had to pause and go back a few times btw), and, in the end, it shows there are 10 errors in your code.

    I hate that almost every android studio tutorial on youtube is full of errors and Android Studio keeps on going light bulb mode on: "well you there is a correct, better way to do this, here follow my suggestion" and the suggestions doesn't fix shit, or makes it worst.

    Android Studio is some hard shit to learn, but I'm not giving up. Thanks for the video "CodeAndroid".

    Let me ask you this: "Assignments are not expressions, and only expressions are allowed in this context", why does this keep alarming me there is something wrong with the code you showed us?

    Also, i got a big old, grey, squiggly line on this part of the code (your's is yellow, mine is grey):

    val createTable = "CREATE TABLE " + TABLE_NAME = " (" +


    COL_NAME + "VARCHAR(256)," +


    Android Studio suggests this me to "Convert concatenation to template" which doesn't fix much.

    MainActivity.kt there are some errors too. i wonder why this app is not working 100%, I wonder how you code could be fixed or if Android Studio is just crazy on calling out inconsistencies in code. Any language for Android Development isn't exactly easy, so don't worry about it, it's really cool that you are helping a lot of people in this darksouls of a quest into the mobile development word.

    Has anyone found some documentation on Android Studio and Kotlin? I would love to read that shit, thanks.

  23. Husni Marwan says:


  24. Rony BN says:

    OS error – 2 : No such file or directory When i click on button to save . Do you know what the error is about ? . Thanks n Great Video

  25. Kumar Krishna says:

    Hi Vignesh,
    I want to develop an app, can we collaborate and execute it.

Leave a Reply

Your email address will not be published. Required fields are marked *