How to save data into SQLite from Android App

While developing the app you might have thought about how to deal with the database. You can work with either online(MySql) database or with an offline(SQLite) database. SQLite is the database that is used to store app data and comes with Android OS. Here you can deal with the database without requiring the internet connection.

When the term Database comes in mind this must be the next thinking, how to accomplish CURD(Create, Update, Read,  Delete) operations. We will see one by one so that you can get it clearly. Here I am going to explain how to store data into SQLite from Android App.

I am creating a table that will store a sample blog post into SQLite.

Step 1. Create a new project in Android having name WorkingWithSqlite.

Step 2. Create a Post class having post details variables and its getter and setter methods.

Step 3. Open activity_main.xml from res package and copy the below code.

This will create the layout as shown below:

layout activity_main.xml
layout activity_main.xml

Step 4. For dealing with SQLite, I am creating a separate class called DBHandle which extends  SQLiteOpenHelper. It will give an error until we import its method. These are as below:

onCreate(): This method is called when the database is created. In this method query for creating table is written.

onUpgrade(): This method is called when the database is upgraded that is when there are any changes in the database table.

Here onCreate() and onUpgrade() method will remain same for CURD operation.

Step 5. Open and copy the below code.

Step 6. Now add the below code in This code will deal with adding the entry to the table and return whether the record is inserted into the table or not.

So the finale DBHandler will be as below:

Step 6.  This will be the AndroidManifest.xml.

Step 7. Finally, run your project you will be having following output.

Record storing to the sqlite
Record storing to the SQLite

Here the data is entered to the Sqlite. In the upcoming post, I will show you how to check the SQLite database. I hope you did it successfully and have the correct output. for any query comment below.