Android Basics – Learn how to use the SQLiteOpenHelper class to setup App Database

SQLiteOpenHelper enables you to create and manage the database. To understand this better create a new class called SurveyDBHelper and extend this class.

In this class you will write the code to create the database tables needed for the Survey App.

public class SurveyDBHelper extends SQLiteOpenHelper

The Survey App will store the information in a survey table. The survey table will store – name, email and age.

It’s an Android convention to call your primary key columns _id.

Following are the data types that can be used

INTEGER – Numbers
TEXT – Character
REAL – Floating Points
NUMERIC – Booleans and Date
BLOB – Binary large object

Keeping this in mind you can use the CREATE TABLE SQL statement to create a new table.

@Override
public void onCreate(SQLiteDatabase db) {
 db.execSQL("CREATE TABLE "+SURVEY_TABLE+" (_id INTEGER PRIMARY KEY AUTOINCREMENT, "
 +SURVEY_TABLE_NAME_COLUMN+" TEXT, "
 +SURVEY_TABLE_EMAIL_COLUMN+" TEXT, "
 +SURVEY_TABLE_AGE_COLUMN+" INTEGER);"
 );
}

Follow the video to understand this better. 
Also the source code is available here for reference.


Android Basics : New App to demonstrate SQLite Database Concepts

To understand how to use SQLite with your App, you will be creating a new App.

The App will be called SurveyApp. And it will let users fill in few details and store it in the database.

Follow the video to get started. The new App source code is available here.

Android Basics – Introduction to SQLite Database

Why you need a Database?

A scenario can be if your app needs to store data. Like when a user registers then you can save the information for later use.

There can be other reasons also. For example if a user has weak or no network then your app can display the last saved data to the user.
What is SQLite Database?

Android comes with a lighweight database which can be used with your apps. SQLite is an open source lighweight database.

SQLite is a software library that implements a self-contained, serverless, zero-configuration, transactional SQL database engine.

Why use SQLite?

1. It’s lightweight – It uses a file to store data. So no processing time is needed and hence you conserve battery.

2. It’s fast and stable and can handle transactions.

3. It’s optimized for a single user.

How does SQLite store data?

Android creates a data folder for each app where the files reside. Two files are created to store the data.

/data/data/{unique-domain-name}/databases/example-db

This folder can only be accessed by the App.

Reference –¬†https://www.sqlite.org/