Using SQLite for Mobile Apps: An Introduction
Learn how to integrate SQLite into mobile app development (Android/iOS)
When you make a mobile app, you need a place to keep all the things your app needs to remember, like a list of items or your score in a game. SQLite is like a little notebook inside your phone where you can store these things, and it helps your app remember them even if the phone is not connected to the internet.
In this blog, you’ll learn how to use SQLite in your Android and iPhone apps. You’ll also learn how to create your own little database, make your app store things in it, and edit and retrieve data as needed.
Why Use SQLite in Mobile Apps?
SQLite is the most widely used database in mobile app development, thanks to its lightweight nature and high performance. Here’s why it’s so popular for mobile applications:
Zero Configuration: SQLite is self-contained—no need for a server or complex setup.
Performance: It is fast, lightweight, and designed to store data locally, and doesn’t take up much space on your phone.
Works Offline: SQLite stores data on the device, so your app can still work without an internet connection.
Setting Up SQLite in Android Apps
Now let’s look at how to get SQLite set up and running in an Android app. Android already knows how to use SQLite. You just need to tell it what to do, and it takes care of the rest! The process involves creating a helper class that manages the database.
Step 1: Create the SQLite Helper Class
First, you need a SQLiteOpenHelper
class to manage the creation and upgrading of the database. This class will handle tasks like creating tables and handling changes in the database schema.
public class DBHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "restaurant.db";
private static final int DATABASE_VERSION = 1;
// Constructor
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
// Create tables when the database is created
String CREATE_TABLE = "CREATE TABLE menu (id INTEGER PRIMARY KEY, name TEXT, price REAL)";
db.execSQL(CREATE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop old table if exists and recreate it
db.execSQL("DROP TABLE IF EXISTS menu");
onCreate(db);
}
}
Step 2: Insert Data into the Database
Now that we have the database and table, let’s insert data into the menu
table.
public void insertMenuItem(String name, double price) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", name);
values.put("price", price);
db.insert("menu", null, values);
db.close();
}
Here, we’re inserting a new menu item into the menu
table. The ContentValues
class is used to define the data that’s being inserted.
Step 3: Retrieve Data from the Database
To get data from the database, you can use a Cursor
object.
public Cursor getMenuItems() {
SQLiteDatabase db = this.getReadableDatabase();
return db.rawQuery("SELECT * FROM menu", null);
}
This method retrieves all the rows from the menu
table. The result is returned as a Cursor
, which you can loop through to access each record.
Step 4: Displaying Data in a List
Let’s display the data we’ve retrieved in a ListView
. We’ll loop through the Cursor
object and add each row to an array:
Cursor cursor = dbHelper.getMenuItems();
List<String> menuItems = new ArrayList<>();
while (cursor.moveToNext()) {
String name = cursor.getString(cursor.getColumnIndex("name"));
double price = cursor.getDouble(cursor.getColumnIndex("price"));
menuItems.add(name + " - $" + price);
}
cursor.close();
// Now set the list data to ListView
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, menuItems);
listView.setAdapter(adapter);
This code retrieves the menu items and displays them in a ListView
.
Setting Up SQLite in iOS Apps
Next, let’s see how to set up SQLite in iOS using Swift. We’ll walk through creating the database, inserting data, and retrieving data from it.
Step 1: Install SQLite for iOS
To use SQLite in your iOS app, you can use a library like SQLite.swift to simplify interactions with the database. First, install the library using CocoaPods:
Add this to your Podfile
:
pod 'SQLite.swift', '~> 0.12.2'
Then run pod install
to install the SQLite library.
Step 2: Creating and Opening the Database
Once SQLite is installed, create and open the SQLite database:
import SQLite
let db = try Connection("path_to_database.sqlite3")
Step 3: Creating Tables
Next, create a table to store the data. In this example, we’ll create a menu
table to store the items available in a restaurant.
let menu = Table("menu")
let id = Expression<Int64>("id")
let name = Expression<String>("name")
let price = Expression<Double>("price")
do {
try db.run(menu.create { t in
t.column(id, primaryKey: true)
t.column(name)
t.column(price)
})
} catch {
print("Table creation failed: \(error)")
}
Step 4: Inserting Data
To insert data into the database, we can use the insert()
method:
let insert = menu.insert(name <- "Pizza", price <- 12.99)
do {
try db.run(insert)
print("Inserted item into menu")
} catch {
print("Insert failed: \(error)")
}
This inserts a new menu item into the menu
table.
Step 5: Retrieving Data
To retrieve data, use a select
query and loop through the results:
do {
for item in try db.prepare(menu) {
print("ID: \(item[id]), Name: \(item[name]), Price: \(item[price])")
}
} catch {
print("Select query failed: \(error)")
}
This code fetches all items from the menu
table and prints the data to the console.
Conclusion
SQLite is an essential tool for mobile app development, offering a simple yet powerful way to manage data locally on both Android and iOS devices. With minimal setup, you can create databases, store data, and easily retrieve it when needed.
In this blog, we covered the basics of integrating SQLite into both Android and iOS applications, from database creation to data insertion and retrieval. Whether you’re building a mobile app that works offline or managing a large amount of local data, SQLite is a fantastic solution for your needs.
Subscribe Now
Stay updated with the latest tips and tutorials on SQLite integration in mobile apps! Subscribe now to receive expert advice, step-by-step guides, and updates directly in your inbox. Join our SQLite Forum community to ask questions, share experiences, and connect with fellow developers!