Article image Working with SQLite Databases: Using ContentValues in SQLite

28.6. Working with SQLite Databases: Using ContentValues in SQLite

Page 34 | Listen in audio

When developing Android applications, managing data is a crucial aspect that often involves using databases. SQLite is a popular choice for local database management in Android due to its lightweight nature and ease of use. One of the essential components when working with SQLite databases in Android is the ContentValues class, which is used to store a set of values that the SQLiteDatabase class can process.

The ContentValues class is essentially a key-value pair storage, where keys are of type String and values can be various types such as String, Integer, Float, Long, etc. This class is particularly useful when inserting or updating rows in a database table.

Inserting Data with ContentValues

To insert data into an SQLite database, you typically create an instance of ContentValues and populate it with the data you wish to insert. Here’s a step-by-step process:

  1. Create an instance of ContentValues: This instance will hold the data you want to insert.
  2. Put data into ContentValues: Use the put() method to add data. The key is the column name, and the value is the data you want to insert.
  3. Insert data into the database: Use the insert() method of SQLiteDatabase, passing the table name and the ContentValues instance.

Here’s an example:


ContentValues values = new ContentValues();
values.put("name", "John Doe");
values.put("age", 30);
values.put("email", "[email protected]");

SQLiteDatabase db = this.getWritableDatabase();
long newRowId = db.insert("Users", null, values);

In this example, we’re inserting a new row into the Users table with the name, age, and email of a user. The insert() method returns the ID of the new row, or -1 if an error occurred.

Updating Data with ContentValues

Updating data in an SQLite database is similar to inserting data. You use ContentValues to specify the new values for the columns you want to update.

Here’s how you can update data:

  1. Create an instance of ContentValues: Populate it with the new data.
  2. Use the update() method: Call update() on the SQLiteDatabase instance, specifying the table name, ContentValues, and a whereClause to identify which rows to update.

Here’s an example:


ContentValues values = new ContentValues();
values.put("email", "[email protected]");

SQLiteDatabase db = this.getWritableDatabase();
String selection = "name = ?";
String[] selectionArgs = {"John Doe"};

int count = db.update(
    "Users",
    values,
    selection,
    selectionArgs);

In this example, we’re updating the email of the user named John Doe. The update() method returns the number of rows affected.

Benefits of Using ContentValues

The ContentValues class provides several benefits when working with SQLite databases:

  • Type Safety: ContentValues ensures that the data types are correctly handled, reducing the risk of SQL injection attacks.
  • Ease of Use: The key-value pair structure is intuitive and easy to use, making the code more readable and maintainable.
  • Flexibility: ContentValues can hold different data types, making it versatile for various database operations.

Handling Null Values

When working with databases, you might encounter scenarios where some fields are optional and can be null. ContentValues handles null values gracefully. If you want to insert a null value, you can simply omit that key-value pair, or explicitly put a null using the putNull() method:


ContentValues values = new ContentValues();
values.put("name", "Jane Doe");
values.putNull("phone");

SQLiteDatabase db = this.getWritableDatabase();
long newRowId = db.insert("Users", null, values);

In this example, the phone column will be set to null for the new row.

Best Practices

While using ContentValues, consider the following best practices:

  • Column Names: Always use the correct column names as keys in ContentValues to avoid runtime errors.
  • Transaction Management: For bulk inserts or updates, use database transactions to ensure data integrity and improve performance.
  • Consistency: Maintain consistency in the data types you use for values to avoid unexpected behavior.

Example: A Complete CRUD Operation

Let’s put everything together with a complete example of CRUD operations using ContentValues in an SQLite database. Consider a simple database for managing books:


public class BooksDbHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "books.db";
    private static final int DATABASE_VERSION = 1;

    public BooksDbHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String SQL_CREATE_BOOKS_TABLE = "CREATE TABLE Books (" +
                "id INTEGER PRIMARY KEY AUTOINCREMENT, " +
                "title TEXT NOT NULL, " +
                "author TEXT, " +
                "price REAL NOT NULL DEFAULT 0);";
        db.execSQL(SQL_CREATE_BOOKS_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS Books");
        onCreate(db);
    }

    public long insertBook(String title, String author, double price) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("title", title);
        values.put("author", author);
        values.put("price", price);

        return db.insert("Books", null, values);
    }

    public int updateBookPrice(long id, double newPrice) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("price", newPrice);

        String selection = "id = ?";
        String[] selectionArgs = {String.valueOf(id)};

        return db.update("Books", values, selection, selectionArgs);
    }

    public int deleteBook(long id) {
        SQLiteDatabase db = this.getWritableDatabase();
        String selection = "id = ?";
        String[] selectionArgs = {String.valueOf(id)};

        return db.delete("Books", selection, selectionArgs);
    }

    public Cursor readAllBooks() {
        SQLiteDatabase db = this.getReadableDatabase();
        String[] projection = {
                "id",
                "title",
                "author",
                "price"
        };

        return db.query("Books", projection, null, null, null, null, null);
    }
}

In this example, we have a BooksDbHelper class that extends SQLiteOpenHelper. It includes methods for inserting, updating, deleting, and reading book records using ContentValues. This class provides a complete CRUD operation implementation, showcasing how ContentValues can be effectively used in managing an SQLite database in an Android application.

By understanding and utilizing ContentValues, you can efficiently manage database operations in your Android applications, ensuring data integrity and consistency while simplifying the process of interacting with SQLite databases.

Now answer the exercise about the content:

You are right! Congratulations, now go to the next page

You missed! Try again.

Article image Working with SQLite Databases: Executing SQL Queries

Next page of the Free Ebook:

35Working with SQLite Databases: Executing SQL Queries

10 minutes

Earn your Certificate for this Course for Free! by downloading the Cursa app and reading the ebook there. Available on Google Play or App Store!

Get it on Google Play Get it on App Store

+ 6.5 million
students

Free and Valid
Certificate with QR Code

48 thousand free
exercises

4.8/5 rating in
app stores

Free courses in
video, audio and text