1 Launching The Application in Android Studio
1 Launching The Application in Android Studio
🔹 Introduction
Android provides multiple options to store data locally on a device. When
structured, persistent storage is required, databases are the most efficient
choice. Android uses SQLite, a lightweight, embedded relational database
engine, for database operations.
🔹 Creating a Database
To create and manage a SQLite database in Android, we extend the
SQLiteOpenHelper class which provides two important lifecycle methods:
1. onCreate(SQLiteDatabase db)
Called when the database is created for the first time. Used to create
tables and initialize data.
2. onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
Called when the database version is incremented. Used to alter tables,
drop old ones, or migrate data.
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE users(id INTEGER PRIMARY KEY, name TEXT)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS users");
onCreate(db);
}
}
🔹 CRUD Operations
Insert Data:
java
CopyEdit
ContentValues values = new ContentValues();
values.put("name", "Alice");
db.insert("users", null, values);
Read Data:
java
CopyEdit
Cursor cursor = db.rawQuery("SELECT * FROM users", null);
Update Data:
java
CopyEdit
ContentValues values = new ContentValues();
values.put("name", "Bob");
db.update("users", values, "id=?", new String[]{"1"});
Delete Data:
java
CopyEdit
db.delete("users", "id=?", new String[]{"1"});