Is there any way to retrieved selected data in Firebase to a fragment in Kotlin? Not all data only selected row.
I'm new to Kotlin. Please help me.
firstly user login to the system. for this I checked the user name from Firebase. it works properly. But after that, I want to retrieve data of that username into a fragment. In one activity I add five fragments. I need to load all data of that user into one Fragment.
for example in this abi is a username and I need to load all data of only that username into one fragment.
Firebase data
Inside of abi
here's what I added.
val rootRef = FirebaseDatabase.getInstance().reference
val userRef = rootRef.child("User").child(sessionId)
val valueEventListener = object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
val name = dataSnapshot.child("fullName").getValue(String::class.java)
val age = dataSnapshot.child("age").getValue(String::class.java)
val phone = dataSnapshot.child("phoneNo").getValue(String::class.java)
val bank = dataSnapshot.child("bankAccNo").getValue(String::class.java)
val password = dataSnapshot.child("passwordRegister").getValue(String::class.java)
nameText.setText(name)
ageText.setText(age)
phoneText.setText(phone)
bankText.setText(bank)
passwordText.setText(password)
}
override fun onCancelled(error: DatabaseError) {
Log.d("TAG", error.getMessage())
}
}
userRef.addListenerForSingleValueEvent(valueEventListener)
To get the data from the Firebase Realtime Database that corresponds only to the abi user, please use the following lines of code:
val rootRef = FirebaseDatabase.getInstance().reference
val userRef = rootRef.child("User").child("abi")
val valueEventListener = object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
val name = dataSnapshot.child("fullName").getValue(String::class.java)
Log.d("TAG", name)
}
override fun onCancelled(databaseError: error) {
Log.d("TAG", error.getMessage()) //Don't ignore potential errors!
}
}
userRef.addListenerForSingleValueEvent(valueEventListener)
In the same way, you can also get the values of the other fields. The result in the logcat will be:
Abilashini
Related
I am trying to get data from my firebase realtime database.
In my database there is a table whose name is "groups" and it has 3 values "datetime", "title", "username".
I want to get title value and add my list.
Normally in static version, I have a list which includes GroupModelRetrieve types and lists the titles in listview
Now I cant see the titles in listview It is empty
I am new in mobile programming. So, I appreaciate that if you help me.
Here is my code
val list: ArrayList<GroupModelRetrieve> = arrayListOf()
database = FirebaseDatabase.getInstance()
databaseReference = database?.getReference("groups")!!.child("title")
val postListener = object : ValueEventListener{
override fun onCancelled(error: DatabaseError) {
Toast.makeText(requireContext(), "Fail to get data.", Toast.LENGTH_SHORT).show();
}
override fun onDataChange(snapshot: DataSnapshot) {
val data = snapshot.getValue()
val item = GroupModelRetrieve(data.toString())
list.add(item)
}
}
databaseReference!!.addValueEventListener(postListener)
val adapter = GroupsAdapter(requireActivity(), list)
v.findViewById<ListView>(R.id.list_view_groups).adapter = adapter
Also I am adding my model
public class GroupModelRetrieve(Title: String) {
val title:String
init {
title = Title
}
}
If you want, I can add more codes. Thanks for your help.
You need to notify the list with the new changes, as by default Firebase works asynchronously to the main thread, so setting the adapter to the list will get called before any Firebase response.
val adapter = GroupsAdapter(requireActivity(), list)
val listView = v.findViewById<ListView>(R.id.list_view_groups) // << Set listView in a variable
listView.adapter = adapter
val list: ArrayList<GroupModelRetrieve> = arrayListOf()
database = FirebaseDatabase.getInstance()
databaseReference = database?.getReference("groups")!!.child("title")
val postListener = object : ValueEventListener{
override fun onCancelled(error: DatabaseError) {
Toast.makeText(requireContext(), "Fail to get data.", Toast.LENGTH_SHORT).show();
}
override fun onDataChange(snapshot: DataSnapshot) {
val data = snapshot.getValue()
val item = GroupModelRetrieve(data.toString())
list.add(item)
adapter.notifyDataSetChanged() // <<<<<<< Here is the change
}
}
databaseReference!!.addValueEventListener(postListener)
Also I suggest using addListenerForSingleValueEvent() instead of addValueEventListener() in case you need the list only once without the need to real-time updates
I am using firebase database and I had stored the user information in the database ( realtime ) and I want to get the information into my user profile UI in my app
Now when I use snapshot, I don't know how to get the information of it
Any help please?
val userId = authRef.currentUser?.uid
val currentUser = dataRef.getReference("/Users/$userId")
currentUser.addValueEventListener(object : ValueEventListener{
override fun onCancelled(p0: DatabaseError) {
}
override fun onDataChange(p0: DataSnapshot) {
// I need to get data from here ( userDisplayName , userPhone, userCity, userCountry)
}
})
Try this
val userId = authRef.currentUser?.uid
val currentUser = dataRef.getReference
val userchild = currentuser.child("Users").child("userId")
userchild.addValueEventListener(object : ValueEventListener{
override fun onCancelled(p0: DatabaseError) {
}
override fun onDataChange(p0: DataSnapshot) {
val userDisplayName = p0.child("userDisplayName").getValue(String::class.java)
val userPhone = p0.child("userPhone").getValue(String::class.java)
val userCity = p0.child("userCity").getValue(String::class.java)
}
})
Must type exect spellings of Users, UserId and other childs. and To these values to textview in the Ui add
TextView.setText=variable abc
Your Mistakes in codes.You have not taken correct data snapshot which i have updated.
To retrieve the data try the following:
override fun onDataChange(p0: DataSnapshot) {
// I need to get data from here ( userDisplayName , userPhone, userCity, userCountry)
val userDisplayName = p0.child("userDisplayName").getValue(String::class.java)
val userPhone = p0.child("userPhone").getValue(String::class.java)
val userCity = p0.child("userCity").getValue(String::class.java)
}
})
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
}
}
Created next structure in my database, and now want to display data in my list
Tried to add next code in onViewCreated:
databaseReference = FirebaseDatabase.getInstance().reference
val wordsRef = databaseReference?.child("talk-6e3c0")?.child("words")
val valueEventListener = object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
topWordsList.clear()
for (wordsSnapshot in dataSnapshot.children) {
val topWord = wordsSnapshot.getValue(TopWord::class.java)
topWord?.let { topWordsList.add(it) }
}
}
override fun onCancelled(databaseError: DatabaseError) {
Log.d("some", "Error trying to get targets for ${databaseError.message}")
}
}
wordsRef?.addListenerForSingleValueEvent(valueEventListener)
Method onDataChanged was called, but i can't get name for example.
My model:
data class TopWord(
val name: String = "",
val description: String = ""
)
You aren't getting something because you are adding the name of your project as a child in the reference and there is no need for that. So please change the following line of code:
val wordsRef = databaseReference?.child("talk-6e3c0")?.child("words")
to
val wordsRef = databaseReference?.child("words")
I just removed the call to .child("talk-6e3c0")?.
Running into an error I have been researching and attempting to fix for the past couple weeks. There are tons of suggestions out there and I've tried at least half a dozen with the same result each time.
How does Kotlin access Firebase data and populate a very simple data class?
Error: com.google.firebase.database.DatabaseException:
Can't convert object of type java.lang.String to type com.touchtapapp.handsofhope.LandingTextTitles
Read about suggestions to first convert to a Map and then to my custom data class... attempted this, successfully created the Mapped values w/ correct data... but ran into the exact same error when sending the Mapped values to the customs data class (LandingTextTitles).
Current code:
Data Model Class
data class LandingTextTitles(
val subTitle: String,
val title: String
)
Method to retrieve data from firebase
private fun initTitles() {
val ref = FirebaseDatabase.getInstance().getReference("/landing")
ref.addListenerForSingleValueEvent(object: ValueEventListener {
override fun onDataChange(p0: DataSnapshot) {
p0.children.forEach {
val titles = it.getValue(LandingTextTitles::class.java)
}
}
override fun onCancelled(p0: DatabaseError) {
// Handle Cancelled Data
}
})
// Log the titles value to see if data passed correctly
Log.d("Titles", titles.toString())
}
When I log out something like Log.d(it.toString()), I see the keys and values just fine. What am I doing wrong here?
EDIT:
Firebase data snapshot
EDIT 2:
If we use Log.d("Titles", it.toString()), we get the following:
D/Titles: DataSnapshot { key = subTitle, value = Start Here. }
D/Titles: DataSnapshot { key = title, value = Facing unexpected problems? }
If you have the following database:
landing
randomId
subTitle : "Awesome"
title : "Developer Team"
Then you can retrieve title and subTitle by doing the following:
private fun initTitles() {
val ref = FirebaseDatabase.getInstance().getReference("/landing")
ref.addListenerForSingleValueEvent(object: ValueEventListener {
override fun onDataChange(p0: DataSnapshot) {
p0.children.forEach {
val title = it.child("title").getValue(String::class.java)
val subTitle = it.child("subTitle").getValue(String::class.java)
}
}
override fun onCancelled(p0: DatabaseError) {
// Handle Cancelled Data
}
})
// Log the titles value to see if data passed correctly
Log.d("Titles", titles.toString())
}
If you want to use the data class, then change this:
override fun onDataChange(p0: DataSnapshot) {
p0.children.forEach {
val titles = it.getValue(LandingTextTitles::class.java)
}
into this:
override fun onDataChange(p0: DataSnapshot) {
val titles = p0.getValue(LandingTextTitles::class.java)
}