w3resource

A Complete Guide to SQLite Integration in Android


SQLite in Android: A Complete Guide

SQLite is a lightweight database engine built into Android, making it an excellent choice for local data storage in mobile applications. Android provides native support for SQLite, enabling developers to store structured data, execute queries, and manage relational data efficiently. With SQLite in Android, you can create and manage databases to store application-specific data like user preferences, app configurations, and offline content.


Key Features of SQLite in Android

    1. Lightweight: Operates without a dedicated server or additional setup.

    2. Integrated: Comes pre-installed with Android, eliminating dependency management.

    3. Relational Data Storage: Supports SQL syntax for complex queries and relationships.

    4. Local Storage: Ideal for offline use cases like caching and user data persistence.

    5. Secure: Data can be encrypted for security.


Using SQLite in Android Applications

Steps to Use SQLite in Android

    1. Create a Database: Extend the SQLiteOpenHelper class to define a database and manage its lifecycle.

    2. Define Tables: Use SQL queries to create, update, and manage tables.

    3. Perform CRUD Operations: Implement Create, Read, Update, and Delete operations using SQL queries.



Example: SQLite Integration in Android

Creating a Database Helper Class

Code:

// Import necessary packages
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

// Define a helper class to manage database creation and updates
public class MyDatabaseHelper extends SQLiteOpenHelper {

    // Define database constants
    private static final String DATABASE_NAME = "example.db";  // Database name
    private static final int DATABASE_VERSION = 1;            // Database version

    // Define table and column constants
    public static final String TABLE_NAME = "users";           // Table name
    public static final String COLUMN_ID = "id";               // ID column
    public static final String COLUMN_NAME = "name";           // Name column
    public static final String COLUMN_AGE = "age";             // Age column

    // SQL query to create the table
    private static final String CREATE_TABLE =
        "CREATE TABLE " + TABLE_NAME + " (" +
        COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
        COLUMN_NAME + " TEXT, " +
        COLUMN_AGE + " INTEGER);";

    // Constructor
    public MyDatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    // Called when the database is created
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE);  // Execute table creation SQL
    }

    // Called when the database version changes
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);  // Drop old table
        onCreate(db);  // Recreate the table
    }
}

Explanation:

    1. Database Constants: Define database name, version, table name, and column names for easy management.

    2. SQLiteOpenHelper Methods: Override onCreate to define the database schema and onUpgrade for version management.

    3. Table Schema: A users table with id, name, and age columns is created.


Performing CRUD Operations

Insert Data

Code:

// Method to insert a user into the database
public void insertUser(SQLiteDatabase db, String name, int age) {
    String query = "INSERT INTO users (name, age) VALUES (?, ?)";
    db.execSQL(query, new Object[]{name, age});  // Execute the query with parameters
}

Read Data

Code:

// Method to retrieve all users
public Cursor getAllUsers(SQLiteDatabase db) {
    String query = "SELECT * FROM users";
    return db.rawQuery(query, null);  // Execute the query and return results
}

Update Data

Code:

// Method to update a user's details
public void updateUser(SQLiteDatabase db, int id, String name, int age) {
    String query = "UPDATE users SET name = ?, age = ? WHERE id = ?";
    db.execSQL(query, new Object[]{name, age, id});  // Execute the query with parameters
}

Delete Data

Code:

// Method to delete a user by ID
public void deleteUser(SQLiteDatabase db, int id) {
    String query = "DELETE FROM users WHERE id = ?";
    db.execSQL(query, new Object[]{id});  // Execute the query with parameters
}

Explanation:

    1. Parameterized Queries: Prevent SQL injection by using placeholders (?) for values.

    2. Database Operations: Each method demonstrates a CRUD operation (Create, Read, Update, Delete).


Benefits of using SQLite in Android

  • Performance: Optimized for mobile devices with low memory usage.
  • Flexibility: Suitable for various app use cases like note-taking apps, e-commerce, etc.
  • Portability: Data remains local to the app, ensuring offline availability.
  • Ease of Use: SQL syntax makes data management simple and intuitive.

Practical Guides to SQLite Snippets and Examples.



Follow us on Facebook and Twitter for latest update.