Edit variables and use another class (Kotlin) - android

Please help, the program not work.
I want to change the variables a and b and put them in the names
Thanks..............................................................................................
class Asd(){
lateinit var a: String
lateinit var b: String
var database = FirebaseDatabase.getInstance().getReference("RedCars")
.child("20-8-2020 18:0")
.addValueEventListener(object : ValueEventListener {
override fun onCancelled(p0: DatabaseError) {
}
override fun onDataChange(p0: DataSnapshot) {
var map = p0.value as Map<String, Any>
a = map["price"].toString()
b = map["pickup"].toString()
}
})
}
public class MyCustomAdapter(context: Context): BaseAdapter(){
private val mContext: Context
val d = Asd().a
val h = Asd().b
var names = arrayListOf<String>(
d, h
)
I try this:.............
public class MyCustomAdapter(context: Context): BaseAdapter(){
lateinit var a: String
lateinit var b: String
var database = FirebaseDatabase.getInstance().getReference("RedCars")
.child("20-8-2020 18:0")
.addValueEventListener(object : ValueEventListener {
override fun onCancelled(p0: DatabaseError) {
}
override fun onDataChange(p0: DataSnapshot) {
var map = p0.value as Map<String, Any>
a = map["price"].toString()
b = map["pickup"].toString()
}
})
private val mContext: Context
var names = arrayListOf<String>(
a, b
)
Logcat error:....................................................
2020-08-05 22:03:16.024 9227-9227/com.example.redcars E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.redcars, PID: 9227
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.redcars/com.example.redcars.MainActivity}: kotlin.UninitializedPropertyAccessException: lateinit property a has not been initialized
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3895)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:4074)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:91)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:149)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:103)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2473)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:219)
at android.app.ActivityThread.main(ActivityThread.java:8347)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1055)
Caused by: kotlin.UninitializedPropertyAccessException: lateinit property a has not been initialized
at com.example.redcars.MainActivity$MyCustomAdapter.<init>(MainActivity.kt:133)
at com.example.redcars.MainActivity.onCreate(MainActivity.kt:47)
at android.app.Activity.performCreate(Activity.java:8085)
at android.app.Activity.performCreate(Activity.java:8073)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1320)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3868)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:4074)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:91)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:149)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:103)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2473)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:219)
at android.app.ActivityThread.main(ActivityThread.java:8347)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1055)
And this have in MainActivity:
listView.adapter = MyCustomAdapter(this)

You should use lateinit properties only after they are initialized. So I suggest to move initialization of names array to ValueEventListener:
public class MyCustomAdapter(context: Context): BaseAdapter(){
lateinit var a: String
lateinit var b: String
lateinit var names: ArrayList<String>
// or you can use MutableList
// var namesMutable: MutableList<String> = mutableListOf()
var database = FirebaseDatabase.getInstance().getReference("RedCars")
.child("20-8-2020 18:0")
.addValueEventListener(object : ValueEventListener {
override fun onCancelled(p0: DatabaseError) {
}
override fun onDataChange(p0: DataSnapshot) {
var map = p0.value as Map<String, Any>
a = map["price"].toString()
b = map["pickup"].toString()
// INITIALIZE THE ARRAY HERE
names = arrayListOf<String>(a, b)
// namesMutable.add(a)
// namesMutable.add(b)
// notifyDatasetChanged()
}
})
// ...
}

Related

Whenever I click an activity ,app is get crushed or sent back user to previous activity.What is The solution of this?

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.

Why is my firebase database not able to convert object of type java.util.ArrayList to type

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

Why variable is not initialized even if it was created?

I don't really understand why logFile(and loggingProcess) are not initialized. The logcat shows that the file exists and createLogFile() method had been called when Activity was created, but when I'm trying to uploadLogs() from the Activity(using SandboxApp().uploadLogs()) it throws an exception
class SandboxApp: Application(), MyCallbacks {
companion object {
#JvmField
val TAG = SandboxApp::class.java.simpleName
}
private lateinit var loggingProcess: Process
private lateinit var logFile: File
private lateinit var fileDirectory: File
private var isLogging = false
private val formatter = SimpleDateFormat("dd-MM-yyyy_HH-mm", Locale.getDefault())
private lateinit var workManager: WorkManager
override fun onCreate() {
super.onCreate()
workManager = WorkManager.getInstance(this)
registerActivityLifecycleCallbacks(this)
}
fun createLogFile() {
val currentTime = formatter.format(Calendar.getInstance().time)
val fileName = "logs-$currentTime.log"
fileDirectory = File(filesDir.absolutePath + File.separator + "sandboxLog")
fileDirectory.mkdirs()
Log.d(TAG, "FileDir exists? $fileDirectory, ${fileDirectory.exists()}")
logFile = File(fileDirectory, fileName)
logFile.createNewFile()
Log.d(TAG, "File exists? $logFile, ${logFile.exists()}")
}
fun startLogging() {
isLogging = true
loggingProcess = Runtime.getRuntime().exec("logcat -f $logFile")
}
private fun stopLogging() {
isLogging = false
loggingProcess.destroy()
}
fun uploadLogs() {
stopLogging()
val data = Data.Builder()
.putString("file path", logFile.absolutePath)
.build()
val request = OneTimeWorkRequest.Builder(LogsWorker::class.java)
.setInputData(data)
.build()
workManager.enqueue(request)
createLogFile()
startLogging()
}
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
super.onActivityCreated(activity, savedInstanceState)
Log.d(TAG, "onActivityCreated method")
createLogFile()
startLogging()
}
}
This is the exception, tha same is for the loggingProcess variable
2020-08-04 15:55:51.338 8741-8741/com.example.sandboxlog E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.sandboxlog, PID: 8741
kotlin.UninitializedPropertyAccessException: lateinit property logFile has not been initialized
at com.example.sandboxlog.SandboxApp.uploadLogs(SandboxApp.kt:66)
at com.example.sandboxlog.MainActivity$onCreate$2.onClick(MainActivity.kt:33)
at android.view.View.performClick(View.java:7125)
at android.view.View.performClickInternal(View.java:7102)
at android.view.View.access$3500(View.java:801)
at android.view.View$PerformClick.run(View.java:27336)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
upd: onCreate method of MainActivity, where uploadLogs is being called
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Log.d(TAG, "MainActivity created")
Thread.setDefaultUncaughtExceptionHandler(CrashHandler())
button.setOnClickListener {
// creating an exception
RequestBody.create(MultipartBody.FORM, exceptionFile!!)
}
buttonSend.setOnClickListener {
SandboxApp().uploadLogs()
}
buttonSecondActivity.setOnClickListener {
Log.d(TAG, "Starting second activity")
val intent = Intent(this, SecondActivity::class.java)
startActivity(intent)
}
}
You shouldn't create an instance of your app class SandboxApp by yourself, it is done by the system. To have access to the instance of SandboxApp you can use ctx.applicationContext property:
val app = context.applicationContext as SandboxApp
app.uploadLogs()
So in the OnClickListener it will look like the following:
buttonSend.setOnClickListener {
val app = applicationContext as SandboxApp
app.uploadLogs()
}

Error adding to mutable list (NPE) Kotlin Android

---Data Class---
trying to add object to meals MutableList-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
data class YelpRestaurant(
val name: String,
val rating: Double,
val price: String,
#SerializedName("review_count") val numReviews: Int,
#SerializedName("image_url") val imageUrl: String,
val categories: List<YelpCategory>,
val location: YelpLocation,
val meals: MutableList<UserMeals>
)
----EDITED ACTIVITY----
class ThoughtsActivity : AppCompatActivity() {
lateinit var mealName: String
lateinit var mealPrice: String
lateinit var mealThought: String
lateinit var selected_Restaurant : YelpRestaurant
val meals = mutableListOf<UserMeals>()
#Subscribe(sticky = true)
fun getRest(selectedRestaurant : YelpRestaurant) {
selected_Restaurant = selectedRestaurant
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_thoughts)
thoughtBtn.setOnClickListener() {
mealName = m_name.text.toString()
mealPrice = m_price.text.toString()
mealThought = m_thought.text.toString()
var addedMeal = UserMeals(mealName, mealPrice.toDouble(), mealThought)
if (mealName.isNotEmpty()) {
selected_Restaurant.meals.add(addedMeal)
}
}
}
override fun onStart() {
super.onStart()
EventBus.getDefault().register(this)
}
override fun onStop() {
super.onStop()
EventBus.getDefault().unregister(this)
}
}
You have null pointer exception when accessing selected_Restaurant.meals to prevent NPE change meals to val and instantiate it when you declare it like this in selected_Restaurant:
val meals = mutableListOf<UserMeals>()

Database exception while displaying Chatlist in Android Kotlin Chat app

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 {}

Categories

Resources