1.Firebase與專案連結
2.點擊Cloud Firestore將library與google-services.json導入進專案
3.Firebase console創建資料庫
選擇(測試模式啟動) 上架前在改為(鎖定模式啟動)
4.寫入資料
private val users = mutableListOf<Map<String, String>>()
private val database = FirebaseFirestore.getInstance()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
users.add(insertUser("fly", "a123456"))
users.add(insertUser("wei", "b123456"))
for (user in users) {
database.collection("users")
.add(user)
.addOnSuccessListener {
Log.e("GGG", it.id)
}
.addOnFailureListener {
Log.e("GGG", it.toString())
}
}
}
private fun insertUser(name: String, password: String): Map<String, String> {
return mapOf("name" to name, "password" to password)
}
回傳的document id
5.讀取資料
private val database = FirebaseFirestore.getInstance()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
database.collection("users")
.get().addOnSuccessListener {
val users = it.toObjects(User::class.java)
users.forEach {user ->
Log.e("GGG", "{user.name}{user.password}")
}
}
}
6.Model(一定要有空建構子)
class User(val name: String, val password: String) {
constructor() : this("", "")
}