DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Designing a Blog Application Using Document Databases
  • Relational DB Migration to S3 Data Lake Via AWS DMS, Part I
  • NoSQL for Relational Minds
  • Business Logic Database Agent

Trending

  • Integrating Model Context Protocol (MCP) With Microsoft Copilot Studio AI Agents
  • Metrics at a Glance for Production Clusters
  • Manual Sharding in PostgreSQL: A Step-by-Step Implementation Guide
  • How to Perform Custom Error Handling With ANTLR
  1. DZone
  2. Data Engineering
  3. Databases
  4. SQLiteOpenHelper and Database Inspector in Android

SQLiteOpenHelper and Database Inspector in Android

Let's dive into using SQLite and Database Inspector for your next Android app.

By 
Thomas Plathanath Mathew user avatar
Thomas Plathanath Mathew
·
Apr. 11, 21 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
14.7K Views

Join the DZone community and get the full member experience.

Join For Free

What Is SQLite?

SQLite is an open-source relational database, similar to MySQL. Android includes a SQLite library in its standard library that implements a serverless, zero-configuration, and transactional SQL database engine. SQLite does not run on a database server, but stores all its data in simple files. A complete SQLite database with many tables, triggers, indices, and views is contained in a single disk file. SQLite is built into all mobile phones and most computers and comes bundled inside. It carries lightweight data and does not require any administration or setup procedure of the database. 

The package android.database.sqlite.SQLiteDatabase consists of all the APIs to perform CRUD operations from our android application. 

SQLiteOpenHelper

SQLiteOpenHelper is an in-built class of android.database.sqlite.SQLiteDatabase package. It is a helper class to manage SQLite database creation and version management. The helper class manages the creation of the database, handling database manipulations, and also the version management.  We need to create a subclass extending from SQLiteOpenHelper class for database manipulations. In this class, we will implement two overridden methods onCreate( ) and onUpgrade( ). These classes take care of opening the database if it exists, creating it if it does not, and upgrading it as necessary.  

onCreate( ) method

The onCreate( ) is called when the database is created for the first time. It is called only once throughout the entire application lifecycle. It will be called whenever there is a first call to getReadableDatabase( ) or getWritableDatabase( ) function. These functions are available in the super SQLiteOpenHelper class. 

The below statement instantiates an object of the SQLiteOpenHelper class and calls its constructor. 

Java
 




xxxxxxxxxx
1


 
1
DatabaseHelper dbh= new DatabaseHelper(getApplicationContext());



Java
 




xxxxxxxxxx
1


 
1
public DatabaseHelper(Context context) {
2
    super(context,dbName,null,version);
3
    context=this.context;
4

          
5
}



SQLiteOpenHelper class call the onCreate( ) method after creating database and instantiate SQLiteDatabase object. The onCreate( ) method is called only once when the database is created for the first time.

Java
 




xxxxxxxxxx
1
10


 
1
@Override
2
public void onCreate(SQLiteDatabase db) {
3

          
4
    try {
5
        db.execSQL(CREATE_TABLE);
6
    } catch (Exception e) {
7

          
8
    }
9

          
10
}



onUpgrade( ) method

The onUpgrade( ) method is called when the database needs to be upgraded. It is called when the database file already exists, and we want to upgrade its version.

Java
 




xxxxxxxxxx
1


 
1
@Override
2
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
3
    db.execSQL(DROP_TABLE);
4
    onCreate(db);
5
}



Now we will create a simple Android application to demonstrate the SQLiteOPneHelper class. This application inserts employee records into a table 'Empdata' in a SQLite database 'Company.db' using the SQLiteOpenHelper class.

We have a very simple UI designed as below in the activity_main.xml

MainActivity.java

Java
 




xxxxxxxxxx
1
34


 
1
package www.sqliteopenhelper.sqliteopenhelper;
2

          
3
import androidx.appcompat.app.AppCompatActivity;
4
import android.os.Bundle;
5
import android.view.View;
6
import android.widget.Button;
7
import android.widget.EditText;
8
import android.widget.Toast;
9

          
10
public class MainActivity extends AppCompatActivity {
11

          
12
    @Override
13
    protected void onCreate(Bundle savedInstanceState) {
14
        super.onCreate(savedInstanceState);
15
        setContentView(R.layout.activity_main);
16

          
17
        EditText edtEmpName = findViewById(R.id.edtName);
18
        EditText edtDesig = findViewById(R.id.edtDesig);
19
        EditText edtSalary = findViewById(R.id.edtSalary);
20
        Button btnSave = findViewById(R.id.btnSave);
21
        DatabaseHelper dbh= new DatabaseHelper(getApplicationContext());
22
        btnSave.setOnClickListener(new View.OnClickListener() {
23
            @Override
24
            public void onClick(View view) {
25
                   Employee objEmp = new Employee(edtEmpName.getText().toString(),edtDesig.getText().toString(),Integer.parseInt(edtSalary.getText().toString()));
26

          
27
                if(dbh.InsertEmployee(objEmp))
28
                    Toast.makeText(getApplicationContext(),"Record inserted successfully",Toast.LENGTH_LONG).show();
29
                else
30
                    Toast.makeText(getApplicationContext(),"Record not inserted",Toast.LENGTH_LONG).show();
31
            }
32
        });
33
    }
34
}



Employee.java

Java
 




xxxxxxxxxx
1
42


 
1
package www.sqliteopenhelper.sqliteopenhelper;
2

          
3
public class Employee {
4
    private String employeeName;
5
    private String employeeDesig;
6
    private int employeeSalary;
7

          
8
    public Employee() {
9
    }
10

          
11
    public Employee(String employeeName, String employeeDesig, int employeeSalary) {
12
        this.employeeName = employeeName;
13
        this.employeeDesig = employeeDesig;
14
        this.employeeSalary = employeeSalary;
15
    }
16

          
17

          
18
    public String getEmployeeName() {
19
        return employeeName;
20
    }
21

          
22
    public String getEmployeeDesig() {
23
        return employeeDesig;
24
    }
25

          
26
    public int getEmployeeSalary() {
27
        return employeeSalary;
28
    }
29

          
30
    public void setEmployeeName(String employeeName) {
31
        this.employeeName = employeeName;
32
    }
33

          
34
    public void setEmployeeDesig(String employeeDesig) {
35
        this.employeeDesig = employeeDesig;
36
    }
37

          
38
    public void setEmployeeSalary(int employeeSalary) {
39
        this.employeeSalary = employeeSalary;
40
    }
41

          
42
}



DatabaseHelper.java

Java
 




x
61


 
1
package www.sqliteopenhelper.sqliteopenhelper;
2

          
3
import android.content.ContentValues;
4
import android.content.Context;
5
import android.database.sqlite.SQLiteDatabase;
6
import android.database.sqlite.SQLiteOpenHelper;
7

          
8
public class DatabaseHelper extends SQLiteOpenHelper {
9
    public static final int version = 1;
10
    public  static String dbName="Company.db";
11
    public static final String TABLE_NAME ="Empdata";
12
    public static final String COL1 = "id";
13
    public static final String COL2 = "name";
14
    public static final String COL3 = "designation";
15
    public static final String COL4 = "salary";
16
    private static final String CREATE_TABLE="create table if not exists "+ TABLE_NAME + "(" + COL1 + " INTEGER PRIMARY KEY AUTOINCREMENT,"+COL2+" TEXT NOT NULL,"
17
            + COL3 + " TEXT, " +COL4 + " INTEGER);";
18
    private static final String DROP_TABLE = "DROP TABLE IF EXISTS "+ TABLE_NAME;
19

          
20
    private Context context;
21

          
22
    public DatabaseHelper(Context context) {
23
        super(context,dbName,null,version);
24
        context=this.context;
25

          
26
    }
27

          
28
    @Override
29
    public void onCreate(SQLiteDatabase db) {
30

          
31
        try {
32
            db.execSQL(CREATE_TABLE);
33
        } catch (Exception e) {
34

          
35
        }
36
    }
37

          
38
    @Override
39
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
40
        db.execSQL(DROP_TABLE);
41
        onCreate(db);
42
    }
43

          
44
    public boolean InsertEmployee(Employee objEmp)
45
    {
46
        SQLiteDatabase db=this.getWritableDatabase();
47
        ContentValues cv = new ContentValues();
48
        cv.put(COL2,objEmp.getEmployeeName());
49
        cv.put(COL3,objEmp.getEmployeeDesig());
50
        cv.put(COL4,objEmp.getEmployeeSalary());
51
   
52
        long result = db.insert(TABLE_NAME,null,cv);
53
        if(result == -1)
54

          
55
            return false;
56
        else
57
            return true;
58
    }
59

          
60

          
61
}



We can see that the DatabaseHelper class is extended from SQLiteOpenHelper. The SQLiteOpenHelper class has different in-built methods for inserting, updating, reading, and deleting records. 

After the database has been created we need to create and update fields. We can use a ContentValues object, which stores keys and values. ContentValues is a name-value pair, used to insert or update values into database tables. ContentValues object will be passed to SQLiteDataBase objects insert( ) and update( ) functions. 

Database Inspector in Android Studio

Database Inspector allows us to inspect, query, and modify our app's databases while our app is running. The database inspector is available in Android Studio 4.1 and higher. This is especially useful for database debugging. The Database Inspector works with plain SQLite and with libraries built on top of SQLite, such as Room. The Database Inspector only works with the SQLite library included in the Android operating system on API level 26 and higher.  

To open a database in the Database Inspector, do the following:

  1. Run the app on an emulator or connected device running API level 26 or higher.
  2. Select View > Tool Windows > Database Inspector from the menu bar.
  3. Select the running app process from the dropdown menu.
  4. The databases in the currently running app appear in the Databases pane. Expand the node for the database that we need to inspect.












Note: A known issue related to the Android 11 emulator causes apps to crash when connecting to the DB Inspector. To fix the issue, follow these steps.

Database Relational database Android (robot)

Opinions expressed by DZone contributors are their own.

Related

  • Designing a Blog Application Using Document Databases
  • Relational DB Migration to S3 Data Lake Via AWS DMS, Part I
  • NoSQL for Relational Minds
  • Business Logic Database Agent

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!