This is the second part of SQLite for Android series tutorials with examples. Here you can find the first part – SQLite for Android Part 1: Creating DB and Table

In this example is explained hot to insert data in to already created database and table.

NOTE: Dont forget to add ButterKnife binding in onCreate() in MainActivity:

After creating Person.db file and student_table, now we are going to insert some data in it.

Layout create:


We need fields to input text for insert in to the database

Insert method:

Create insertData() method which returns boolean and receives three argument of String type, name, lastName and dateOfBirth:

Here we create the instance of SQLite databas (in previous tutorial created in the constructor just for tutorial scenarion)

We need to create ContentValue object so we can put values in it:

In contentValues .put() value in to table by passing argument one COLUMN and argument two, the actual data (name, lastName,…). Now, the created contentValues are inserted into our database, previously created:

But because we are building boolean method, and need to know if values are inserted in to the database, we need to get the return value of .insert() method. This method returns inserted row value or -1 if data is not inserted. We are going to GET the returned value and store in to a long variable:

With this insertResult we can check if the data is entered correctly or not

Main Activity

In MainActivity initialize edit texts and button for adding the values entered in edit text fields:

Insert Button Click

In onAddClick() implement adding data to database table. First we check if edit text fields are null or empty. After that, we assign value to boolean isDataInserted by calling previously created dataBase object and its .insertData() method. Then we check the value of isDataInserted. If it is true, show success Toast message, if not show fail message:


You can get the whole project on GitHub /SQLiteDatabaseAndroid

Spread the love

Leave a Reply

Your email address will not be published.