Introduction to SQLite Databases


  

SQLite is a lightweight, relational database management system embedded within Android and iOS. It is ideal for storing structured data in mobile applications.

Setting Up SQLite in Android:

  1. Creating a Database Helper Class:

    kotlin
    import android.content.Context import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteOpenHelper class DatabaseHelper(context: Context) : SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) { companion object { private const val DATABASE_NAME = "example.db" private const val DATABASE_VERSION = 1 } override fun onCreate(db: SQLiteDatabase) { val createTable = "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)" db.execSQL(createTable) } override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { db.execSQL("DROP TABLE IF EXISTS users") onCreate(db) } }
  2. Inserting Data:

    kotlin
    val dbHelper = DatabaseHelper(this) val db = dbHelper.writableDatabase val values = ContentValues().apply { put("name", "John Doe") put("age", 30) } db.insert("users", null, values)
  3. Retrieving Data:

    kotlin
    val db = dbHelper.readableDatabase val cursor = db.query("users", null, null, null, null, null, null) with(cursor) { while (moveToNext()) { val id = getInt(getColumnIndexOrThrow("id")) val name = getString(getColumnIndexOrThrow("name")) val age = getInt(getColumnIndexOrThrow("age")) // Use the data } } cursor.close()

Setting Up SQLite in iOS:

  1. Creating a SQLite Database:

    swift
    import SQLite3 var db: OpaquePointer? func openDatabase() -> OpaquePointer? { let fileURL = try! FileManager.default .url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) .appendingPathComponent("example.sqlite") if sqlite3_open(fileURL.path, &db) != SQLITE_OK { print("Error opening database") return nil } return db }
  2. Creating a Table:

    swift
    func createTable() { let createTableString = "CREATE TABLE IF NOT EXISTS users(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER)" var createTableStatement: OpaquePointer? if sqlite3_prepare_v2(db, createTableString, -1, &createTableStatement, nil) == SQLITE_OK { if sqlite3_step(createTableStatement) == SQLITE_DONE { print("Table created.") } else { print("Table could not be created.") } } else { print("CREATE TABLE statement could not be prepared.") } sqlite3_finalize(createTableStatement) }
  3. Inserting Data:

    swift
    func insert(name: String, age: Int) { let insertString = "INSERT INTO users (name, age) VALUES (?, ?)" var insertStatement: OpaquePointer? if sqlite3_prepare_v2(db, insertString, -1, &insertStatement, nil) == SQLITE_OK { sqlite3_bind_text(insertStatement, 1, name, -1, nil) sqlite3_bind_int(insertStatement, 2, Int32(age)) if sqlite3_step(insertStatement) == SQLITE_DONE { print("Successfully inserted row.") } else { print("Could not insert row.") } } else { print("INSERT statement could not be prepared.") } sqlite3_finalize(insertStatement) }
  4. Retrieving Data:

    swift
    func query() { let queryString = "SELECT * FROM users" var queryStatement: OpaquePointer? if sqlite3_prepare_v2(db, queryString, -1, &queryStatement, nil) == SQLITE_OK { while sqlite3_step(queryStatement) == SQLITE_ROW { let id = sqlite3_column_int(queryStatement, 0) let name = String(cString: sqlite3_column_text(queryStatement, 1)) let age = sqlite3_column_int(queryStatement, 2) print("Query Result: \(id) | \(name) | \(age)") } } else { print("SELECT statement could not be prepared") } sqlite3_finalize(queryStatement) }

Using SharedPreferences in Android

SharedPreferences is used for storing key-value pairs in Android, ideal for saving small amounts of data such as user preferences.

  1. Storing Data:

    kotlin
    val sharedPref = getSharedPreferences("myPrefs", Context.MODE_PRIVATE) with(sharedPref.edit()) { putString("username", "JohnDoe") putInt("age", 30) apply() }
  2. Retrieving Data:

    kotlin
    val sharedPref = getSharedPreferences("myPrefs", Context.MODE_PRIVATE) val username = sharedPref.getString("username", "defaultName") val age = sharedPref.getInt("age", 0)

CoreData Basics for iOS

CoreData is a powerful framework in iOS for managing and persisting data.

  1. Setting Up CoreData:

    • When creating a new project, check "Use Core Data" in the project options.
    • This will add a .xcdatamodeld file to your project where you can define your data model.
  2. Creating a Data Model:

    • Open the .xcdatamodeld file.
    • Add an entity (e.g., User) with attributes (e.g., name of type String and age of type Integer).
  3. Generating NSManagedObject Subclass:

    • Select the entity and go to Editor -> Create NSManagedObject Subclass.
    • Xcode will generate a class for your entity.
  4. Saving Data:

    swift
    import UIKit import CoreData class ViewController: UIViewController { let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext func saveUser(name: String, age: Int16) { let newUser = User(context: context) newUser.name = name newUser.age = age do { try context.save() } catch { print("Failed to save user: \(error)") } } }
  5. Fetching Data:

    swift
    func fetchUsers() -> [User] { let fetchRequest: NSFetchRequest<User> = User.fetchRequest() do { let users = try context.fetch(fetchRequest) return users } catch { print("Failed to fetch users: \(error)") return [] } }

Reading and Writing Data to/from Files

Android:

  1. Writing to a File:

    kotlin
    val filename = "example.txt" val fileContents = "Hello, World!" openFileOutput(filename, Context.MODE_PRIVATE).use { it.write(fileContents.toByteArray()) }
  2. Reading from a File:

    kotlin
    val filename = "example.txt" val fileContents = openFileInput(filename).bufferedReader().use { it.readText() }

iOS:

  1. Writing to a File:

    swift
    let fileName = "example.txt" let text = "Hello, World!" if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first { let fileURL = dir.appendingPathComponent(fileName) do { try text.write(to: fileURL, atomically: false, encoding: .utf8) } catch { print("Failed to write to file: \(error)") } }
  2. Reading from a File:

    swift
    let fileName = "example.txt" if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first { let fileURL = dir.appendingPathComponent(fileName) do { let text = try String(contentsOf: fileURL, encoding: .utf8) print(text) } catch { print("Failed to read from file: \(error)") } }

Additional Tips:

  • Choosing the Right Storage Solution:

    • Use SQLite or CoreData for structured data and complex queries.
    • Use SharedPreferences for simple key-value pairs and user preferences.
    • Use file storage for large binary data or documents.
  • Data Security:

    • Encrypt sensitive data before storing it.
    • Follow platform guidelines for securing data at rest.
  • Data Backup and Restoration:

    • Implement backup mechanisms to prevent data loss.
    • Use cloud storage solutions for critical data.

By understanding SQLite databases, SharedPreferences, CoreData, and file handling, you'll be able to effectively manage and persist data in your mobile applications. Practice using these storage solutions to become proficient in handling different types of data requirements.

Comments

Popular posts from this blog

Introduction to App Development

Understanding App Layouts and User Interfaces

Introduction to App Lifecycle and Navigation