Creating, Opening, and Closing SQLite Database in Android
1. Creating an SQLite Database
To create a database, you subclass SQLiteOpenHelper and override the onCreate() method:
public class MyDatabaseHelper extends SQLiteOpenHelper {
public MyDatabaseHelper(Context context) {
super(context, "MyDatabase.db", null, 1);
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, email TEXT)");
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS users");
onCreate(db);
This creates a table named 'users' when the database is first created.
2. Opening the Database
Create an instance of your helper class and call:
a. getWritableDatabase()
Opens the database for read and write operations.
MyDatabaseHelper dbHelper = new MyDatabaseHelper(context);
SQLiteDatabase db = dbHelper.getWritableDatabase();
Creating, Opening, and Closing SQLite Database in Android
b. getReadableDatabase()
Opens the database in read-only mode if write access is not available.
SQLiteDatabase db = dbHelper.getReadableDatabase();
3. Closing the Database
Even though Android handles this, it's best practice to close the database manually:
db.close(); // Close the SQLiteDatabase
dbHelper.close(); // Close the helper class
Always use try-finally or try-with-resources to ensure proper closing.
Avoid keeping the database open longer than necessary.
Quick Recap
| Operation | Method |
|---------------|--------------------------------------------|
| Create DB | SQLiteOpenHelper + onCreate() |
| Open DB | getWritableDatabase(), getReadableDatabase()|
| Close DB | close() on SQLiteDatabase and helper |