0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

RealtimeDatabase

Last updated at Posted at 2021-01-17

依存関係の宣言

build.gradle(モジュール)
dependencies{
    implementation 'com.google.firebase:firebase-database-ktx'
}

# 準備

MainActivity.kt
class MainActivity : AppCompatActivity() {
    //追加
    private lateinit var database:DatabaseRefernce

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

        //追加
        database = Firebase.database.reference
    }
}

#書き込み

...
database = Firebase.database.reference
database.child("users").child("user01").child("name").setValue("山田太郎")
database.child("users").child("user01").child("email").setValue("yamada@example.com")

こうもできる

data class User(
    val name:String = "",
    val email:String = ""
)

val user = User("yamadaTarou","yamada@example.com")

database.child("users").child("user01").setValue(user)

#読み取り

database.child("users").addChildEventListener(object :ChildEventListener{
        override fun onChildAdded(snapshot: DataSnapshot, previousChildName: String?){
            //処理
        }
        override fun onChildChanged(snapshot: DataSnapshot, previousChildName: String?) {
            //処理
        }
        override fun onCancelled(error: DatabaseError) {}
        override fun onChildMoved(snapshot: DataSnapshot, previousChildName: String?) {}
        override fun onChildRemoved(snapshot: DataSnapshot) {}
    })

これでusers配下に何かしらの変更が行われたときにそれぞれの処理を行います
snapshotには変更が行われた箇所のみが入っています
初回はonChildAddedが自動的に呼び出されます
※listenerをつけた配下に何もない場合は呼び出されない

Snapshotの仕組み

database.addChildListener{}

database.child("name").setValue("yamada tarou")
//snapshot.value = yamada tarou
//snapshot.key = name

database.child("name").setValue("yamada jirou")
/*
{
    name:yamada jirou
}
*/

database.child("users").child("user01").child("name").setValue("yamada jirou")
/*
users:{
    user01:{
        name:yamada jirou
    }
}
*/
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?