Firebase

Android Firebase Realtime Database

1.Firebase與專案連結

2.點擊Realtime Database將library與google-services.json導入進專案

3.Firebase console創建資料庫

選擇(測試模式啟動) 上架前在改為(鎖定模式啟動)

4.寫入資料

private lateinit var database: DatabaseReference

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    database = FirebaseDatabase.getInstance().reference

    insertUser("0", "fly", "a123456")
    insertUser("1", "wei", "b123456")
}

private fun insertUser(userId: String, name: String, password: String) {
    val user = User(name, password)
    database.child("users").child(userId).setValue(user)
}

5.讀取資料

private lateinit var database: DatabaseReference

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    database = FirebaseDatabase.getInstance().reference

    queryUser("0")
    queryUser("1")
}

private fun queryUser(userId: String) {
    database.child("users").child(userId).addValueEventListener(object : ValueEventListener {
        override fun onCancelled(error: DatabaseError) {
            Log.e("GGG", "Failed to read value.", error.toException());
        }

        override fun onDataChange(snapshot: DataSnapshot) {
            val user = snapshot.getValue(User::class.java)
            user?.let { user ->
                Log.e("GGG", "{user.username}{user.password}")
            }
        }
    })
}

6.Model(一定要有空建構子)

class User(val username: String, val password: String)  {
    constructor() : this("", "")
}

發表迴響