How to integrate SQLite in Android with other Android components?

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.

Step 1: Add SQLite Dependency

SQLite is included in Android by default, so no additional dependencies are required. You can start using it right away.

Step 2: Create a Database Helper Class

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); } }

Step 3: Interact with the Database

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();

Step 4: Close the Database Connection

Don't forget to close the database connection when it's no longer needed to avoid memory leaks.

db.close();

SQLite Android Database SQLiteOpenHelper CRUD operations Android components Data storage