i m working over application connected with fire base here which retrieves data from db 'm getting error unresolved reference dataSnapshot in Homefrag.kt file and to be very precise in
//load posts from firebase
fun LoadPostFromFireBase(){...}
clean project=>rebuild=>invalidate cache
fun LoadPostFromFireBase(){
myRef.child("posts")
.addValueEventListener(object : ValueEventListener {
override fun onDataChange(p0: DataSnapshot ) {
try {
listOfPost.clear()
listOfPost.add(Post("0","him","url"," ","add","addPost"))
var td= dataSnapshot!!.value as HashMap<String,Any>
for(key in td.keys){
var post= td[key] as HashMap<String,Any>
listOfPost.add(Post(key,
post["postText"] as String,
post["postImageURL"] as String
,post["postDate"] as String
,post["personName"] as String
,post["personID"] as String))
}
adapter!!.notifyDataSetChanged()
}catch (ex:Exception){}
}
override fun onCancelled(p0: DatabaseError) {
}
})
}
getting unresolved dataSnapshot!
You're looking for something that does not exist. Look at what the function onDataChange is giving you through its parameters.
I don't know Kotlin, but I'm pretty sure looking at your syntax that you're receiving "p0" inside the onDataChange, but you're looking for the object dataSnapshot.
You can fix it by replacing
var td= dataSnapshot!!.value as HashMap<String,Any>
with
var td= p0!!.value as HashMap<String,Any>
Related
I'm new to Android & I don't know how to get all the firebase snapshot data at once inside the UID in the single data class.
val usersPrivateRef = Constants.FIREBASE_RESIDENT_PRIVATE
usersPrivateRef?.child("Fs0qczU3GsfJuGDGAeEN7bIgfjD3")
?.addListenerForSingleValueEvent(object : ValueEventListener{
override fun onDataChange(snapshot: DataSnapshot) {
if (snapshot.exists()) {
println(snapshot)
} else {
showLongToast("Snapshot not exists")
}
}
override fun onCancelled(error: DatabaseError) {}
})
To get a value from the DataSnapshot you can use its child() and getValue calls. For example, to print Krishna's email, you'd do:
println(snapshot.child("personalDetails/email").getValue(String::class.java)
I have found a solution for my above question
With the help of Gson library & also I have created the Kotlin data classes same as my snapshot data.
private var residentDATA : ArrayList<MineUserInfo> = ArrayList<MineUserInfo>()
var gson = Gson()
val json = Gson().toJson(snapshot.value)
var data = gson?.fromJson(json, MineUserInfo::class.java)
residentDATA.add(data)
I'm trying to retrieve submittedRequests from database .
userRef.addValueEventListener(object : ValueEventListener {
override fun onCancelled(p0: DatabaseError) {
}
override fun onDataChange(snapshot: DataSnapshot) {
if(snapshot!!.exists()){
val children=snapshot!!.children
for(item in children) {
val retrieveUser= item.getValue(User::class.java) //it crashes here
if (retrieveUser != null) {
userData.add(retrieveUser)
}
}
}
}
})
User Class
class User(val userId:String="", val name:String="", val surname:String="", val profileImageUrl: String="",val submittedRequests:String="", val pickedUpRequests:String="")
Error Message is :
com.google.firebase.database.DatabaseException: Failed to convert value of type java.util.HashMap to String
How can I retrieve submittedRequests from database properly?
You're declared submittedRequests:String="" in your User class. Looking at your JSON the submittedRequests is not a simple string, but rather a nested object, or a map.
This should work better
submittedRequests:Map<String, Any>=hashMapOf<String, Any>()
Can someone help me fix it?
Following code works without any error, however, it does not retrieve data from Firebase and show in the TextView.
private fun viewData() {
val postReference = FirebaseDatabase.getInstance().getReference("dataID")
val dbView= findViewById<TextView>(R.id.txtFdbData)
val postListener = object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
val post = dataSnapshot.getValue(Post::class.java)
dbView.text=post?.postName
}
override fun onCancelled(databaseError: DatabaseError) {
}
}
postReference.addValueEventListener(postListener)
Toast.makeText(this,"Retrieved",Toast.LENGTH_LONG).show()
}
Above code is called when I tap the button 'btnView'
viewButton = findViewById(R.id.btnView)
viewButton.setOnClickListener {
viewData()
}
When I hit the button it shows the toast message 'Retrieved' and the default value given in the TextView (txtFdbData) is deleted (or may be replaced with an empty string?, I do not know).
Following is the post Class
data class Post (
val postName: String="",
val postDescription:String="")
I am working on Android Studio, using Kotlin and Firebase Realtime Database.
You query to database return list of items. So loop through it and try to get Post. Check below:
override fun onDataChange(dataSnapshot: DataSnapshot) {
dataSnapshot.children.forEach {childSnapshot ->
val post = childSnapshot.getValue(Post::class.java)
dbView.text=post?.postName
}
}
getReference("dataID") is not your data node it is your parent node.
Then you have to access their children using getChildren() method.
Change you on data change method with this.
override fun onDataChange(dataSnapshot: DataSnapshot) {
for (postSnapshot : dataSnapshot.getChildren()) {
val post = postSnapshot .getValue(Post::class.java)
dbView.text=post?.postName
}
}
I try to retrive data from firebase database
but i have null pointer exeption
here is my model code
class Request {
var Name: String? = null
var Phone: String? = null
var Street: String? = null
var Home:String?= null
var Flat:String?=null
var Status: String?=null
}
Here is how i retrieve data
var mDatabase=FirebaseDatabase.getInstance().reference
mDatabase.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(p0: DataSnapshot) {
for (d in p0.children) {
var modelRequest: Request? = d.child("Requests").child(user.toString()).getValue(Request::class.java)
var ord: Order? =d.child("Orders").getValue(Order::class.java)
Log.d("loadedList", "ok")
requestList.add(modelRequest!!)
}
}
})
Here is my data structure
You're looking over the top-level nodes in your database (Food, Requests, etc) and then getting the Requests child node of each. Since there is no /Requests/Requests that will always be null.
This should be closer:
override fun onDataChange(snapshot: DataSnapshot) {
var modelRequest: Request? = snapshot.child("Requests").child(user.toString()).getValue(Request::class.java)
var ord: Order? =snapshot.child("Orders").getValue(Order::class.java)
Log.d("loadedList", "ok")
requestList.add(modelRequest!!)
}
Note that you're now loading all the data from your database, to then only use the Requests and Orders nodes. This is a waste of bandwidth, so you really should only request the data you need. You could do this by attaching two listeners and waiting for the result of both.
I'm building an activity in an app where users can upload a post, and other users in the app can view the post.
I built a function called loadPost()
This function will take what's there in the database and load it in my View.
Unfortunately, I'm facing an error with the
.addValueEventListener(ValueEventListener{
It's telling me that the interface needs a constructor.
here's the function:
//*******************************************************
//Load posts to the screen from the database
//****************************************************
fun loadPost(){
myRef.child("posts")
.addValueEventListener(ValueEventListener{
override fun onDataChange(#NonNull dataSnapshot: DataSnapshot?) {
try {
postElements.clear()
postElements.add(Post("0","him","url","add"))
postElements.add(Post("0","him","url","ads"))
//Hashmap : Key and value (represents the post and node)
var td= dataSnapshot!!.value as HashMap<String,Any>
for(key in td.keys){
var post= td[key] as HashMap<String,Any>
postElements.add(Post(key,
post["text"] as String,
post["postImage"] as String
,post["userUID"] as String))
}
adpater!!.notifyDataSetChanged() //notify when there's an update in the adapter
}catch (ex:Exception){}
}
override fun onCancelled(p0: DatabaseError?) {
}
})
}
this is how the constructor of a ValueEventListener should look alike:
object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
}
}
which means, that you have to replace this one line
.addValueEventListener(ValueEventListener {
with:
.addValueEventListener(object : ValueEventListener {
see https://youtrack.jetbrains.com/issue/KT-7770 (concerning the code-converter)