Android SQLite Database to Saving Data in Android Device Tutorial

0

This tutorial explains, how to use the SQLite database in Android applications.

Introduction

Android provides internally database to store data. SQLite Database is one of the way to store data. SQLite Database is the open source to store data in a Text file on a Device. It supports standard relational database features like SQL syntax, transactions and prepared statement.

In this tutorial describes how to create Database on Android Device & how to Insert, Select, Update, Delete data. We will create a new Database, Database name is studytutorial and its table name is users. Table Structure given below:
Android table structure



Create a new project

We are going to create a new android project. Go to File ⇒ New ⇒ New Projects in Android studio.

Create DBHelper Class

We need to create a class named as DBHelper. It handle all database operations like Create, Select, Update, Delete Etc.

Extend SQLiteOpenHelper

Extend your DBHelper.java class from SQLiteOpenHelper.

public class DBHelper extends SQLiteOpenHelper {

Override onCreate() and onUpgrade()

onCreate() method need to call when database creation and onUpgrade() method is called when database is upgrading such as modify table structure, adding constraints to database etc. Also create a constructor which has parameter as context. In this constructor, we will pass the context, Database Name, NULL & Database Version in the super() method.

public class DBHelper extends SQLiteOpenHelper {

    public static final String DATABASE_NAME = "studytutorial";
    private static final int DATABASE_VERSION = 1;
    public String table_name = "users";

    public DBHelper(Context context) {
        super(context, DATABASE_NAME , null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(
                "CREATE TABLE IF NOT EXISTS " + table_name +
                        "(id integer primary key, user_name text, phone_number text)"
        );
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + table_name);

    }
}

Call DBHelper Class

We need to initialize DBHelper Class to create Table from Activity Class.

DBHelper dbHelper = new DBHelper(this);

Create insertData() method (Inserting New Record)

To insert new record in the database, we need to create insertData() method in the DBHelper class. In this method, we will initialize ContentValues() object and put the values as column name and its value. Call the insert method with table name, null and ContentValues object as parameter.

public void insertData(){
        SQLiteDatabase db1 = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put("user_name", "Abhay");
        contentValues.put("phone_number", "9971634265");
        db1.insert(table_name, null, contentValues);
}


Call insertData() method

To insert new data in the table, we need to call insertData() method from Activity Class. We have already initialize DBHleper class in the Activity Class. Hence use below code.

dbHelper.insertData();

Select Data

To select data, we need create a new method getuser(). In this method, we will use Cursor. We will write raw query just like Mysql command.

public Cursor getuser() {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor res = db.rawQuery("select * from " + table_name + " ",
                null);
        return res;
}

Call getuser() method (Reading Data)

To print data, we need to call getuser() method from Activity Class.

final Cursor cursor = dbHelper.getuser();
if (cursor.moveToFirst()) {
       do {
           String userName = cursor.getString(cursor.getColumnIndex("user_name"));
           String phoneNumber = cursor.getString(cursor.getColumnIndex("phone_number"));
           Toast.makeText(getApplication(), 
           " SQL Data UserName "+  userName + 
           " Phone Number" + phoneNumber, Toast.LENGTH_SHORT).show();

      } while (cursor.moveToNext());
}
//closing cursor
cursor.close();

Update Data

To update data, we will create a new method updateUser() in the DBHelper Class. In this method, we will update single user details.

public boolean updateUser (Integer id, String userName, String phone){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put("user_name", userName);
        contentValues.put("phone_number", phone);
        db.update(table_name, 
        contentValues, "id = ? ",
        new String[] { Integer.toString(id) } );
        return true;
}

Delete Data

To delete data, we will create a new method deleteUser() in the DBHelper CLass.

public Integer deleteUser (Integer id){
    SQLiteDatabase db = this.getWritableDatabase();
    return db.delete(table_name,
           "id = ? ",
           new String[] { Integer.toString(id) });
}