SQLite Database Connectivity in Android

 SQLite Database Connectivity in Android



 Introduction

In this post, we will see how to create an SQLite database in an Android application. We will also see how to add records to the database and read and display in an application.

 SQLiteDatabase

 In Android, the SQLiteDatabase namespace defines the functionality to connect and manage a database. It provides functionality to create, delete, manage and display database content.

Create a Database

 Simple steps to create a database and handle are as follows.

    1. Create "SQLiteDatabase" object.
    2. Open or Create a database and create a connection.
    3. Perform insert, update or delete operation.
    4. Create a Cursor to display data from the table of the database.
    5. Close the database connectivity.
    6. Following tutorial helps you to create a database and insert records in it.

Step 1: Instantiate "SQLiteDatabase" object: SQLiteDatabase db;  
  • Before you can use the above object, you must import the android.database.sqlite.SQLiteDatabase namespace in your application.
db=openOrCreateDatabase(String path, int mode, SQLiteDatabase.CursorFactory factory) 
  • This method is used to create/open database. As the name suggests, it will open a database connection if it is already there, otherwise, it will create a new one.
  • Example:
db=openOrCreateDatabase("XYZ_Database",SQLiteDatabase.CREATE_IF_NECESSARY,null); 
  • Arguments:
    • Int mode: operating mode. Use 0 or "MODE_PRIVATE" for the default operation, or "CREATE_IF_NECESSARY"  if you like to give an option that "if a database is not there, create it"
    • CursorFactory factory: An optional factory class that is called to instantiate a cursor when a query is called.

Step 2: Execute DDL command: db.execSQL(String sql) throws SQLException 

  • This command is used to execute a single SQL statement that doesn't return any data means other than SELECT or any other.

            db.execSQL("Create Table Temp (id Integer, name Text)"); 

  • In the above example, it takes "CREATE TABLE" statement of SQL. This will create a table of "Integer" & "Text" fields.
  • Try and Catch block is required while performing this operation. An exception that indicates there was an error with SQL parsing or execution. 

Step 3: Create an object of "ContentValues" and Initiate it.: ContentValues values=new ContentValues(); 
  • This class is used to store a set of values. We can also say, it will map ColumnName and relevant ColumnValue.
  • Example:
                        values.put("id", eid.getText().toString());           
                        values.put("name", ename.getText().toString());  
  • Arguments:
                        String Key: Name of the field as in table. Ex. "id", "name"
                        String Value: Value to be inserted.
Step 4: Perform Insert Statement: insert(String table, String nullColumnHack, ContentValues values)  
Arguments:
                        String table: Name of table related to the database.
                        String nullColumnHack: If not set to null, the nullColumnHack parameter provides the name of nullable column name to explicitly insert a NULL into in the case where your values is empty.
                        ContentValues values: This map contains the initial column values for the row.This method returns a long. The row ID of the newly inserted row, or -1 if an error occurred.
Example:
                db.insert("temp", null, values); 

Step 5: Create Cursor
This interface provides random read-write access to the result set returned by a database query.
Cursor c=db.rawQuery(String sql, String[] selectionArgs) 
Arguments:
Strign sql: The SQL query
String []selectionArgs: You may include ?s in where clause in the query, which will be replaced by the values from selectionArgs. The values will be bound as Strings.
Example:
Cursor c=db.rawQuery("SELECT * FROM temp",null); 
Methods:  
moveToFirst: Moves cursor pointer at a first position of a result set
moveToNext: Moves cursor pointer next to the current position.
isAfterLast: Returns false, if the cursor pointer is not atlast position of a result set.
Example:
c.moveToFirst();  
while(!c.isAfterLast())  
{  
c.moveToNext();  

Step 6: Close Cursor and Close Database connectivity 

Note:

  1. If you want to see where your database stored? Follow below instruction.
  2. Start Your Emulator ( It is necessary to start Emulator to see File Explorer content)  
  3. Open "Device File Explorer"
  4. Data -> Data -> find your "package" -> databases -> "database"

Summary: 

SQLiteDatabase provides so much functionality to create and manage databases. In this post, we learned how to create a new database, connect to it and read and display data.

Thanks a lot for query or your valuable suggestions related to the topic.

Previous Post Next Post

Contact Form