Skip to main content

SQLite database

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

https://www.studytutorial.in/android-sqlite-database-to-saving-data-in-android-device-tutorial

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.
1
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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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.
1
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.
1
2
3
4
5
6
7
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.
1
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.
1
2
3
4
5
6
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.
1
2
3
4
5
6
7
8
9
10
11
12
13
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.
1
2
3
4
5
6
7
8
9
10
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.
1
2
3
4
5
6
public Integer deleteUser (Integer id){
    SQLiteDatabase db = this.getWritableDatabase();
    return db.delete(table_name,
           "id = ? ",
           new String[] { Integer.toString(id) });
}

Comments

Popular posts from this blog

Android Bar Chart Using MpAndroidChart Library Tutorial

https://www.numetriclabz.com/android-bar-chart-using-mpandroidchart-library-tutorial/ Android Bar Chart Using MpAndroidChart Library Tutorial Objective In this tutorial we learn how to implement Bar Chart using MpAndroidChart Library in your Android App. Download Source Code       Step 1 Contents ·        1  Introduction ·        2  Creating Bar chart o    2.1  Create a new Project o    2.2  Adding library in Project o    2.3  Create Layout o    2.4  To Plot Bar Chart §   2.4.1  Initialize the graph id §   2.4.2  Creating a Dataset §   2.4.3  Defining X-axis labels §   2.4.4  Set the data §   2.4.5  Add the description to the chart §   2.4.6  Run your App § ...

Codelabs for Android Developer Fundamentals (V2)

Android fundamentals 09.2: App settings https://codelabs.developers.google.com/codelabs/android-training-adding-settings-to-app/index.html?index=..%2F..android-training#10 To find the next practical codelab in the Android Developer Fundamentals (V2) course, see  Codelabs for Android Developer Fundamentals (V2) . For an overview of the course, including links to the concept chapters, apps, and slides, see  Android Developer Fundamentals (Version 2) . Viedo Book PDF https://developer.android.com/courses/fundamentals-training/toc-v2 https://google-developer-training.github.io/android-developer-fundamentals-course-concepts-v2/index.html This page lists the practical codelabs that are included in the Android Developer Fundamentals (V2) course. For links to the concept chapters, slides, and apps that accompany these codelabs, see the  course overview . https://developer.android.com/courses/fundamentals-training/toc-v2 https://github.co...

Audio in Android& MediaPlayer

  MainActivity.java <code> package com.example.myapplication; import androidx.appcompat.app. AppCompatActivity; import android.media.AudioManager; import android.media.MediaPlayer; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super .onCreate( savedInstanceState); setContentView(R.layout. activi ty_main ); try { Uri uri = Uri. parse ( " https:// freetestdata.com/wp-content/ uploads/2021/09/Free_Test_ Data_100KB_OGG.ogg " ); MediaPlayer player = new MediaPlayer(); player.setAudioStreamType( AudioManager. STREAM_MUSIC ); player.setDataSource( this ,uri) ; player.prepare(); player.start(); } catch (Exception e) { ...