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 syntaxtransactions 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 contextDatabase NameNULL & 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 namenull 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

web2apk

http://web2apk.com/create.aspx Create App   Intro   About   Changes   MalWare ?   Contact   Privacy Useful Links Bluetooth Mini Keyboards Android Mini PC Reset Android URL App Title Icon or

how to retrieve image from sqlite database in android and display in listview

 Android platform provides several ways to store data in our application. 1. SQLite database 2. SharedPreferences etc For our post, we will only work with SQLite database. First and foremost, we need to understand what an SQLite database is? SQLite database  is an open source SQL database that stores data to a text file on a device. It executes SQL Commands to perform a set of functions, that is, create, read, update and delete operations. On my previous post, I showed how to  store data in SQLite database from edit text, retrieve and populate it in a listview . For this post, I will show the SQLite CRUD operations with images from gallery and text from EditText. We need to understand this; images are stored in SQLite database as BLOB data type. A BLOB is a large binary object that can hold a variable amount of data.  Note, we can only store images in the database as BLOB data type. We need to convert our image path to a bitmap then to bytes. Also

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 §   2.4.7  Set the color §   2.4.8  Adding Animations o    2.5  To plot grouped bar chart §   2.5.1  Creating Dataset o    2.6  Get the best of Android plus exclusive deals and freebies in your inbox!