使用SQLite作為本地的資料庫
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
class myDataBase(
context: Context, name: String = database,
factory: SQLiteDatabase.CursorFactory? = null, version: Int = v
) :
SQLiteOpenHelper(context, name, factory, version) {
companion object {
private const val database = "classmoney.db"
private const val v = 1
}
override fun onCreate(db: SQLiteDatabase) {
db.execSQL("CREATE TABLE students (name text PRIMARY KEY,number integer NOT NULL,age integer NOT NULL)")
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
db.execSQL("DROP TABLE IF EXISTS students")
onCreate(db)
}
}
使用.addSnapshotListener
對Firestore進行監聽,SnapshotListener會在Firestore中的資料有發生變動時觸發
Firestore.collection("Student")
.addSnapshotListener { querySnapshot, firebaseFirestoreException ->
}
透過SnapshotListener只能知道那些文件被修改,但不知道修改的方式,所以需要設計處理文件的流程
Firestore.collection("Student")
.addSnapshotListener { querySnapshot, firebaseFirestoreException ->
//從本地資料庫尋找名字相同的資料
if(db.rawQuery("SELECT * FROM students WHERE name LIKE '${i.name}'",null).count == 0){
//如果找不到 則新增一筆資料
db.execSQL(
"INSERT INTO accounts(name,number,age) VALUES(?,?,?)",
arrayOf<Any?>(
i.name,
i.number,
i.age
)
)
}else{
//若有相同的資料 則修改本地資料的內容
db.execSQL("UPDATE students SET number = '${i.number}' WHERE name LIKE '${i.name}'")
db.execSQL("UPDATE students SET age = '${i.age}' WHERE name LIKE '${i.name}'")
}
}
當文件被刪除時,在SnapshotListener會得到一個內容完全相同的文件,所以在刪除時可以先將一個欄位修改成一個特定的代號再進行刪除
fun delete(id:String){
//先將年齡欄位改為0
Firestore.collection("Student")
.document("$id")
.update("age",0)
//再進行刪除
Firestore.collection("Student")
.document("$id")
.update("age",0)
}
Firestore.collection("Student")
.addSnapshotListener { querySnapshot, firebaseFirestoreException ->
//從本地資料庫尋找名字相同的資料
if(db.rawQuery("SELECT * FROM students WHERE name LIKE '${i.name}'",null).count == 0){
//如果找不到 則新增一筆資料
db.execSQL(
"INSERT INTO accounts(name,number,age) VALUES(?,?,?)",
arrayOf<Any?>(
i.name,
i.number,
i.age
)
)
}else{
//若有相同的資料 則修改本地資料的內容
if(i.age == 0){
//若年齡欄位為0 則刪除本地的資料
db.execSQL("DELETE FROM students WHERE name LIKE '${i.name}'")
}else{
db.execSQL("UPDATE students SET number = '${i.number}' WHERE name LIKE '${i.name}'")
db.execSQL("UPDATE students SET age = '${i.age}' WHERE name LIKE '${i.name}'")
}
}
}