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:
Creating a Database Helper Class:
kotlinimport 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) } }
Inserting Data:
kotlinval dbHelper = DatabaseHelper(this) val db = dbHelper.writableDatabase val values = ContentValues().apply { put("name", "John Doe") put("age", 30) } db.insert("users", null, values)
Retrieving Data:
kotlinval 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:
Creating a SQLite Database:
swiftimport 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 }
Creating a Table:
swiftfunc 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) }
Inserting Data:
swiftfunc 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) }
Retrieving Data:
swiftfunc 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.
Storing Data:
kotlinval sharedPref = getSharedPreferences("myPrefs", Context.MODE_PRIVATE) with(sharedPref.edit()) { putString("username", "JohnDoe") putInt("age", 30) apply() }
Retrieving Data:
kotlinval 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.
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.
Creating a Data Model:
- Open the
.xcdatamodeld
file. - Add an entity (e.g.,
User
) with attributes (e.g.,name
of type String andage
of type Integer).
- Open the
Generating NSManagedObject Subclass:
- Select the entity and go to
Editor -> Create NSManagedObject Subclass
. - Xcode will generate a class for your entity.
- Select the entity and go to
Saving Data:
swiftimport 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)") } } }
Fetching Data:
swiftfunc 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:
Writing to a File:
kotlinval filename = "example.txt" val fileContents = "Hello, World!" openFileOutput(filename, Context.MODE_PRIVATE).use { it.write(fileContents.toByteArray()) }
Reading from a File:
kotlinval filename = "example.txt" val fileContents = openFileInput(filename).bufferedReader().use { it.readText() }
iOS:
Writing to a File:
swiftlet 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)") } }
Reading from a File:
swiftlet 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
Post a Comment