Android Kotlin How to Get Records from Firebase - android

I am a beginner in android programming with Kotlin. I'm close on this, but missing something. Google is not showing me just what I need. Hoping someone here can.
I'm using android studio 4.1.1, kotlin and Firebase
I have several records in my test Firebase database.
each of these records has data, but when I use println in my code one part is showing null and it is not hitting another println at all.
my code - in part
WeightExercise.kt:
...
// i write records to the db like this:
val ref = FirebaseDatabase.getInstance().getReference("weights")
val recordID = ref.push().key
val userId = Global.userID
if (recordID != null){
ref.child(userId).child(recordID).setValue(weight).addOnCompleteListener{
Toast.makeText(applicationContext,"Weight Record rated successfully",Toast.LENGTH_LONG).show()
}
}
...
DisplayWeightsActivity.kt:
val uid = FirebaseAuth.getInstance().currentUser!!.uid
val ref = FirebaseDatabase.getInstance().getReference("weights")
val uidRef = ref.child("weights").child(uid)
val valueEventListener = object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
println("$$$$$$ dataSnapshot: ${dataSnapshot.toString()}")
for (ds in dataSnapshot.children) {
println("#$#$#$#$#$ in override dataSnapshot.children")
val muscle = ds.child("muscleGroup").getValue(String::class.java)
val exercise = ds.child("exerciseText").getValue(String::class.java)
val date = ds.child("date").getValue(String::class.java)
Log.d("TAG", date + " " + muscle + " " + exercise)
}
}
override fun onCancelled(databaseError: DatabaseError) {
Log.d("DB ERROR", databaseError.message) //Don't ignore errors!
}
uidRef.addListenerForSingleValueEvent(valueEventListener)
}
In my Logcat window I see this:
$$$$$$ dataSnapshot: DataSnapshot { key = oB3pzvhAr6foyhGZUuvFl4CECOw2, value = null }
But the println("#$#$#$#$#$ in override dataSnapshot.children") does not print.
The key above oB3pzv... matches my userid, so it sees that. I'm not sure what value = null means. Is it not seeing the children records? How do I get the children records under weights >> userId ?

Related

Extract Data from firebase

Unable to extract information from the datasnapshot received from firebase.
Currently, I am able to get the dataSnapshot from firebase, but I am having problems extracting the information from it.
In the example below I have a lobby with the code "81MUB" and inside I have a list of players (only using one player in the example). Data from FireBase
{
"81MUB": [
{
"name": "Alejandro",
"points": 0
}
]
}
Data Class
data class Player(
val name: String,
val points: Int
)
Listener
fun getCode(): String {
val index = ('A'..'Z') + ('1'..'9')
var code = ""
for (i in 0..4){
code += index[Random().nextInt(index.size)]
}
return code
}
class MviewModel : ViewModel() {
private val _Players: MutableLiveData<MutableList<Player>> =
MutableLiveData(mutableListOf<Player>(Player("Alejandro", 0)))
private var _LobbyCode: String = ""
private val dataBase = FirebaseDatabase.getInstance()
fun getPlayer(): MutableLiveData<MutableList<Player>> = _Players
fun createLobby() {
_LobbyCode = getCode()
}
fun listener() {
val postListener = object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
}
override fun onCancelled(databaseError: DatabaseError) {
// Getting Post failed, log a message
}
}
dataBase.reference.child(_LobbyCode).addValueEventListener(postListener)
}
}
Any tips?
Each time you call getCode() you are generating a new random code. When reading data, you always use the exact same code that exists in the database. So in code, it should look like this:
val db = Firebase.database.reference
val codeRef = db.child("81MUB")
codeRef.get().addOnCompleteListener {
if (it.isSuccessful) {
val snapshot = it.result
val name = snapshot.child("name").getValue(String::class.java)
val points = snapshot.child("points").getValue(Long::class.java)
Log.d("TAG", "$name/$points")
} else {
Log.d("TAG", error.getMessage()) //Never ignore potential errors!
}
}
The result in the logcat will be:
Alejandro/0
If you however want to map the 81MUB node into an object of type Player, then your data class should look like this:
data class Player(
val name: String? = null,
val points: Int? = null
)
And in code:
val db = Firebase.database.reference
val codeRef = db.child("81MUB")
codeRef.get().addOnCompleteListener {
if (it.isSuccessful) {
val snapshot = it.result
val player = snapshot.getValue(Player::class.java)
Log.d("TAG", "${player.name}/${player.points}")
} else {
Log.d("TAG", error.getMessage()) //Never ignore potential errors!
}
}
Which will produce the exact same output as above.
You might also take into consideration, using the DatabaseReference#push() method which:
Create a reference to an auto-generated child location. The child key is generated client-side and incorporates an estimate of the server's time for sorting purposes.
Instead of using your codes.

access child database in firebase always returns null using android studio & kotlin

I've been having problems accessing this child database in firebase, it always returns null, been searching online for days and still got no answer...here's my code, I'm using Kotlin and Firebase:
auth = FirebaseAuth.getInstance()
database = FirebaseDatabase.getInstance()
databaseReference = database?.reference!!.child("users")
val nikReference = databaseReference?.child("nik")
val mainDB = nikReference?.child("jabatan")
val user = auth.currentUser
etEmailUserShow.text = user?.email
mainDB?.addValueEventListener(object: ValueEventListener{
override fun onDataChange(snapshot: DataSnapshot) {
etValidasiLamaran.text = "Jabatan - - > "+snapshot.child("jabatan").value.toString() //<<-- this one returns null
}
heres my database configuration
Te structure is users/nik/... (the one I've highlighted red in the screenshot is nik).
What I want to access is the value likes of : berkas,ijasah,jabatan,etc etc.
To be able to display the data under a specific user, you have to create a reference that points exactly to that user. That being said, to display the data of the first user, please use the following lines of code:
val db = FirebaseDatabase.getInstance().reference
val nikRef = db.child("users").child("753951852")
val valueEventListener = object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
val jabatan = snapshot.child("jabatan").getValue(String::class.java)
Log.d("TAG", jabatan)
etValidasiLamaran.text = "Jabatan - - > " + jabatan
}
override fun onCancelled(error: DatabaseError) {
Log.d("TAG", error.getMessage()) //Never ignore potential errors!
}
}
nikRef.addListenerForSingleValueEvent(valueEventListener)
The result in the logcat will be:
POSISI : MASTER

Infinite cycle on Firebase with Kotlin

So, my app does is a QR code scanner that adds the QR id to the current user UID. I first verify if the user already did that scan; if not, that id is added to the firebase table; otherwise, it will create that table.
This is my code:
private fun infoAdd(str2: String, view: View) {
val currentUser = auth.currentUser?.uid
val postReference = FirebaseDatabase.getInstance().getReference("organsUsers")
val dbView = postReference.child(currentUser.toString())
val postListener = object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
val org = snapshot.child("uOrgans")
if (org != null) {
val post = org.getValue(String::class.java)
dbView.child("uOrgans").setValue("$post,$str2")
} else {
dbView.child("uOrgans").setValue(str2)
}
}
override fun onCancelled(databaseError: DatabaseError) {
}
}
dbView.addValueEventListener(postListener)
}
The str2 it's the string of the QR id.
This is what happens to Firebase:
Please Help!!!!
I first verify if the user already did that scan; if not, that id is added to the firebase table; otherwise, it will create that table.
It doesn't make any sense because in both cases you are "setting" the value of str2 into the database, that's why you see that behavior of highlighting that operation in yellow. Because a Firebase Realtime Database is a NoSQL database and is structured as pairs of keys and values, every node is a Map, which means that when using a setValue() operation, the old value is replaced with the new one.
If you want to check if the value of uOrgans exists, then update it for example, please use the following lines of code:
val uid = FirebaseAuth.getInstance().currentUser!!.uid
val rootRef = FirebaseDatabase.getInstance().reference
val uidRef = rootRef.child("organsUsers").child(uid)
val valueEventListener = object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
val org = snapshot.child("uOrgans")
if(org.exists()) {
val post = org.getValue(String::class.java)
dbView.getRef().updateChildren(mapOf("uOrgans" to "$post,$str2")) //Update it
Log.d("TAG", $post,$str2)
} else {
uidRef.child("uOrgans").setValue(str2)
}
}
override fun onCancelled(databaseError: DatabaseError) {
Log.d("TAG", databaseError.getMessage()) //Don't ignore potential errors!
}
}
uidRef.addListenerForSingleValueEvent(valueEventListener)
If doesn't exist, the str2 is added to the database.
One thing to mention, if uOrgans doesn't exist, none of its parents (organsUsers and the UID) nodes will not exist.

how to get child in android kotlin and firebase?

My Firebase data structure is
MyPage
message{
-M9CrzvBuz1EBojnK9xP{
id: user
text: hi
time: "2020.06.07/08:22:46"
But I don't know how to get id, text and time. How can I get it with Kotlin?
The number of children in the message will continue to increase. Can I get them all?
Assuming that the MyPage is the root of your database, please use the following lines of code:
val rootRef = FirebaseDatabase.getInstance().reference
val messageRef = rootRef.child("message")
val valueEventListener = object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
for (ds in dataSnapshot.children) {
val id = ds.child("id").getValue(String::class.java)
val text = ds.child("text").getValue(String::class.java)
val time = ds.child("time").getValue(String::class.java)
Log.d("TAG", text + " " + id + " " + time)
}
}
override fun onCancelled(databaseError: DatabaseError) {
Log.d("TAG", databaseError.getMessage()) //Don't ignore errors!
}
}
messageRef.addListenerForSingleValueEvent(valueEventListener)
And the result in your logcat will be:
hi user 2020.06.07/08:22:46
Map data = remoteMessage.getData();
String id= data.get("id");
You can parse the body from your RemoteMessage.

How to get elements from a condition node in a Realtime Database Firebase

I need to get from the Firebase Realtime Database node, not the entire list, but only the one that contains the value "ok".
I can get the whole list using the User model
val list:List<User> = it.children.map {it.getValue(User::class.java)}
If you need to get only the users that have the id property set to "ok", then you should use a Query line in the following lines of code:
val rootRef = FirebaseDatabase.getInstance().reference
val usersRef = rootRef.child("users")
val okQuery = usersRef.orderByChild("id").equalTo("ok")
val valueEventListener = object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
for (ds in dataSnapshot.children) {
val user = ds.getValue(User::class.java)
Log.d("TAG", ds.key + " -> " + user.id)
}
}
override fun onCancelled(databaseError: DatabaseError) {
Log.d("TAG", databaseError.getMessage()) //Don't ignore errors!
}
}
okQuery.addListenerForSingleValueEvent(valueEventListener)
The result in the logcat will be:
kolya -> ok
sasha -> ok

Categories

Resources