1.Firebase與專案連結
![](https://badgameshow.com/fly/wp-content/uploads/2020/03/FCM1-198x300.png)
2.點擊Cloud Firestore將library與google-services.json導入進專案
![](https://badgameshow.com/fly/wp-content/uploads/2021/01/wp_editor_md_5855c94636983c3eade8da82b9f71618.jpg)
3.Firebase console創建資料庫
選擇(測試模式啟動) 上架前在改為(鎖定模式啟動)
![](https://badgameshow.com/fly/wp-content/uploads/2021/01/wp_editor_md_b12c6ebcde01c081c3ddebd827a88c82.jpg)
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)
}
![](https://badgameshow.com/fly/wp-content/uploads/2021/01/wp_editor_md_92c1465e8dfae9cd6fb37a05bf8bcf35.jpg)
![](https://badgameshow.com/fly/wp-content/uploads/2021/01/wp_editor_md_a43805a1e8b1afcb32810cef1f6716ef.jpg)
回傳的document id
![](https://badgameshow.com/fly/wp-content/uploads/2021/01/wp_editor_md_d33908c084040d1844d02e185ce59bd6.jpg)
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("", "")
}
![](https://badgameshow.com/fly/wp-content/uploads/2021/01/wp_editor_md_1bd6abe9c78ef6c63a71fc9afc156ad6.jpg)