How to use SQLite in Android in an Android app?

SQLite is a lightweight database engine that comes pre-installed with Android. It is used to store data locally in applications. This guide will explain how to use SQLite in your Android app effectively.

Steps to Use SQLite in Android

  1. Create a Database Helper Class: Extend the SQLiteOpenHelper class and override the necessary methods to create and manage your database.
  2. Implement Database Operations: Add methods for inserting, updating, deleting, and querying data.
  3. Utilize the Database in Your App: Use the helper class to interact with the SQLite database within your application.

Example of SQLite Implementation:

// DatabaseHelper.java import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class DatabaseHelper extends SQLiteOpenHelper { private static final String DATABASE_NAME = "myDatabase.db"; private static final String TABLE_NAME = "myTable"; private static final String COL_1 = "ID"; private static final String COL_2 = "NAME"; public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, 1); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT)"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); onCreate(db); } public boolean insertData(String name) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put(COL_2, name); long result = db.insert(TABLE_NAME, null, contentValues); return result != -1; // if data is inserted successfully, result will be -1 } public Cursor getAllData() { SQLiteDatabase db = this.getWritableDatabase(); return db.rawQuery("SELECT * FROM " + TABLE_NAME, null); } }

SQLite Android SQLite Database Android App Development Local Database Database Helper Class