Display data from Firebase Realtime Database - android

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")?.

Related

Firebase to Kotlin Fragment

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

KOTLIN: My data do not gets from firebase realtime database

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

How to update Firebase Data using Constructor class

I want to update the Name-based from User Input NIK then show the data to the field and by pressing the update button it will update the data inside the Database.
I'm using this Constructor Class :
import com.google.firebase.database.Exclude
import com.google.firebase.database.IgnoreExtraProperties
#IgnoreExtraProperties
class DatabaseModelUpdate(
var nama : String = ""
) {
#Exclude
fun toMap(): Map<String, Any?> {
return mapOf(
"nama" to this.nama
)
}
}
and my source code is :
val nama = findViewById<EditText>(R.id.editNama).text.toString().trim()
val model = DatabaseModelUpdate(nama)
val post = model.toMap()
var query = reference.orderByKey().equalTo(NIK)
query.addListenerForSingleValueEvent(object : ValueEventListener {
#SuppressLint("SetTextI18n")
override fun onDataChange(dataSnapshot: DataSnapshot) {
if (dataSnapshot.exists()) {
for (userSnapshot in dataSnapshot.children) {
var keys = userSnapshot.ref.key.toString()
val updates = hashMapOf<String, Any>(
"/Users/$keys" to post
)
userSnapshot.ref.updateChildren(updates)
}
}
My JSON :
But, after I pressed the Update Button nothing change.
UPDATE
Codes:
private fun updating() {
val NIK = findViewById<EditText>(R.id.inputNik).text.toString().trim()
val nama = findViewById<EditText>(R.id.editNama).text.toString().trim()
var query = reference.orderByChild("nik").equalTo(NIK)
query.addListenerForSingleValueEvent(object : ValueEventListener {
#SuppressLint("SetTextI18n")
override fun onDataChange(dataSnapshot: DataSnapshot) {
if (dataSnapshot.exists()) {
for (userSnapshot in dataSnapshot.children) {
var keys = userSnapshot.ref.key.toString()
val updates = hashMapOf<String, Any?>(
"Users/$keys/nama" to nama
)
dataSnapshot.ref.updateChildren(updates)
Database :
The codes just making a new nodes instead updating the data
UPDATES 2
using
"nama" to nama
database :
To update the "nama" property of the object which has the key equal to "NIK", you can directly point to that particular property and set the new name as shown in the following lines of code:
val query = reference.orderByKey().equalTo(NIK)
val listener = object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
for (ds in dataSnapshot.children) {
ds.child("nama").getRef().setValue("newNama")
}
}
override fun onCancelled(databaseError: DatabaseError) {
Log.d("TAG", databaseError.getMessage()) //Don't ignore potential errors!
}
}
query.addListenerForSingleValueEvent(listener)
So there is no need at all to create any additional classes for a simple update.
Edit:
You might also consider trying this:
for (userSnapshot in dataSnapshot.children) {
val updates = hashMapOf<String, Any>(
"nama" to "newNama"
)
userSnapshot.ref.updateChildren(updates)
}

Can't convert object of type java.lang.Long to type(Model class); Fetching Data from firebaseDatabase android kotlin

I am using Firebase Database to populate a recyclerview. and i'm facing problem in fetching data.
the error
com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.Long to type com.massino.pfeadelramzi.models.Meuble
my code:
var mdatabase : DatabaseReference?=null
var listMeubles = mutableListOf<Meuble>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_liste_meuble3_d)
mdatabase = FirebaseDatabase.getInstance().reference.child("Bureau")
mdatabase!!.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
for (sna: DataSnapshot in snapshot.children){
val lis: Meuble? = sna.getValue(Meuble::class.java) //THE PROBLEME IS HERE
listMeubles.add(lis!!)
}
mon_recycler.setHasFixedSize(true)
mon_recycler.layoutManager = LinearLayoutManager(this#ListeMeuble3DActivity)
mon_recycler.adapter = MeubleAdapter(listMeubles.toTypedArray()){}
}
override fun onCancelled(error: DatabaseError) {
TODO("Not yet implemented")
}
})
}
My data Class Meuble:
data class Meuble(val imageResource: Int, val nom: String, val prix: Int,val stock:Int)
my Firebase data (now i'm just trying to find a solution so i created just one child
Code to add data to Firebase
button4.setOnClickListener{
var nomUI = spinner.selectedItem.toString()
var prixUI = textView2.text.toString().toInt()
var stockUI= textView3.text.toString().toInt()
var databaseref = firebaseDatabase.getReference(nomUI)
if ( nomUI != null || !TextUtils.isEmpty(prixUI.toString()) || !TextUtils.isEmpty(stockUI.toString())){
var meuble = Meuble(R.drawable.fauteuille2,nomUI,prixUI,stockUI)
databaseref.setValue(meuble)
}else {
Toast.makeText(this,"Remplissez la case manquante",Toast.LENGTH_LONG).show()
}
}
Please help to solve this exception.
As Ticherhaz commented: since you only have the properties for one child nodes under /Bureau, you should use loop over the child nodes in onDataChange.
Right now your loop means that sna points to each individual property, and that's why it fails. There is (for example) no way to parse the value of prix into a `` object.
The code for when you have a single child is:
mdatabase = FirebaseDatabase.getInstance().reference.child("Bureau")
mdatabase!!.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
val lis: Meuble? = snapshot.getValue(Meuble::class.java)
listMeubles.add(lis!!)
mon_recycler.setHasFixedSize(true)
mon_recycler.layoutManager = LinearLayoutManager(this#ListeMeuble3DActivity)
mon_recycler.adapter = MeubleAdapter(listMeubles.toTypedArray()){}
}
override fun onCancelled(error: DatabaseError) {
TODO("Not yet implemented")
}
})
Error Handling :
So to handle my error:
i had to add a Default Value to each parametre in the constructor of my Data class :
data class Meuble(val imageResource: Int = -1, val nom: String="", val prix: Int=-1,val stock:Int=-1)

Retrieve data from Firebase on Android Studio

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

Categories

Resources