I have been developing a chatting app in Android using Kotlin and Firebase. Registering, searching and sending message to a user, all of this has been successful. But I'm unable to generate a chatlist which is a list of the recent chats of the user. The user can tap on it to access that particular chat, just like any other chatting app.
The user is stored in a User model and the data is registered in the database in that same format.
I am able to display the profile picture of the user using the addValueEventListener method but when the similar method is invoked for the chatlist, it throws an error -
com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type kushwaha.samir.boop.models.User
This is the code where the error occurs -
val user = snapshot.getValue<User>(User::class.java!!)
present in the function - chatList()
Database view
MainActivityChat code >
class MainActivityChat : Fragment() {
lateinit var profile_image: CircleImageView
lateinit var firebaseUser: FirebaseUser
lateinit var reference: DatabaseReference
lateinit var referenceusers: DatabaseReference
lateinit var referenceuserschats: DatabaseReference
lateinit var referencechatlist: DatabaseReference
var root: View? = null
lateinit var auth: FirebaseAuth
lateinit var fragment: Fragment
var recyclerView: RecyclerView? = null
var userAdapter: UserAdapter? = null
var mUsers: MutableList<User>? = null
var fuser: FirebaseUser?=null
private var usersList: MutableList<Chatlist>? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
root = inflater.inflate(R.layout.activity_mainchat, container, false)
setHasOptionsMenu(true)
firebaseUser = FirebaseAuth.getInstance().currentUser!!
val uid = firebaseUser.uid
val floatingActionButton = root!!.findViewById(R.id.searchPerson) as FloatingActionButton
floatingActionButton.setOnClickListener {
val intent = Intent(activity, SearchActivity::class.java)
startActivity(intent)
}
fuser = FirebaseAuth.getInstance().currentUser!!
usersList = ArrayList()
reference = FirebaseDatabase.getInstance().getReference("Chatlist").child(fuser!!.uid)
referencechatlist = FirebaseDatabase.getInstance().getReference("Chatlist").child(fuser!!.uid)
profile_image = root!!.findViewById(R.id.profile_image)
firebaseUser = FirebaseAuth.getInstance().currentUser!!
FirebaseDatabase.getInstance().reference.child("Users").child(uid)
.addValueEventListener(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
val user = dataSnapshot.getValue(User::class.java)
// usernamedisplay.text = user!!.username
if (user!!.profileImageUrl == "default") {
profile_image.setImageResource(R.mipmap.ic_launcher)
Log.d(ProfileFragment.TAG, "No image retrieved/found")
} else {
//change this
context?.let { Glide.with(it).load(user.profileImageUrl).into(profile_image) }!!
Log.d(ProfileFragment.TAG, "Image set")
}
}
override fun onCancelled(databaseError: DatabaseError) {
}
})
reference = FirebaseDatabase.getInstance().getReference("Chats")
reference.addValueEventListener(object : ValueEventListener {
override fun onCancelled(p0: DatabaseError) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun onDataChange(dataSnapshot: DataSnapshot) {
var unread = 0
for (snapshot in dataSnapshot.children) {
val chat = snapshot.getValue<Chat>(Chat::class.java!!)
if (chat!!.receiver == firebaseUser!!.uid && !chat!!.isIsseen!!) {
unread++
}
}
reference = FirebaseDatabase.getInstance().getReference("Chatlist").child(fuser!!.uid)
reference.addValueEventListener(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
usersList!!.clear()
for (snapshot in dataSnapshot.children) {
val chatlist = snapshot.getValue<Chatlist>(Chatlist::class.java!!)
usersList!!.add(chatlist!!)
}
chatList()
}
override fun onCancelled(databaseError: DatabaseError) {
}
})
}
})
updateToken(FirebaseInstanceId.getInstance().token)
return root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
recyclerView = view!!.findViewById(R.id.recycler_viewmain)
recyclerView!!.setHasFixedSize(true)
recyclerView!!.layoutManager = LinearLayoutManager(context)
}
private fun updateToken(token: String?) {
val reference = FirebaseDatabase.getInstance().getReference("Tokens")
val token1 = Token(token!!)
reference.child(fuser!!.uid).setValue(token1)
}
private fun chatList() {
mUsers = ArrayList()
reference = FirebaseDatabase.getInstance().getReference("Users")
reference.addValueEventListener(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
mUsers!!.clear()
for (snapshot in dataSnapshot.children) {
**val user = snapshot.getValue<User>(User::class.java!!)**
for (chatlist in usersList!!) {
if (user!!.id == chatlist.id) {
mUsers!!.add(user)
}
}
}
userAdapter = UserAdapter(context!!, mUsers!!, true)
recyclerView!!.adapter = userAdapter
}
override fun onCancelled(databaseError: DatabaseError) {
}
})
}
private fun status(status: String) {
reference = FirebaseDatabase.getInstance().getReference("Users").child(firebaseUser!!.uid)
val hashMap = HashMap<String, Any>()
hashMap["status"] = status
reference.updateChildren(hashMap)
}
override fun onResume() {
super.onResume()
status("online")
}
override fun onPause() {
super.onPause()
status("offline")
}
companion object {
val TAG = "MainActivityChat"
}
}
User Model
class User {
var id: String? = null
var phoneno: String? = null
var profileImageUrl: String? = null
var search: String? = null
var status: String? = null
var username: String? = null
constructor(id: String, phoneno: String, profileImageUrl: String, search: String, status: String, username: String) {
this.id = id
this.phoneno = phoneno
this.profileImageUrl = profileImageUrl
this.search = search
this.status = status
this.username = username
}
constructor() {
}
}
Chatlist model
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
#Parcelize
class Chatlist(val id: String):
Parcelable {
constructor() : this("")
}
Logcat
2019-03-02 22:20:52.446 20562-20562/kushwaha.samir.boop E/AndroidRuntime: FATAL EXCEPTION: main
Process: kushwaha.samir.boop, PID: 20562
com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type kushwaha.samir.boop.models.User
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertBean(com.google.firebase:firebase-database##16.0.5:423)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToClass(com.google.firebase:firebase-database##16.0.5:214)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertToCustomClass(com.google.firebase:firebase-database##16.0.5:79)
at com.google.firebase.database.DataSnapshot.getValue(com.google.firebase:firebase-database##16.0.5:212)
at kushwaha.samir.boop.MainActivityChat$chatList$1.onDataChange(MainActivityChat.kt:187)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database##16.0.5:75)
at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database##16.0.5:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database##16.0.5:55)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6762)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
According to your comment, you say that when you try to log the content of your snapshot object you get:
{ key = status, value = offline }
Which obviously means that you are using a wrong reference. So you get that result because you are getting a reference in database for the status property which of type String and that's why you get that error:
com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type kushwaha.samir.boop.models.User
To solve this, please change the following line of code:
reference.addValueEventListener(object : ValueEventListener {}
to
val rootRef = FirebaseDatabase.getInstance().getReference()
val usersRef = rootRef.child("Users")
usersRef.addValueEventListener(object : ValueEventListener {}
Related
i'm trying to delete a document in my firestore database
i'm using a listview to list some things of my data base, the items of this listview have a delete button, what i want is: when the user presses the delete button, this thing gets deleted from the list and from the firestore, there what i'm trying:
this is my entire activity to do this:
class RigBuilderActivity : AppCompatActivity() {
lateinit var botaoAddPc: FloatingActionButton
lateinit var pcName:EditText
lateinit var infoButton:FloatingActionButton
lateinit var pcListView: ListView
companion object{
const val TAG = "RigBuilderActivity"
}
var pc = arrayListOf<PC>()
val pcAdapter = PcAdapter()
val db = Firebase.firestore
val userId = FirebaseAuth.getInstance().currentUser!!.uid
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_rig_builder)
botaoAddPc = findViewById(R.id.rig_builder_button_add_pc)
pcName = findViewById(R.id.rig_builder_text_input)
infoButton = findViewById(R.id.rig_builder_button_info)
pcListView = findViewById(R.id.rig_builder_pc_list)
botaoAddPc.setOnClickListener{
var pc_text :String = pcName.text.toString()
val computer = PC(UUID.randomUUID().toString(),pc_text)
db.collection("users").document(userId).collection("PC").add(computer.toHashmapPC()).addOnSuccessListener { task->
Log.d(TAG, "DocumentSnapshot added with ID: ${task.id}")
Toast.makeText(this,"Pc added",Toast.LENGTH_SHORT).show()
}.addOnFailureListener{ e->
Log.w(TAG,"Error Adding PC",e)
Toast.makeText(this,"Failed",Toast.LENGTH_SHORT).show()
}
}
pcListView.adapter = pcAdapter
db.collection("users").document(userId).collection("PC").addSnapshotListener{ value, e->
if (e!=null){
Log.w(TAG,"Listen failed.",e)
return#addSnapshotListener
}
pc.clear()
for (doc in value!!){
val pc = PC.fromQueryDoc(doc)
this.pc.add(pc)
}
pcAdapter.notifyDataSetChanged()
}
}
fun getPcName():String{
return pcName.toString()
}
inner class PcAdapter : BaseAdapter() {
override fun getCount(): Int {
return pc.size
}
override fun getItem(p0: Int): Any {
return pc[p0]
}
override fun getItemId(p0: Int): Long {
return 0
}
override fun getView(p0: Int, p1: View?, p2: ViewGroup?): View {
val rootView = layoutInflater.inflate(R.layout.pc_item_layout, p2,false )
val textViewPcName = rootView.findViewById<TextView>(R.id.pc_name)
val editButton = rootView.findViewById<ImageButton>(R.id.pc_edit_button)
val deleteButton = rootView.findViewById<FloatingActionButton>(R.id.pc_delete_button)
textViewPcName.text = pc[p0].counter.toString()
deleteButton.setOnClickListener{
val ref : DocumentReference = db.collection("users").document(userId).collection("PC").document(pc[p0].getPcId())
ref.delete().addOnSuccessListener {
Log.d(TAG,"Pc deleted with success")
Toast.makeText(this#RigBuilderActivity,"Deleted with success",Toast.LENGTH_SHORT).show()
}
pcAdapter.notifyDataSetChanged()
}
editButton.setOnClickListener{
}
textViewPcName.text = pc[p0].name
return rootView
}
}
}
in case of needing, this is my PC class, i'm just using one of the constructors to test the list and make the delete works:
class PC {
var id:String
var name : String? = null
var counter : Long? = null
lateinit var cpu :CPU
lateinit var gpu: GPU
lateinit var motherBoard: MotherBoard
/**
* Construtor de teste
*/
constructor(id:String, name:String?){
this.id = id
this.name = name
}
/**
* Construtor ainda a implementar
*/
constructor(id:String, name:String?, cpu: CPU,gpu: GPU,motherBoard: MotherBoard){
this.id = id
this.name = name
this.cpu = cpu
this.gpu = gpu
this.motherBoard = motherBoard
}
fun toHashmapPC() : HashMap <String, Any?>{
return hashMapOf(
"id" to id,
"name" to name
)
}
fun getPcId():String{
return id
}
companion object{
fun fromQueryDoc(documentSnapshot: DocumentSnapshot):PC{
return PC(
documentSnapshot["id"] as String,
documentSnapshot["name"] as String
)
}
}
}
Here is the error , whenever I tried to enter another activity which provide database information it shows :
2022-12-20 17:58:40.090 7261-7261/com.example.blood E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.blood, PID: 7261
com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type com.example.blood.utilities.User
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertBean(CustomClassMapper.java:436)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToClass(CustomClassMapper.java:232)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertToCustomClass(CustomClassMapper.java:80)
at com.google.firebase.database.DataSnapshot.getValue(DataSnapshot.java:203)
at com.example.blood.activities.NewsfeedActivity$getUserData$1.onDataChange(NewsfeedActivity.kt:43)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(ValueEventRegistration.java:75)
at com.google.firebase.database.core.view.DataEvent.fire(DataEvent.java:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(EventRaiser.java:55)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:236)
at android.app.ActivityThread.main(ActivityThread.java:8057)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:620)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1011)
My Code:
class NewsfeedActivity:AppCompatActivity () {
private lateinit var dbref: DatabaseReference
private lateinit var userRecyclerView: RecyclerView
private lateinit var userArrayList: ArrayList<User>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_newsfeed)
userRecyclerView = findViewById(R.id.userList)
userRecyclerView.layoutManager = LinearLayoutManager(this)
userRecyclerView.setHasFixedSize(true)
userArrayList = arrayListOf<User>()
getUserData()
}
private fun getUserData() {
dbref = FirebaseDatabase.getInstance().getReference("Users")
dbref.addValueEventListener(object : ValueEventListener{
override fun onDataChange(snapshot: DataSnapshot) {
if (snapshot.exists()){
for (userSnapshot in snapshot.children){
val user = userSnapshot.getValue(User::class.java)
userArrayList.add(user!!)
}
userRecyclerView.adapter=MyAdapter(userArrayList)
}
}
override fun onCancelled(error: DatabaseError) {
finish()
}
})
}
User Data Class Code Where I am using these:
data class User(
val name: String? = null,
val email: String? = null,
val phoneNumber: String? = null,
val bloodGroup: String? = null,
val cityName: String? = null,
val availabality: String? = null
)
Previously I tried the set all the argument of Data class at null.
It looks like one of the values under /Users in your database is a plain string value, rather than a User object. Have a look at your data in the Firebase console to see which child that is.
I've been struggling with the problem for a long time and I can't solve it.I'm in EditActivity trying to add a key to the data from the firebase that I get from it with the help of Ad and process it using the AdsManager.
The key should not be equal to zero. In this line I check if the key is zero, then the Firebase writes data to empty.db.child (ad.key?: "Empty"). SetValue (ad). When I load the data to the Firebase, it shows them empty. Without displaying the key. You know what the problem is?
Ad
data class Ad(
var user_id : String? = null ,
var name : String? = null ,
var button1 : String? = null ,
val textTex : String? = null ,
val textk : String? = null ,
val description : String? = null,
val name_ads: String?=null,
val key :String? =null
)
AdsManager
class AdsManager(val readDataColbak : ReadDataColbak?) {
private lateinit var auth: FirebaseAuth
val db =Firebase.database.getReference("main")
fun pubilshAd(ad :Ad) {
db.child(ad.key?: "empty").setValue(ad)
}
fun ReadDataDb() {
db.addListenerForSingleValueEvent(object :ValueEventListener{
override fun onDataChange(snapshot : DataSnapshot) {
val adArray =ArrayList<Ad>()
for (item in snapshot.children){
val ad =item.children.iterator().next().child("ad").getValue(Ad::class.java)
adArray.add(ad !!)
}
readDataColbak?.readData(adArray)
}
override fun onCancelled(error : DatabaseError) {
}
})
}
}
EditActivity1
class EditActivity1: AppCompatActivity(), FfragmentInterfes{
lateinit var mBinder : ActivityEdit1Binding
private var dialog=D()
private var chooseImageFrog:FragmentList? =null
val adsManager = AdsManager(null)
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
imageAdapter = ImageAdapter()
mBinder=ActivityEdit1Binding.inflate(layoutInflater)
setContentView(mBinder.root)
init()
}
fun onClickPublish(view : View) {
adsManager.pubilshAd(fillAd())
}
private fun fillAd() : Ad {
var ad : Ad
mBinder.apply {
ad= Ad(
name_ads.text.toString(),
user_id.text.toString(),
name.text.toString(),
button1.text.toString(),
description.text.toString(),
textk.text.toString(),
adsManager.db.push().key
)
}
return ad
}
I'm getting a Firebase DatabaseException "Can't convert object of type java.util.ArrayList to type com.muasya.clientapp.Model.FoodModel" when I click that process application crashes and shows the error any idea about the error and how to fix it
2021-06-12 08:52:11.816 4753-4753/com.muasya.clientapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.muasya.clientapp, PID: 4753
com.google.firebase.database.DatabaseException: Can't convert object of type java.util.ArrayList to type com.muasya.clientapp.Model.FoodModel
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertBean(CustomClassMapper.java:436)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToClass(CustomClassMapper.java:232)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertToCustomClass(CustomClassMapper.java:80)
at com.google.firebase.database.DataSnapshot.getValue(DataSnapshot.java:203)
at com.muasya.clientapp.HomeActivity$onBestDealFoodItemClick$1$onDataChange$1.onDataChange(HomeActivity.kt:304)
at com.google.firebase.database.Query$1.onDataChange(Query.java:191)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(ValueEventRegistration.java:75)
at com.google.firebase.database.core.view.DataEvent.fire(DataEvent.java:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(EventRaiser.java:55)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6153)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:892)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:782)
This is my HomeActiviy.kt
#Subscribe(sticky = true,threadMode = ThreadMode.MAIN)
fun onBestDealFoodItemClick(event: BestDealItemClick)
{
if (event.model != null)
{
dialog!!.show()
FirebaseDatabase.getInstance()
.getReference("Category")
.child(event.model!!.menu_id!!)
.addListenerForSingleValueEvent(object:ValueEventListener{
override fun onCancelled(p0: DatabaseError) {
dialog!!.dismiss()
Toast.makeText(this#HomeActivity, ""+p0.message,Toast.LENGTH_SHORT).show()
}
override fun onDataChange(p0: DataSnapshot) {
if (p0.exists())
{
Common.categorySelected = p0.getValue(CategoryModel::class.java)
//Load food
FirebaseDatabase.getInstance()
.getReference("Category")
.child(event.model!!.menu_id!!)
.child("foods")
.orderByChild("id")
.equalTo(event.model.food_id)
.limitToLast(1)
.addListenerForSingleValueEvent(object:ValueEventListener{
override fun onCancelled(p0: DatabaseError) {
dialog!!.dismiss()
Toast.makeText(this#HomeActivity, ""+p0.message,Toast.LENGTH_SHORT).show()
}
override fun onDataChange(snapshot: DataSnapshot) {
if (p0.exists())
{
for (foodSnapshot in p0.children)
Common.foodSelected = foodSnapshot.getValue(FoodModel::class.java)
navController!!.navigate(R.id.nav_food_detail)
}
else
{
Toast.makeText(this#HomeActivity, "Item doesn't exist",Toast.LENGTH_SHORT).show()
}
dialog!!.dismiss()
}
})
}
else
{
dialog!!.dismiss()
Toast.makeText(this#HomeActivity, "Item doesn't exist",Toast.LENGTH_SHORT).show()
}
}
})
}
}
Common.kt
object Common {
val COMMENT_REF: String="Comments"
var foodSelected: FoodModel?=null
var categorySelected: CategoryModel?=null
val CATEGORY_REF: String ="Category"
val FULL_WIDTH_COLUMN: Int = 1
val DEFAULT_COLUMN_COUNT: Int = 0
val BEST_DEALS_REF: String="BestDeals"
val POPULAR_REF:String="MostPopular"
val USER_REFERENCE="Users"
var currentUser:UserModel?=null
FoodModel.kt
class FoodModel {
var key: String?=null
var name: String?=null
var image: String?=null
var id: String?=null
var description: String?=null
var price: Long=0
var addon: List<AddonModel> = ArrayList<AddonModel>()
var size: List<SizeModel> = ArrayList<SizeModel>()
var ratingValue:Double = 0.toDouble()
var ratingCount:Long = 0.toLong()
CategoryModel.kt
package com.muasya.clientapp.Model
class CategoryModel {
var menu_id:String?=null
var name:String?=null
var image:String?=null
var foods:List<FoodModel>?=null
}
Firebase realtime database
Firebase realtime database
category node
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)