How to retrieve nested data structure from Firebase Realtime Database on Kotlin - android

I'm trying to retrieve submittedRequests from database .
userRef.addValueEventListener(object : ValueEventListener {
override fun onCancelled(p0: DatabaseError) {
}
override fun onDataChange(snapshot: DataSnapshot) {
if(snapshot!!.exists()){
val children=snapshot!!.children
for(item in children) {
val retrieveUser= item.getValue(User::class.java) //it crashes here
if (retrieveUser != null) {
userData.add(retrieveUser)
}
}
}
}
})
User Class
class User(val userId:String="", val name:String="", val surname:String="", val profileImageUrl: String="",val submittedRequests:String="", val pickedUpRequests:String="")
Error Message is :
com.google.firebase.database.DatabaseException: Failed to convert value of type java.util.HashMap to String
How can I retrieve submittedRequests from database properly?

You're declared submittedRequests:String="" in your User class. Looking at your JSON the submittedRequests is not a simple string, but rather a nested object, or a map.
This should work better
submittedRequests:Map<String, Any>=hashMapOf<String, Any>()

Related

Get firebase snapshot data in Kotlin Android

I'm new to Android & I don't know how to get all the firebase snapshot data at once inside the UID in the single data class.
val usersPrivateRef = Constants.FIREBASE_RESIDENT_PRIVATE
usersPrivateRef?.child("Fs0qczU3GsfJuGDGAeEN7bIgfjD3")
?.addListenerForSingleValueEvent(object : ValueEventListener{
override fun onDataChange(snapshot: DataSnapshot) {
if (snapshot.exists()) {
println(snapshot)
} else {
showLongToast("Snapshot not exists")
}
}
override fun onCancelled(error: DatabaseError) {}
})
To get a value from the DataSnapshot you can use its child() and getValue calls. For example, to print Krishna's email, you'd do:
println(snapshot.child("personalDetails/email").getValue(String::class.java)
I have found a solution for my above question
With the help of Gson library & also I have created the Kotlin data classes same as my snapshot data.
private var residentDATA : ArrayList<MineUserInfo> = ArrayList<MineUserInfo>()
var gson = Gson()
val json = Gson().toJson(snapshot.value)
var data = gson?.fromJson(json, MineUserInfo::class.java)
residentDATA.add(data)

Kotlin - How to save data from firebase to livedata with data class?

I trying run this code, but I get error: Can't convert object of type java.lang.String
i need to fetch data from realtime database and save it to livedata.
fun loadRecentlyAddedVoices(){
REF_DATABASE_ROOT.child(NODE_STICKERS).addListenerForSingleValueEvent(object :
ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
for (ds in snapshot.children) {
recentlyAddedVoices.value = ds.getValue(VoicesModel::class.java).toString()
}
}
override fun onCancelled(error: DatabaseError) {
}
})
}
Voices Model:
data class VoicesModel(
val title:String,
val description: String,
val count: Int,
val likes: Int,
val downloads: Int,
val data: VoiceDataModel
)
VoiceDataModel:
data class VoiceDataModel(
val voice_title: String,
val source: String
)
Can't convert object of type java.lang.String
According to your shared code, this exception is most probably given from the below:
recentlyAddedVoices.value = ds.getValue(VoicesModel::class.java).toString()
recentlyAddedVoices looks like the MutableLiveData object of a list of VoiceDataModel.
Using toString() here is the reason of the raised exception. And there is no reason to convert this value to a String.
Instead you need to create a normal list of VoicesModel first by iterating over the children of the datasnapshot, and then set the LiveData upon the completion of the list:
fun loadRecentlyAddedVoices(){
REF_DATABASE_ROOT.child(NODE_STICKERS).addListenerForSingleValueEvent(object :
ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
val temp: MutableList<VoicesModel> = mutableListOf()
for (ds in snapshot.children) {
val value: voiceModel = ds.getValue<VoicesModel>(VoicesModel::class.java)
// Aggregating to a non-live data list
temp.add(value)
}
// Setting the Live data value:
recentlyAddedVoices.value = temp
}
override fun onCancelled(error: DatabaseError) {
}
})
}

Can't convert object of type java.lang.Long to type(Model class); Fetching Data from firebaseDatabase android kotlin

I am using Firebase Database to populate a recyclerview. and i'm facing problem in fetching data.
the error
com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.Long to type com.massino.pfeadelramzi.models.Meuble
my code:
var mdatabase : DatabaseReference?=null
var listMeubles = mutableListOf<Meuble>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_liste_meuble3_d)
mdatabase = FirebaseDatabase.getInstance().reference.child("Bureau")
mdatabase!!.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
for (sna: DataSnapshot in snapshot.children){
val lis: Meuble? = sna.getValue(Meuble::class.java) //THE PROBLEME IS HERE
listMeubles.add(lis!!)
}
mon_recycler.setHasFixedSize(true)
mon_recycler.layoutManager = LinearLayoutManager(this#ListeMeuble3DActivity)
mon_recycler.adapter = MeubleAdapter(listMeubles.toTypedArray()){}
}
override fun onCancelled(error: DatabaseError) {
TODO("Not yet implemented")
}
})
}
My data Class Meuble:
data class Meuble(val imageResource: Int, val nom: String, val prix: Int,val stock:Int)
my Firebase data (now i'm just trying to find a solution so i created just one child
Code to add data to Firebase
button4.setOnClickListener{
var nomUI = spinner.selectedItem.toString()
var prixUI = textView2.text.toString().toInt()
var stockUI= textView3.text.toString().toInt()
var databaseref = firebaseDatabase.getReference(nomUI)
if ( nomUI != null || !TextUtils.isEmpty(prixUI.toString()) || !TextUtils.isEmpty(stockUI.toString())){
var meuble = Meuble(R.drawable.fauteuille2,nomUI,prixUI,stockUI)
databaseref.setValue(meuble)
}else {
Toast.makeText(this,"Remplissez la case manquante",Toast.LENGTH_LONG).show()
}
}
Please help to solve this exception.
As Ticherhaz commented: since you only have the properties for one child nodes under /Bureau, you should use loop over the child nodes in onDataChange.
Right now your loop means that sna points to each individual property, and that's why it fails. There is (for example) no way to parse the value of prix into a `` object.
The code for when you have a single child is:
mdatabase = FirebaseDatabase.getInstance().reference.child("Bureau")
mdatabase!!.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
val lis: Meuble? = snapshot.getValue(Meuble::class.java)
listMeubles.add(lis!!)
mon_recycler.setHasFixedSize(true)
mon_recycler.layoutManager = LinearLayoutManager(this#ListeMeuble3DActivity)
mon_recycler.adapter = MeubleAdapter(listMeubles.toTypedArray()){}
}
override fun onCancelled(error: DatabaseError) {
TODO("Not yet implemented")
}
})
Error Handling :
So to handle my error:
i had to add a Default Value to each parametre in the constructor of my Data class :
data class Meuble(val imageResource: Int = -1, val nom: String="", val prix: Int=-1,val stock:Int=-1)

Retrieve data from Firebase on Android Studio

Can someone help me fix it?
Following code works without any error, however, it does not retrieve data from Firebase and show in the TextView.
private fun viewData() {
val postReference = FirebaseDatabase.getInstance().getReference("dataID")
val dbView= findViewById<TextView>(R.id.txtFdbData)
val postListener = object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
val post = dataSnapshot.getValue(Post::class.java)
dbView.text=post?.postName
}
override fun onCancelled(databaseError: DatabaseError) {
}
}
postReference.addValueEventListener(postListener)
Toast.makeText(this,"Retrieved",Toast.LENGTH_LONG).show()
}
Above code is called when I tap the button 'btnView'
viewButton = findViewById(R.id.btnView)
viewButton.setOnClickListener {
viewData()
}
When I hit the button it shows the toast message 'Retrieved' and the default value given in the TextView (txtFdbData) is deleted (or may be replaced with an empty string?, I do not know).
Following is the post Class
data class Post (
val postName: String="",
val postDescription:String="")
I am working on Android Studio, using Kotlin and Firebase Realtime Database.
You query to database return list of items. So loop through it and try to get Post. Check below:
override fun onDataChange(dataSnapshot: DataSnapshot) {
dataSnapshot.children.forEach {childSnapshot ->
val post = childSnapshot.getValue(Post::class.java)
dbView.text=post?.postName
}
}
getReference("dataID") is not your data node it is your parent node.
Then you have to access their children using getChildren() method.
Change you on data change method with this.
override fun onDataChange(dataSnapshot: DataSnapshot) {
for (postSnapshot : dataSnapshot.getChildren()) {
val post = postSnapshot .getValue(Post::class.java)
dbView.text=post?.postName
}
}

Populating Data Class via Simple Firebase Calls

Running into an error I have been researching and attempting to fix for the past couple weeks. There are tons of suggestions out there and I've tried at least half a dozen with the same result each time.
How does Kotlin access Firebase data and populate a very simple data class?
Error: com.google.firebase.database.DatabaseException:
Can't convert object of type java.lang.String to type com.touchtapapp.handsofhope.LandingTextTitles
Read about suggestions to first convert to a Map and then to my custom data class... attempted this, successfully created the Mapped values w/ correct data... but ran into the exact same error when sending the Mapped values to the customs data class (LandingTextTitles).
Current code:
Data Model Class
data class LandingTextTitles(
val subTitle: String,
val title: String
)
Method to retrieve data from firebase
private fun initTitles() {
val ref = FirebaseDatabase.getInstance().getReference("/landing")
ref.addListenerForSingleValueEvent(object: ValueEventListener {
override fun onDataChange(p0: DataSnapshot) {
p0.children.forEach {
val titles = it.getValue(LandingTextTitles::class.java)
}
}
override fun onCancelled(p0: DatabaseError) {
// Handle Cancelled Data
}
})
// Log the titles value to see if data passed correctly
Log.d("Titles", titles.toString())
}
When I log out something like Log.d(it.toString()), I see the keys and values just fine. What am I doing wrong here?
EDIT:
Firebase data snapshot
EDIT 2:
If we use Log.d("Titles", it.toString()), we get the following:
D/Titles: DataSnapshot { key = subTitle, value = Start Here. }
D/Titles: DataSnapshot { key = title, value = Facing unexpected problems? }
If you have the following database:
landing
randomId
subTitle : "Awesome"
title : "Developer Team"
Then you can retrieve title and subTitle by doing the following:
private fun initTitles() {
val ref = FirebaseDatabase.getInstance().getReference("/landing")
ref.addListenerForSingleValueEvent(object: ValueEventListener {
override fun onDataChange(p0: DataSnapshot) {
p0.children.forEach {
val title = it.child("title").getValue(String::class.java)
val subTitle = it.child("subTitle").getValue(String::class.java)
}
}
override fun onCancelled(p0: DatabaseError) {
// Handle Cancelled Data
}
})
// Log the titles value to see if data passed correctly
Log.d("Titles", titles.toString())
}
If you want to use the data class, then change this:
override fun onDataChange(p0: DataSnapshot) {
p0.children.forEach {
val titles = it.getValue(LandingTextTitles::class.java)
}
into this:
override fun onDataChange(p0: DataSnapshot) {
val titles = p0.getValue(LandingTextTitles::class.java)
}

Categories

Resources