retriving data from firebase - android

i have data where there is image post and description
when i retrieve the data it shows error toast,
can't find whats wrong here is my code
class MainActivity : AppCompatActivity() {
val ref = FirebaseDatabase.getInstance().getReference("post")
var storageRef = FirebaseStorage.getInstance().reference
private val TAG = ""
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val recyclerView = findViewById<RecyclerView>(R.id.DrawerId)
recyclerView.layoutManager = LinearLayoutManager(this, LinearLayout.VERTICAL,false)
val users = ArrayList<RecyClass>()
val userlist = ArrayList<RecyClass>()
ref.addChildEventListener(object :ChildEventListener{
override fun onCancelled(p0: DatabaseError?) {
Log.e(TAG ,"Error is here")
}
override fun onChildMoved(p0: DataSnapshot?, p1: String?) {}
override fun onChildChanged(p0: DataSnapshot?, p1: String?) {}
override fun onChildAdded(p0: DataSnapshot?, p1: String?) {
if(p0!!.exists()){
for (h in p0.children) {
getpost(h.key)
}
}
}
override fun onChildRemoved(p0: DataSnapshot?) {}
})
}
private fun getpost(key: String?) {
val postdata = FirebaseDatabase.getInstance().getReference("post").child(key)
postdata.addListenerForSingleValueEvent(object:ValueEventListener{
override fun onCancelled(p0: DatabaseError?) {
}
override fun onDataChange(p0: DataSnapshot?) {
if(p0!!.exists()){
val userlist = ArrayList<RecyClass>()
var descText = ""
var Image = ""
if (p0.child("desc").getValue()!=null){
descText = p0.child(key).child("desc").getValue().toString()
}
if (p0.child("Image").getValue()!=null){
Image = p0.child(key).child("Image").getValue().toString()
}
val kkk = RecyClass(descText,Image)
val adptr =RecyclerAdapter(userlist,applicationContext )
userlist.add(kkk)
adptr.notifyDataSetChanged()
}else{
Toast.makeText(this#MainActivity,"error",Toast.LENGTH_LONG).show()
}
}
}
})
}
i already have multiple data inside firebase node
when i put toast inside if(p0!!.exists()) it shows but when toast is moved inside if (p0.child("desc").getValue()!=null) it dhoesnt work..
i am getting blank page in recycler view

Related

Recyclerview separates the data values,stores in one variable, and display values separately

EDIT
i changed my code and got a result but it breaks the data into separate values. it reads all the data from the database for each child. i have 2 childs but it only retrieves the last childs data and display its values separately. it stores its value from the variable eta_text
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
clear_all = view.findViewById(R.id.clear_all)
notificationView = view.findViewById(R.id.notificationList)
notificationArray = arrayListOf()
getNotifData()
var linearLayoutManager = LinearLayoutManager(context)
notificationView.layoutManager = linearLayoutManager
notificationView.setHasFixedSize(true)
}
private fun getNotifData() {
val user = FirebaseAuth.getInstance().currentUser
val useremail = user!!.email
dbref = FirebaseDatabase.getInstance().reference
dbref.child("Students").orderByChild("email").equalTo(useremail.toString()).addValueEventListener(object : ValueEventListener{
override fun onDataChange(snapshot: DataSnapshot) {
for (ds in snapshot.children) {
val idNumber: String? = ds.key
dbref.child("Notification").child(idNumber.toString()).addValueEventListener(object : ValueEventListener{
override fun onDataChange(dsnapshot: DataSnapshot) {
for (dsd in dsnapshot.children) {
val key: String? = dsd.key
dbref.child("Notification").child(idNumber.toString()).child(key.toString()).addValueEventListener(object : ValueEventListener{
override fun onDataChange(dsnap: DataSnapshot) {
notificationArray.clear()
if (dsnap.exists()){
for (queueSnapshot in dsnap.children){
notificationArray.add(Notification(queueSnapshot.value.toString()))
}
notifadapter = MyAdapter_Notification(notificationArray)
notificationView.adapter = notifadapter
}
}
override fun onCancelled(error: DatabaseError) {
TODO("Not yet implemented")
}
})
}
}
override fun onCancelled(error: DatabaseError) {
TODO("Not yet implemented")
}
})
}
}
override fun onCancelled(error: DatabaseError) {
TODO("Not yet implemented")
}
})
}
My data class
package com.example.sqms
data class Notification(var eta_text : String ?= null,
var office_name : String ?= null,
var time_text : String ?= null)
My Adapter
class MyAdapter_Notification (private val notificationList : ArrayList<Notification>)
: RecyclerView.Adapter<MyAdapter_Notification.MyViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val notificationView = LayoutInflater.from(parent.context).inflate(R.layout.notification_view,parent,false)
return MyViewHolder(notificationView)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val currentItem = notificationList[position]
holder.eta_text.text = currentItem.eta_text
holder.office_name.text = currentItem.office_name
holder.time_text.text = currentItem.time_text
}
override fun getItemCount(): Int {
return notificationList.size
}
inner class MyViewHolder(notificationView : View) : RecyclerView.ViewHolder(notificationView){
val eta_text : TextView = itemView.findViewById(R.id.eta_text)
val office_name : TextView = itemView.findViewById(R.id.office_name)
val time_text : TextView = itemView.findViewById(R.id.time_text)
}
}
picture below is the values from database
database
picture below is the data that is displayed separately
notification recycler view
i just solved it. i just removed the 3rd nested databasereference and changed the data writing
private fun getNotifData() {
val user = FirebaseAuth.getInstance().currentUser
val useremail = user!!.email
dbref = FirebaseDatabase.getInstance().reference
dbref.child("Students").orderByChild("email").equalTo(useremail.toString()).addValueEventListener(object : ValueEventListener{
override fun onDataChange(snapshot: DataSnapshot) {
for (ds in snapshot.children) {
val idNumber: String? = ds.key
dbref.child("Notification").child(idNumber.toString()).addValueEventListener(object : ValueEventListener{
override fun onDataChange(dsnapshot: DataSnapshot) {
notificationArray.clear()
if (dsnapshot.exists()){
for (queueSnapshot in dsnapshot.children){
val notif = queueSnapshot.getValue(Notification::class.java)
if (notif != null) {
notificationArray.add(notif)
}
}
notifadapter = MyAdapter_Notification(notificationArray)
notificationView.adapter = notifadapter
}
if (notifadapter.itemCount==0) {
notificationView.visibility = View.GONE;
new_notif.visibility = View.VISIBLE;
}
else {
notificationView.visibility = View.VISIBLE;
new_notif.visibility = View.GONE;
}
}
override fun onCancelled(error: DatabaseError) {
TODO("Not yet implemented")
}
})
}
}
override fun onCancelled(error: DatabaseError) {
TODO("Not yet implemented")
}
})
}

RecyclerView is looping the same data retrieved from firebase

I tried to add a new data to firebase and then show it in a recyclerview, but after i add the data the recyclerview just loop the whole data until the data is done uploading thus creating a view like this :
the looped recyclerview
As you can see in the picture that in that link, i tried to add "food 6" data but as the result for the adding process the recyclerview keep updating the items inside it until the adding process complete
Here is my adapter code
class FoodAdapter (private var dataList : ArrayList<Food>): RecyclerView.Adapter<FoodAdapter.MyViewholder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewholder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.food_recyclerview,parent,false)
return MyViewholder(itemView)
}
override fun onBindViewHolder(holder: MyViewholder, position: Int) {
val currentItem = dataList[position]
Log.w("adapater",currentItem.image_pic.toString())
Picasso.get().load(currentItem.image_pic).into(holder.foodPic)
holder.food_name.text = currentItem.name
holder.food_price.text = currentItem.price.toString()
if (currentItem.avail == true){
holder.food_avail.text = "Tersedia"
holder.food_avail.setTextColor(Color.GREEN)
} else {
if (currentItem.avail == false){
holder.food_avail.text = "Habis"
holder.food_avail.setTextColor(Color.RED)
} else {
holder.food_avail.text = "Error"
}
}
}
override fun getItemCount(): Int {
return dataList.size
}
inner class MyViewholder (itemView : View): RecyclerView.ViewHolder(itemView){
val foodPic : ImageView = itemView.findViewById(R.id.iv_gambar_makanan)
val food_name : TextView = itemView.findViewById(R.id.tv_nama_makanan)
val food_avail : TextView = itemView.findViewById(R.id.tv_status_makanan)
val food_price : TextView = itemView.findViewById(R.id.tv_harga_makanan)
}
}
here is my update data to firebase code
private fun addDatatoFirebase() {
val dataRef = ref.child(preferences.getValue("username").toString()).child("FoodList/"+ UUID.randomUUID().toString())
var PicUrl = ""
val addImage = StorageRef.child(preferences.getValue("username").toString())
.child("food_pics/" + UUID.randomUUID())
Log.i("Cycle", "Add Image to Firebase")
addImage.putFile(FilePath).addOnSuccessListener {
addImage.downloadUrl.addOnSuccessListener {
PicUrl = it.toString()
dataRef.child("image_pic").setValue(PicUrl)
}
}
Log.i("URL",addImage.toString())
dataRef.addValueEventListener(object : ValueEventListener{
override fun onDataChange(snapshot: DataSnapshot) {
id = snapshot.ref
Log.w("PicUrl data",PicUrl)
dataRef.child("name").setValue(food_name)
dataRef.child("avail").setValue(availability)
dataRef.child("price").setValue(food_price.toInt())
}
override fun onCancelled(error: DatabaseError) {
Toast.makeText(applicationContext,"Error",Toast.LENGTH_SHORT)
}
})
}
and here is the code to get the data
private fun getFoodData() {
val foodData = ref.child(preferences.getValue("username").toString()).child("FoodList")
foodData.addValueEventListener(object : ValueEventListener{
override fun onDataChange(snapshot: DataSnapshot) {
if (snapshot != null) {
for (userSnapshot in snapshot.children) {
var data = userSnapshot.getValue(Food::class.java)
foodDataArrayList.add(data!!)
}
}
foodList.adapter = FoodAdapter(foodDataArrayList)
}
override fun onCancelled(error: DatabaseError) {
Toast.makeText(applicationContext,"Error",Toast.LENGTH_SHORT)
}
})
foodList.adapter = FoodAdapter(foodDataArrayList)
}
Can anyone show me how to fix this issue?
You missed out on one thing. Whenever data gets changed, you get all the entries again and again without removing the previous un-updated data. So, the simple solution would be to clear the list before getting the data. Try this code:
private fun getFoodData() {
val foodData = ref.child(preferences.getValue("username").toString()).child("FoodList")
foodData.addValueEventListener(object : ValueEventListener{
override fun onDataChange(snapshot: DataSnapshot) {
if (snapshot != null) {
foodDataArrayList.clear() // added this line
for (userSnapshot in snapshot.children) {
var data = userSnapshot.getValue(Food::class.java)
foodDataArrayList.add(data!!)
}
}
foodList.adapter = FoodAdapter(foodDataArrayList)
}
override fun onCancelled(error: DatabaseError) {
Toast.makeText(applicationContext,"Error",Toast.LENGTH_SHORT)
}
})
}

RecyclerView doesn't appear in a Fragment

Why doesn't RecyclerView appear in my fragment? I've added recyclerview adapter in the fragment, but it still didn't appear. Here are the codes:
FollowersFragment.kt
class FollowersFragment : Fragment() {
private lateinit var binding: FragmentFollowersBinding
companion object {
private const val TAG = "FollowersFragment"
const val ARG_NAME = "userName"
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_followers, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding = FragmentFollowersBinding.inflate(layoutInflater)
val username = arguments?.getString(ARG_NAME)
val layoutManager = LinearLayoutManager(requireActivity())
binding.rvFollowers.layoutManager = layoutManager
val itemDecoration = DividerItemDecoration(requireActivity(), layoutManager.orientation)
binding.rvFollowers.addItemDecoration(itemDecoration)
val client = ApiConfig.getApiService().getFollowers(username.toString(),"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")
client.enqueue(object : Callback<List<FollowsResponseItem>> {
override fun onResponse(
call: Call<List<FollowsResponseItem>>,
response: Response<List<FollowsResponseItem>>
) {
if(response.isSuccessful){
val responseBody = response.body()
if(responseBody!=null){
Log.d(TAG,responseBody.toString())
setUserData(responseBody)
}else{
Log.e(TAG,"onFailure: ${response.message()}")
}
}
}
override fun onFailure(call: Call<List<FollowsResponseItem>>, t: Throwable) {
Log.e(TAG, "onFailure: ${t.message}")
}
})
}
fun setUserData(item: List<FollowsResponseItem>){
val listUser = ArrayList<UserResponse>()
val executor = Executors.newSingleThreadExecutor()
executor.execute {
try {
for (i in 0..item.size-1) {
if(item.size>5 && i>5){
break
}
val client = ApiConfig.getApiService()
.getUser(item.get(i).login, "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")
client.enqueue(object : Callback<UserResponse> {
override fun onResponse(
call: Call<UserResponse>,
response: Response<UserResponse>
) {
if (response.isSuccessful) {
val responseBody = response.body()
if (responseBody != null) {
listUser.add(responseBody)
if(i==4 || item.get(i).login.equals(item.get(item.size-1).login)){
Log.d(TAG,"user : $listUser")
val adapter = ListUserAdapter(listUser)
binding.rvFollowers.adapter = adapter
Log.d(TAG,adapter.toString())
adapter.setOnItemClickCallback(object: ListUserAdapter.OnItemClickCallback{
override fun onItemClicked(data: UserParcelable) {
showSelectedUser(data)
}
})
}
} else {
Log.e(TAG, "onFailure: ${response.message()}")
}
}
}
override fun onFailure(call: Call<UserResponse>, t: Throwable) {
Log.e(TAG, "onFailure: ${t.message}")
}
})
}
} catch(e: InterruptedException) {
e.printStackTrace()
}
}
}
private fun showSelectedUser(data: UserParcelable) {
}
}
DetailActivity.kt
class DetailActivity : AppCompatActivity() {
private lateinit var binding: ActivityDetailBinding
private var getUserName: String ="sidiqpermana"
companion object{
const val EXTRA_DATA = "extra_data"
#StringRes
private val TAB_TITLES = intArrayOf(
R.string.tab_text_1,
R.string.tab_text_2
)
}
#SuppressLint("SetTextI18n")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
supportActionBar?.hide()
binding = ActivityDetailBinding.inflate(layoutInflater)
setContentView(binding.root)
val data = intent.getParcelableExtra<UserParcelable>(EXTRA_DATA) as UserParcelable
val sectionsPagerAdapter = SectionsPagerAdapter(this)
val viewPager: ViewPager2 = binding.viewPager
viewPager.adapter = sectionsPagerAdapter
val tabs: TabLayout = binding.tabs
sectionsPagerAdapter.userName = data.login
TabLayoutMediator(tabs,viewPager){ tab, position ->
tab.text = resources.getString(TAB_TITLES[position])
}.attach()
getUserName = data.login
showInfo(data)
}
fun getUserName() : String{
return getUserName
}
#SuppressLint("SetTextI18n")
private fun showInfo(data: UserParcelable){
Glide.with(this#DetailActivity)
.load(data.avatar_url)
.into(binding.detailPp)
if(data.name.equals("null")) binding.detailName.setText("No Name") else binding.detailName.setText(data.name)
binding.detailUsername.setText(data.login)
if(data.bio.equals("null")) binding.detailBio.setText("No Name") else binding.detailBio.setText(data.bio)
binding.detailFollowers.setText("${data.followers} Followers")
binding.detailFollowings.setText("${data.following} Following")
if(data.location.equals("null")) binding.detailLocation.setText("No Location") else binding.detailLocation.setText(data.location)
}
}
ListUserAdapter.kt (RecyclerView Adapter)
class ListUserAdapter (private val listUser: ArrayList<UserResponse>) : RecyclerView.Adapter<ListUserAdapter.ListViewHolder>() {
private lateinit var onItemClickCallback: OnItemClickCallback
fun setOnItemClickCallback(onItemClickCallback: OnItemClickCallback){
this.onItemClickCallback = onItemClickCallback
}
class ListViewHolder(var binding: ItemUsersRowBinding) : RecyclerView.ViewHolder(binding.root) {
}
override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): ListViewHolder {
val binding = ItemUsersRowBinding.inflate(LayoutInflater.from(viewGroup.context),viewGroup,false)
return ListViewHolder(binding)
}
#SuppressLint("SetTextI18n")
override fun onBindViewHolder(holder: ListViewHolder, position: Int) {
var (followers,avatar_url,following, name,bio, location, login) = listUser[position]
name = name ?: "No Name"
bio = bio ?: "No Bio"
location = location?: "No Location"
holder.apply {
Glide.with(itemView.getContext())
.load(avatar_url)
.into(binding.photoProfile)
binding.profileName.setText(name.toString())
binding.username.setText(login)
binding.followers.setText("$following Followers")
binding.followings.setText("$following Followings")
binding.location.setText(location.toString())
val detailUser = UserParcelable(followers,avatar_url,following,
name.toString(), bio.toString(), location.toString(), login)
itemView.setOnClickListener{ onItemClickCallback.onItemClicked(detailUser)}
}
}
override fun getItemCount(): Int {
return listUser.size
}
interface OnItemClickCallback {
fun onItemClicked(data: UserParcelable)
}
}
Help me solve this problem please.
There is no need to initialize adapter every time you want to update the list. Either make your ListUserAdapter extend ListAdapter and than use adapter.submitList(listUser) or if you want to extend RecyclerView.Adapter as you do, you can do the following :
class ListUserAdapter () : RecyclerView.Adapter<ListUserAdapter.ListViewHolder>() {
private val listUser: List<UserResponse>
fun submitList(newList: List<UserResponse>) {
listUser = newList
notifyDataSetChanged()
}
override fun onBindViewHolder(holder: ListViewHolder, position: Int) {
val listItem = listUser[position]
...
}
override fun getItemCount(): Int {
return listUser.size
}
}
I suggest you go with ListAdapter. Check if Log.d(TAG,"user : $listUser") is printed, if it is and listUser is not empty than call adapter.submitList(listUser) and RV should be populated.
You have missed to notify adapter about the changes, So after
binding.rvFollowers.adapter = adapter call adapter.notifyDataSetChanged()

Key expected String[] but value was a java.lang.String

I am getting issues of getting my USER KEY and it returned as null even if there's a username.
Thing is I am just trying to get my username.
I am currently using firebase database
class NewMessageActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_new_message)
supportActionBar?.title="Select User"
/*
val adapter = GroupAdapter<ViewHolder>()
adapter.add(UserItem())
adapter.add(UserItem())
adapter.add(UserItem())
new_message_list.adapter = adapter
*/
fetchusers()
}
companion object {
val USER_KEY = "USER_KEY"
}
private fun fetchusers(){
val ref = FirebaseDatabase.getInstance().getReference("/users")
ref.addListenerForSingleValueEvent(object: ValueEventListener {
override fun onDataChange(p0: DataSnapshot) {
val adapter = GroupAdapter<ViewHolder>()
p0.children.forEach {
Log.d("NewMessage", it.toString())
val user = it.getValue(User::class.java)
if (user != null){
adapter.add(UserItem(user))
}
}
adapter.setOnItemClickListener { item, view ->
val userItem = item as UserItem
val intent = Intent(view.context, ChatLogActivity::class.java)
intent.putExtra(USER_KEY, userItem.user.username)
startActivity(intent)
finish()
}
new_message_list.adapter = adapter
}
override fun onCancelled(p0: DatabaseError) {
}
})
}
}
class UserItem(val user: User): Item<ViewHolder>() {
override fun bind(viewHolder: ViewHolder, position: Int){
//list stuff
viewHolder.itemView.username_textview_new.text = user.username
Picasso.get().load(user.profileImageUrl).into(viewHolder.itemView.imageview_new_msg)
}
override fun getLayout(): Int {
return R.layout.user_row_new_message
}
}
This one really frustrated me for hours. I needed this for my chat log title for each person
Maybe I should skip this?
I am just new to android development
Can anyone help?
error in debug

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