Reading
Add Comment
In order to read your data from Firebase with Kotlin you need to go through the usual rigmarole of setting up Firebase and Kotlin in Android Studio - I'm not even going near the Android Studio 3 Preview because it's as buggy as a a nest of fly lavae.
Ok here we go:
1. Declare the DatabaseReference object in your class, I use the lateinit modifier because it allows me declare the object without having to initialize it immediately. I can initialize it later at my leisure:
lateinit var databaseRef: databaseReference
2 I initialize it within my onCreate like so:
databaseRef = FirebaseDatabase.getInstance().getReference()
Please make sure you import
import com.google.firebase.database.*
3 I call a method getGreeting()
In this method I call the entry "greeting" in my Firebase app account. greeting is just a name value entry with a string as the value. To listen for the response of my call, I have the ValueEventListener added to the reference call like so:
databaseRef.child("greeting").addValueEventListener(object:ValueEventListener{
override fun onDataChange(snapshot: DataSnapshot){\
println("TestBed: ${snapshot.value}")
}
})
}
That's it really, the code below shows you the complete business
import com.google.firebase.database.* class TestBedScrollingActivity : AppCompatActivity() { lateinit var databaseRef: DatabaseReference override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_test_bed_scrolling) val toolbar = findViewById(R.id.toolbar) as Toolbar setSupportActionBar(toolbar) val fab = findViewById(R.id.fab) as FloatingActionButton fab.setOnClickListener { view -> Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show() } databaseRef = FirebaseDatabase.getInstance().getReference() getGreeting() } // [ Begin get greeting form Firebase ] fun getGreeting(){ println("--------- start greeting ----------") databaseRef.child("greeting").addValueEventListener(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { println("TestBed: ${snapshot.value}") } override fun onCancelled(error: DatabaseError) {} }) } // [ End get greeting from Firebase ]
0 comments:
Post a Comment