How to check inside Unknown Child Value, Firebase Database? - android

Database Structure
I have the database structure shown in the image,
and I am using the following reference to retrieve the child values.
private fun readNotificationComments() {
val notifRef = FirebaseDatabase.getInstance().reference
.child("Notifications")
.child(FirebaseAuth.getInstance().currentUser!!.uid)
.child("Comments")
.child(/*unknown child*/)
notifRef.addValueEventListener(object : ValueEventListener{
override fun onDataChange(dataSnapshot: DataSnapshot) {
if(dataSnapshot.exists()){
(notificationList as ArrayList<Notification>).clear()
for(snapshot in dataSnapshot.children)
{
val notification = snapshot.getValue(Notification::class.java)
(notificationList as ArrayList<Notification>).add(notification!!)
}
Collections.reverse(notificationList);
notificationAdapter!!.notifyDataSetChanged()
refresh = true
swipe_refresh_comments.isRefreshing = false
}
}
override fun onCancelled(error: DatabaseError) {
TODO("Not yet implemented")
}
})
}
Now my problem is that the value "-MYxVs5l5bmRA-rf9PSt" is unknown and created randomly, how to make changes so that it the function looks for data past that unknown child value?
This is the model class
class Notification
{
private var userid: String = ""
private var text: String = ""
private var postid: String = ""
private var ispost: Boolean = false
constructor()
constructor(userid: String, text: String, postid: String, ispost: Boolean) {
this.userid = userid
this.text = text
this.postid = postid
this.ispost = ispost
}
fun getUserId(): String
{
return userid
}
fun setUserId(userid: String)
{
this.userid = userid
}
fun getPostId(): String
{
return postid
}
fun setPostId()
{
this.postid = postid
}
fun getText(): String
{
return text
}
fun setText(text: String)
{
this.text = text
}
fun getIsPost(): Boolean
{
return ispost
}
fun setIsPost(ispost: Boolean)
{
this.ispost = ispost
}
}

Related

No setter/field 'image' found on class 'model'

I already find question-related to my problem but I still don't really get the idea. I want to get data images from the database URL in firebase storage using glide. but my logcat shows this line.
2023-02-14 10:02:36.417 25063-25063/com.isjieman.ocion W/ClassMapper: No setter/field for post_image found on class com.isjieman.ocion.model.Post
2023-02-14 10:02:36.436 25063-25063/com.isjieman.ocion W/ClassMapper: No setter/field for background_image found on class com.isjieman.ocion.model.User
2023-02-14 10:02:36.436 25063-25063/com.isjieman.ocion W/ClassMapper: No setter/field for profile_image found on class com.isjieman.ocion.model.User
2023-02-14 10:02:36.438 25063-25063/com.isjieman.ocion W/Glide: Load failed for with size [960x240]
class com.bumptech.glide.load.engine.GlideException: Failed to load resource
the problem is only for field image on the model. i already succeed on retrieve the other data from firebase except the image only. how do i solve this more technically? glad if someone wants to explain my problem
here's the database structure
{
"Posts": {
"-NNsor5WiX9wxTDf7qo5": {
"category": "Art",
"description": "tes 123",
"duration": "-",
"paymentMethods": "e-wallet",
"postId": "-NNsor5WiX9wxTDf7qo5",
"post_image": "https://firebasestorage.googleapis.com/v0/b/final-project-idn.appspot.com/o/Posts%20Pictures%2F1675990621049.jpg?alt=media&token=f7b747c0-1efe-4f43-9ff1-729c7d99c7c1",
"priceRange": "Rp 0 - 10.000",
"publisher": "6FzpJ2sQC9gewbUIGHB8hiNWK1z2",
"title": "tes"
}
},
"User": {
"6FzpJ2sQC9gewbUIGHB8hiNWK1z2": {
"background_image": "https://firebasestorage.googleapis.com/v0/b/final-project-idn.appspot.com/o/Default%20Images%2Fimg_background.png?alt=media&token=b51e7cf5-2015-4cc4-9583-159373d081e2",
"bio": "Member of NCT",
"email": "mark#gmail.com",
"link": "",
"profile_image": "https://firebasestorage.googleapis.com/v0/b/final-project-idn.appspot.com/o/Profile%20Pictures%2F6FzpJ2sQC9gewbUIGHB8hiNWK1z2.jpg?alt=media&token=d174fad9-2f8c-4964-83ec-549f18876587",
"uid": "6FzpJ2sQC9gewbUIGHB8hiNWK1z2",
"userName": "marklee"
}
}
}
here's my User model
class User {
private var uid: String = "0"
private var userName: String = ""
private var email: String = ""
private var bio: String? = null
private var link: String? = null
private var profile_image: String = ""
private var background_image: String = ""
constructor()
constructor(uid : String, userName : String, email : String, bio : String, link : String, profile_image : String, background_image : String){
this.uid = uid
this.userName = userName
this.email = email
this.bio = bio
this.link = link
this.profile_image = profile_image
this.background_image = background_image
}
//function UID
fun getUID(): String{
return uid
}
fun setUID(uid: String){
this.uid = uid
}
//function User Name
fun getUserName(): String{
return userName
}
fun setUserName(userName: String){
this.userName = userName
}
//function Email
fun getEmail(): String{
return email
}
fun setEmail(email: String){
this.email = email
}
//function bio
fun getBio(): String?{
return bio
}
fun setBio(bio: String?){
this.bio = bio
}
//function link
fun getLink(): String?{
return link
}
fun setLink(link: String?){
this.link = link
}
//function Profile Image
fun getProfileImage(): String{
return profile_image
}
fun setProfileImage(profile_image: String){
this.profile_image = profile_image
}
//function Background Image
fun getBackgroundImage(): String{
return background_image
}
fun setBackgroundImage(background_image: String){
this.background_image = background_image
}
}
here's Post model
class Post {
private var postId: String = ""
private var title: String = ""
private var post_image: String = ""
private var description: String = ""
private var category: String = ""
private var priceRange: String = ""
private var duration: String = ""
private var paymentMethods: String = ""
private var publisher: String = ""
constructor()
constructor(
postId: String,
title: String,
post_image: String,
description: String,
category: String,
priceRange: String,
duration: String,
paymentMethods: String,
publisher: String
) {
this.postId = postId
this.title = title
this.post_image = post_image
this.description = description
this.category = category
this.priceRange = priceRange
this.duration = duration
this.paymentMethods = paymentMethods
this.publisher = publisher
}
//Get
fun getPostId(): String{
return postId
}
fun getTitle(): String{
return title
}
fun getPostImage(): String{
return post_image
}
fun getDescription(): String{
return description
}
fun getCategory(): String{
return category
}
fun getPriceRange(): String{
return priceRange
}
fun getDuration(): String{
return duration
}
fun getPaymentMethods(): String{
return paymentMethods
}
fun getPublisher(): String{
return publisher
}
//Set
fun setPostId(postId: String){
this.postId = postId
}
fun setTitle(title: String){
this.title = title
}
fun setPostImage(post_image: String){
this.post_image = post_image
}
fun setDescription(description: String){
this.description = description
}
fun setCategory(category: String){
this.category = category
}
fun setPriceRange(priceRange: String){
this.priceRange = priceRange
}
fun setDuration(duration: String){
this.duration = duration
}
fun setPaymentMethods(paymentMethods: String){
this.paymentMethods = paymentMethods
}
fun setPublisher(publisher: String){
this.publisher = publisher
}
}
here's my PostAdapter.kt
class PostAdapter(private val mContext: Context,
private val mPost: List<Post>) : RecyclerView.Adapter<PostAdapter.ViewHolder>()
{
private var firebaseUser: FirebaseUser? = null
inner class ViewHolder(#NonNull itemView: View) : RecyclerView.ViewHolder(itemView){
var profileImage: CircleImageView
var tvUsername: TextView
var likeButton: ImageButton
var tvTitle: TextView
var tvPrice: TextView
var tvDescription: TextView
var tvSeeMore: TextView
var postImage: ImageView
init {
profileImage = itemView.findViewById(R.id.cvProfile)
tvUsername = itemView.findViewById(R.id.tvCvUsername)
likeButton = itemView.findViewById(R.id.cvFav)
tvTitle = itemView.findViewById(R.id.tvCvTitle)
tvPrice = itemView.findViewById(R.id.tvCvPrice)
tvDescription = itemView.findViewById(R.id.tvCvDesc)
tvSeeMore = itemView.findViewById(R.id.tvCvSeeMore)
postImage = itemView.findViewById(R.id.ivPostImage)
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(mContext).inflate(R.layout.item_timeline, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
firebaseUser = FirebaseAuth.getInstance().currentUser
val post = mPost[position]
Glide.with(mContext.applicationContext).load(post.getPostImage()).into(holder.postImage)
holder.tvTitle.text = post.getTitle()
holder.tvDescription.text = post.getDescription()
holder.tvPrice.text = post.getPriceRange()
publisherInfo(holder.profileImage, holder.tvUsername, post.getPublisher())
}
private fun publisherInfo(
profileImage: CircleImageView,
tvUsername: TextView,
publisher: String
) {
val usersRef = FirebaseDatabase.getInstance().reference.child("User").child(publisher)
usersRef.addValueEventListener(object : ValueEventListener{
override fun onDataChange(snapshot: DataSnapshot) {
if (snapshot.exists())
{
val user = snapshot.getValue(User::class.java)
Glide.with(mContext.applicationContext).load(user!!.getProfileImage()).into(profileImage)
tvUsername.text = user!!.getUserName()
}
}
override fun onCancelled(error: DatabaseError) {
Toast.makeText(mContext, error.message, Toast.LENGTH_LONG).show()
}
})
}
override fun getItemCount(): Int {
return mPost.size
}
}
any help i would really appreciate. thanks
You are getting the following warning:
No setter/field for post_image found on class com.isjieman.ocion.model.Post
Because in the Post class, you have an incorrect getter for the post_image field. The getter is defined as:
fun getPostImage(): String{
return post_image
}
While it should be defined as:
fun getPost_image(): String{
return post_image
}
You're getting the following warnings:
No setter/field for background_image found on class com.isjieman.ocion.model.User
No setter/field for profile_image found on class com.isjieman.ocion.model.User
Due to the exact same reason as above. You have these getters:
fun getBackgroundImage(): String{
return background_image
}
fun getProfileImage(): String{
return profile_image
}
Which should have been defined as:
fun getBackground_image(): String{
return background_image
}
fun getProfile_image(): String{
return profile_image
}
Bear in mind that Firebase Realtime Database serializes/deserializes any public fields and public properties that follow JavaBean naming conventions for getters and setters. That's the reason why you got those warnings.

How do I set a child value of a Firebase Realtime Database when using a ViewModel and LiveData?

I have the following data class that holds the child values of a specific reference from the Firebase Realtime Database:
data class Users(
val uid: String = "",
var firstName: String = "",
var lastName: String = "",
)
This is my ViewModel:
class UsersViewModel : ViewModel() {
private val uid = Firebase.auth.currentUser!!.uid
private val USERS_REF: DatabaseReference = FirebaseDatabase.getInstance().getReference("/users/$uid")
private val liveData: FirebaseQueryLiveData = FirebaseQueryLiveData(USERS_REF)
private val usersLiveData: MediatorLiveData<Users> = MediatorLiveData()
init {
usersLiveData.addSource(liveData, object : Observer<DataSnapshot> {
override fun onChanged(dataSnapshot: DataSnapshot?) {
if (dataSnapshot != null) {
usersLiveData.postValue(dataSnapshot.getValue(Users::class.java))
} else {
usersLiveData.value = null
}
}
})
}
#NonNull
fun getUsersLiveData() : LiveData<Users> {
return usersLiveData
}
}
This is my extended LiveData:
class FirebaseQueryLiveData(ref: DatabaseReference) : LiveData<DataSnapshot>() {
private val query: Query = ref
private val listener: MyValueEventListener = MyValueEventListener()
private var listenerRemovePending = false
private val removeListener = object : Runnable {
override fun run() {
query.removeEventListener(listener)
listenerRemovePending = false
}
}
override fun onActive() {
super.onActive()
if (listenerRemovePending) {
Handler(Looper.getMainLooper()).removeCallbacks(removeListener)
} else {
query.addValueEventListener(listener)
}
listenerRemovePending = false
}
override fun onInactive() {
super.onInactive()
Handler(Looper.getMainLooper()).postDelayed(removeListener, 2000)
query.removeEventListener(listener)
}
private inner class MyValueEventListener : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
value = snapshot
}
override fun onCancelled(error: DatabaseError) {
return
}
}
}
For reading the values from my database in my Activity or Fragment, this is what I've done:
val usersViewModel = ViewModelProvider(this).get(UsersViewModel::class.java)
val usersLiveData = usersViewModel.getUsersLiveData()
usersLiveData.observe(this, object : Observer<Users> {
override fun onChanged(users: Users?) {
if (users != null) {
firstNameTextView.text = users.firstName
lastNameTextView.text = users.lastName
}
}
})
This all works, but my question is how do I write to a specific child for my database in my Activity or Fragment? For example, let's say I want to only modify the lastName child? How do I do that? I don't have any references to FirebaseDatabase in my activities and fragments because the ViewModel and LiveData ensure that I don't need them anymore.

RecycleViewer not showing anything in the list after update in Firebase database

I got a problem and I can't see an error in my code, maybe You'll help me. I've got an application in Android Studio that uses connection with Firebase. I add products to the database by a button and in the activity that holds RecycleViever, it lists that product there. The problem is that RecycleViewer shows nothing, even though that my button adds product to the Firebase. That RecycleViewer should list products from Firebase. I add product with It's structure:
data class Product(var name: String, var price: Double, var quantity: Long, var bought: Boolean) {
var id: String = ""
companion object {
fun fromContentValues(values: ContentValues?): Product {
values?.let{
return Product(
values.getAsString("name"),
values.getAsDouble("price"),
values.getAsLong("amount"),
values.getAsBoolean("bought"))
} ?: throw IllegalArgumentException()
}
}
#Exclude
fun toMap(): Map<String, Any?> {
return mapOf(
"id" to id,
"name" to name,
"price" to price,
"quantity" to quantity,
"bought" to bought
)
}
}
Product Repository:
class ProductRepository(private val dbRef: DatabaseReference) {
fun insert(product: Product) {
val key = dbRef.push().key
if (key == null) {
Log.w("error", "Couldn't get push key for posts")
return
}
product.id = key
val productValues = product.toMap()
val childUpdates = hashMapOf<String, Any>(
key to productValues
)
dbRef.updateChildren(childUpdates)
}
fun update(product: Product){
val productValues = product.toMap()
val childUpdates = hashMapOf<String, Any>(
product.id to productValues
)
dbRef.updateChildren(childUpdates)
}
fun delete(key: String){
dbRef.child(key).removeValue()
}
}
Product ViewModel:
class ProductViewModel(app: Application) : AndroidViewModel(app) {
private val repo: ProductRepository
val allProducts: MutableList<Product>
init {
allProducts = arrayListOf()
val database = FirebaseDatabase.getInstance()
val reference : DatabaseReference = database.getReference("database/products")
var name: String
var price: Double
var amount: Long
var bought: Boolean
reference.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
for (product in snapshot.children) {
name = product.child("name").value as String
price = product.child("price").value as Double
amount = product.child("amount").value as Long
bought = product.child("bought").value as Boolean
val newProduct = Product(name, price, amount, bought)
allProducts.add(newProduct)
}
}
override fun onCancelled(error: DatabaseError) {
Log.w("error", "loadPost:onCancelled", error.toException())
}
})
repo = ProductRepository(reference)
}
fun insert(product: Product) {
repo.insert(product)
}
fun update(product: Product) {
repo.update(product)
}
fun delete(product: Product) {
repo.delete(product.id)
}
}
My Adapter:
class ProductsAdapter(val productViewModel: ProductViewModel) : RecyclerView.Adapter<ProductsAdapter.ViewHolder>() {
private var products = mutableListOf<Product>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ProductsAdapter.ViewHolder {
val inflater = LayoutInflater.from(parent.context)
val view = ListElementBinding.inflate(inflater)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ProductsAdapter.ViewHolder, position: Int) {
val currentProduct = products[position]
holder.binding.rvTv1.text = currentProduct.name
holder.binding.rvTv2.text = currentProduct.price.toString()
holder.binding.rvTv3.text = currentProduct.amount.toString()
holder.binding.rvCb1.isChecked = currentProduct.bought
holder.binding.bted.setOnClickListener {
currentProduct.name = holder.binding.rvTv1.text.toString()
currentProduct.price = holder.binding.rvTv2.text.toString().toDouble()
currentProduct.amount = holder.binding.rvTv3.text.toString().toLong()
currentProduct.bought = holder.binding.rvCb1.isChecked
productViewModel.update(currentProduct)
}
holder.binding.btdel.setOnClickListener {
productViewModel.delete(currentProduct)
products.remove(currentProduct)
notifyDataSetChanged()
}
}
override fun getItemCount(): Int = products.size
inner class ViewHolder(val binding: ListElementBinding) : RecyclerView.ViewHolder(binding.root)
fun setProducts() {
this.products = productViewModel.allProducts
notifyDataSetChanged()
}
fun addProduct(product: Product) {
productViewModel.insert(product)
notifyDataSetChanged()
}
}
And finally activity that Lists it all:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = ActivityListBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.rv1.layoutManager = LinearLayoutManager(baseContext)
binding.rv1.addItemDecoration(DividerItemDecoration(baseContext, DividerItemDecoration.VERTICAL))
val productViewModel = ProductViewModel(this.application)
binding.rv1.adapter = ProductsAdapter(productViewModel)
(binding.rv1.adapter as ProductsAdapter).setProducts()
binding.bt5.setOnClickListener() {
val name = et1.text.toString()
val price = et3.text.toString().toDouble()
val amount = et2.text.toString().toLong()
val bought = false
val product = Product(name, price, amount, bought)
(binding.rv1.adapter as ProductsAdapter).addProduct(product)
et1.text.clear()
et2.text.clear()
et3.text.clear()
}
binding.rv1.adapter = ProductsAdapter(productViewModel)
}
}
I literally have no idea, why it's not showing anything. Maybe You can help me.

Problem in retrieving chat message from firebase

I am trying to build a chatting application but whenever I click on the any of the users it crashes.
class MessegeActivity : AppCompatActivity() {
var userIdVisit: String = ""
var currentUserId : FirebaseUser?=null
var chatsAdpater:ChatAdpater?=null
var mChatList:List<Chat>?=null
lateinit var recycler_view_chat:RecyclerView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_messege)
intent = intent
userIdVisit = intent.getStringExtra("visit_id")
currentUserId =FirebaseAuth.getInstance().currentUser!!
recycler_view_chat =findViewById(R.id.recycler_view_chat)
recycler_view_chat.setHasFixedSize(true)
var linearLayoutManager =LinearLayoutManager(applicationContext)
linearLayoutManager.stackFromEnd =true
recycler_view_chat.layoutManager =linearLayoutManager
//showing other username and profile dp
val reference = FirebaseDatabase.getInstance().reference
.child("Users").child(userIdVisit)
reference.addValueEventListener(object : ValueEventListener {
override fun onDataChange(p0: DataSnapshot) {
val user: Users? = p0.getValue(Users::class.java)
username_mchat.text = user!!.getFullName()
Picasso.get().load(user.getImg()).into(profile_image_mchat)
retreiveMsg(currentUserId!!.uid,userIdVisit,user.getImg())
}
override fun onCancelled(error: DatabaseError) {
}
})
send_messege_btn.setOnClickListener {
val messege = text_messege.text.toString()
if (messege == "") {
Toast.makeText(this#MessegeActivity, "Please write something!!", Toast.LENGTH_SHORT)
.show()
} else {
sendMessegeToUser(currentUserId!!.uid, userIdVisit, messege)
}
text_messege.setText("")
}
attach_image_file.setOnClickListener {
val intent = Intent()
intent.action = Intent.ACTION_GET_CONTENT
intent.type = "image/*"
startActivityForResult(Intent.createChooser(intent, "Pick Image"), 198)
}
}
private fun sendMessegeToUser(senderId: String, receiverId: String?, messege: String) {
val reference = FirebaseDatabase.getInstance().reference
val messegeKey:String = reference.push().key!!
val messegeHashMap = HashMap<String, Any?>()
messegeHashMap["sender"] = senderId
messegeHashMap["messege"] = messege
messegeHashMap["receiver"] = receiverId
messegeHashMap["isseen"] = "false"
messegeHashMap["url"] = ""
messegeHashMap["messegeId"] = messegeKey
reference.child("Chats").child(messegeKey).setValue(messegeHashMap)
.addOnCompleteListener { task ->
if (task.isSuccessful) {
val ChatsListRefernce =
FirebaseDatabase.getInstance().reference.child("ChatLists").child(currentUserId!!.uid).child(userIdVisit)
ChatsListRefernce.addListenerForSingleValueEvent(object :ValueEventListener{
override fun onDataChange(p0: DataSnapshot) {
if(!p0.exists())
{
ChatsListRefernce.child("id").setValue(userIdVisit)
}
val ChatsListReceiverRefernce =
FirebaseDatabase.getInstance().reference.child("ChatLists").child(userIdVisit).child(currentUserId!!.uid)
ChatsListReceiverRefernce.child("id").setValue(currentUserId!!.uid)
}
override fun onCancelled(error: DatabaseError) {
}
})
//notification
// val reference = FirebaseDatabase.getInstance().reference
// .child("Users").child(currentUserId!!.uid)
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == 198 && resultCode ==RESULT_OK && data!=null && data.data != null) {
val progressBar = ProgressDialog(this)
progressBar.setMessage("Please wait")
progressBar.show()
val fileUri = data.data
val storageRef = FirebaseStorage.getInstance().reference.child("Chat Images")
val ref = FirebaseDatabase.getInstance().reference
val messegeId = ref.push().key
val filepath = storageRef.child("$messegeId.jpg")
var uploadTask: StorageTask<*>
uploadTask = filepath.putFile(fileUri!!)
uploadTask.continueWithTask(Continuation<UploadTask.TaskSnapshot, Task<Uri>> { task ->
if (!task.isSuccessful) {
task.exception?.let {
throw it
}
}
return#Continuation filepath.downloadUrl
}).addOnCompleteListener { task ->
val downloadUrl = task.result
val url = downloadUrl.toString()
val messegeHashMap = HashMap<String,Any?>()
messegeHashMap["sender"] = currentUserId!!.uid
messegeHashMap["messege"] = "sent you an image"
messegeHashMap["receiver"] = userIdVisit
messegeHashMap["isseen"] = "false"
messegeHashMap["url"] = url
messegeHashMap["messegeId"] = messegeId.toString()
ref.child("Chats").child(messegeId!!).setValue(messegeHashMap)
progressBar.dismiss()
}
}
}
private fun retreiveMsg(senderId: String, receiverId: String?, recieverimgUrl: String?) {
mChatList =ArrayList()
val reference =FirebaseDatabase.getInstance().reference.child("Chats")
reference.addValueEventListener(object:ValueEventListener{
override fun onDataChange(p0: DataSnapshot) {
(mChatList as ArrayList<Chat>).clear()
for (snapshot in p0.children)
{
val chat= snapshot.getValue(Chat::class.java)
if(chat!!.getReceiver().equals(senderId)&& chat.getSender().equals(receiverId) ||
chat.getReceiver().equals(receiverId)&& chat.getSender().equals(senderId))
{
(mChatList as ArrayList<Chat>).add(chat)
}
chatsAdpater = ChatAdpater(this#MessegeActivity,(mChatList as ArrayList<Chat>),recieverimgUrl!!)
recycler_view_chat.adapter =chatsAdpater
}
}
override fun onCancelled(error: DatabaseError) {
TODO("Not yet implemented")
}
})
}
}
package com.insidecoderz.trails2.Model
class Chat {
private var sender:String =""
private var messege:String =""
private var receiver:String =""
private var isseen :Boolean= false
private var url:String =""
private var messegeId:String =""
constructor()
constructor(
sender: String,
messege: String,
receiver: String,
isseen:Boolean,
url: String,
messegeId: String
) {
this.sender = sender
this.messege = messege
this.receiver = receiver
this.isseen = isseen
this.url = url
this.messegeId = messegeId
}
fun getSender(): String?{
return sender
}
fun setSender(sender: String){
this.sender =sender
}
fun getMessege(): String?{
return messege
}
fun setMessege(messege: String){
this.messege =messege
}
fun getReceiver(): String?{
return receiver
}
fun setReceiver(receiver: String){
this.receiver =receiver
}
fun isIsSeen(): Boolean {
return isseen
}
fun setIsSeen(isseen: Boolean){
this.isseen =isseen
}
fun getUrl(): String?{
return url
}
fun setUrl(url: String){
this.url =url
}
fun getMessegeId(): String?{
return messegeId
}
fun setMessegeId(messegeId: String){
this.messegeId =messegeId
}
}
I am facing this issue again and again, whenever I run the application in the application in the emulator it crashes with showing this error.
2020-08-22 23:19:59.920 17005-17005/com.insidecoderz.trails2 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.insidecoderz.trails2, PID: 17005
com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.Boolean to type com.insidecoderz.trails2.Model.Chat
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertBean(CustomClassMapper.java:435)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToClass(CustomClassMapper.java:231)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertToCustomClass(CustomClassMapper.java:79)
at com.google.firebase.database.DataSnapshot.getValue(DataSnapshot.java:203)
at com.insidecoderz.trails2.MessegeActivity$retreiveMsg$1.onDataChange(MessegeActivity.kt:202)
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:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:224)
at android.app.ActivityThread.main(ActivityThread.java:7134)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:536)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:876)
If you access the id of the user with the following code val reference = FirebaseDatabase.getInstance().reference.child("Users").child(userIdVisit) and then you try to get the data as a model Chat you can not do that, instead try FirebaseDatabase.getInstance().reference.child("Users").This way you'll be able to get your data as model Chat but it won't be the id you want, also if at the node "Users" you have more users then you'll obtain all the users info using the model Chat
If you need the information for the userIdVisit then you can you do the following
snapshot.child("userInfo1").getValue();
snapshot.child("userInfo2").getValue();
This is the sample for java, you should adapt it for kotlin, I'm sorry for not providing the sample in kotlin but I'm not familiar with it

Cant convert object of String to Model Class in android kotlin

I tried to retrieve data from Firebase using the childeventlistener. I have seen all the methods available on stackoverflow to resolve the difficulty but nothing worked.Code is given below
ViewModel
class AccepyReqViewModel : ViewModel() {
companion object {
const val TAG = "AcceptViewModel"
}
private val _userdetail = MutableLiveData<User>()
val userdetail: LiveData<User>
get() = _userdetail
private val userid = FirebaseAuth.getInstance().currentUser?.uid
private val chatrequest = "CHATREQ"
private val db_chat = FirebaseDatabase.getInstance().getReference(chatrequest)
private val company_info = "User_Info"
private val db_company = FirebaseDatabase.getInstance().getReference(company_info)
private val reqchildeventlister = object : ChildEventListener {
override fun onCancelled(error: DatabaseError) {}
override fun onChildMoved(snapshot: DataSnapshot, p1: String?) {
}
override fun onChildChanged(snapshot: DataSnapshot, p1: String?) {
}
override fun onChildAdded(snapshot: DataSnapshot, p1: String?) {
val getid = snapshot.getValue(Request::class.java)
val id = getid!!.id
val requesttype = getid.requesttype
Log.d(TAG, "Second function to be called")
Log.d(TAG, "$requesttype request type")
id?.let { getDetails(it) }
Log.d(TAG, "$id ID passed")
}
override fun onChildRemoved(snapshot: DataSnapshot) {
}
}
fun getRequest() {
Log.d(TAG, "getRequest method called 1st fun")
db_chat.child(userid!!).addChildEventListener(reqchildeventlister)
}
fun getDetails(id: String) {
Log.d(TAG, "Second function called")
db_company.child(id).addChildEventListener(datachildeventlistener)
}
private val datachildeventlistener = object : ChildEventListener {
override fun onCancelled(error: DatabaseError) {
}
override fun onChildMoved(snapshot: DataSnapshot, p1: String?) {
}
override fun onChildChanged(snapshot: DataSnapshot, p1: String?) {
Log.d(TAG, "onChildChanged")
val data = snapshot.getValue(User::class.java)
data?.id = snapshot.key
_userdetail.value = data
}
override fun onChildAdded(snapshot: DataSnapshot, p1: String?) {
val data = snapshot.getValue(User::class.java)
data?.id = snapshot.key
_userdetail.value = data
}
override fun onChildRemoved(snapshot: DataSnapshot) {
}
}
}
The Model Class is as follows
import com.google.firebase.database.Exclude
data class User(
#get:Exclude
var id: String? = null,
var isAdmin: Boolean? = true,
var name: String? = null,
var position: String? = null,
var contact: String? = null,
var comname: String? = null,
var address: String? = null,
var email: String? = null,
var website: String? = null
) {
constructor() : this("", true, "", "", "", "", "", "", "")
}
Firebase Realtime Database looks as follows
CHATREQ
8EFvXhAKTfWuIavGhXlz344bgMD2
c2HUyNV6sYQImIFqVNMfIaFDTKT2
id: "c2HUyNV6sYQImIFqVNMfIaFDTKT2"
request_type: "sent"
c2HUyNV6sYQImIFqVNMfIaFDTKT2
8EFvXhAKTfWuIavGhXlz344bgMD2
id: "8EFvXhAKTfWuIavGhXlz344bgMD2"
request_type: "received"
Company_Info
-M6Ez9RiFRpm8_cn35Pp
User_Info
8EFvXhAKTfWuIavGhXlz344bgMD2
admin: false
contact: "484615674"
name: "Chetan"
position: "c"
c2HUyNV6sYQImIFqVNMfIaFDTKT2
address: "add"
admin: true
comname: "Palekar"
contact: "549874561"
email: "add#gmail.com"
name: "Kp"
position: "adfa"
website: "www.add.com"
The stacktrace said that "cant convert object of string to the user Model class"
Hope Someone help me out with this .
Thank-You for your help.
Instead of using childEventListener, you need to use valueEventListener:
private val company_info = "User_Info"
private val db_company = FirebaseDatabase.getInstance().getReference(company_info)
private val reqEventlister = object : ValueEventListener {
override fun onCancelled(error: FirebaseError?) {
println(error!!.message)
}
override fun onDataChange(snapshot: DataSnapshot?) {
val getid = snapshot.getValue(Request::class.java)
val id = getid!!.id
val requesttype = getid.requesttype
Log.d(TAG, "Second function to be called")
Log.d(TAG, "$requesttype request type")
id?.let { getDetails(it) }
Log.d(TAG, "$id ID passed")
}
})
fun getRequest() {
Log.d(TAG, "getRequest method called 1st fun")
db_chat.child(userid!!).addValueEventListener(reqEventlister)
}
When using childEventListener, you are directly retrieving the children under the 8EFvXhAKTfWuIavGhXlz344bgMD2 thus retrieving values of type String. Instead you need to use ValueEventListener which will map your Request class to the data retrieved.

Categories

Resources