Integrating SQLite in Android applications is a common practice for data storage. This guide will lead you through the basic steps to set up SQLite in your Android project, connect it with other components, and perform CRUD (Create, Read, Update, Delete) operations.
SQLite is included in Android by default, so no additional dependencies are required. You can start using it right away.
To manage database creation and version management, you need to create a subclass of SQLiteOpenHelper
.
class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "example.db";
private static final int DATABASE_VERSION = 1;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE = "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)";
db.execSQL(CREATE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS users");
onCreate(db);
}
}
You can now use the DatabaseHelper
class to interact with the database.
DatabaseHelper dbHelper = new DatabaseHelper(this);
SQLiteDatabase db = dbHelper.getWritableDatabase();
// Insert data
ContentValues values = new ContentValues();
values.put("name", "John Doe");
long newRowId = db.insert("users", null, values);
// Read data
Cursor cursor = db.query("users", new String[] { "id", "name" }, null, null, null, null, null);
while (cursor.moveToNext()) {
int id = cursor.getInt(cursor.getColumnIndexOrThrow("id"));
String name = cursor.getString(cursor.getColumnIndexOrThrow("name"));
}
cursor.close();
Don't forget to close the database connection when it's no longer needed to avoid memory leaks.
db.close();
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?