Firebase query equalTo() or startAt().endAt() stop working - firebase

I already tried suggestions from other posts but no success.
I just run into an issue,I got the following code which displays data from Firebase database when user clicks on a specific date.If I comment out (startAt(),endAt()), the recycler gets populated with all data, when I add equalTo() or startAt().endAt()) recycler does not get populated.
The code before was working normally, just recently stopped working and I have no clue why.
The code looks like this:
Bellow is the adapter:
fun calendarAdapt(options:FirebaseRecyclerOptions<ModelCalendar>,dataref:
DatabaseReference,context: Context):FirebaseRecyclerAdapter<ModelCalendar,CalendHold>{
return object :FirebaseRecyclerAdapter<ModelCalendar,CalendHold>(options){
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CalendHold {
return
CalendHold(LayoutInflater.from(parent.context).inflate(R.layout.list_row_calendar,parent,false))
}
override fun onBindViewHolder(holder: CalendHold, positionc: Int, modelc: ModelCalendar)
{
val postkeyC= getRef(positionc).key
dataref.child(postkeyC!!).addValueEventListener(object:ValueEventListener{
override fun onDataChange(dataSnapshot: DataSnapshot) {
holder.bindlogC(modelc)
}
override fun onCancelled(p0: DatabaseError) {
}
})
}
}
}
This is the Query:
fun query2(cont: LifecycleOwner,selected_date:String):FirebaseRecyclerOptions<ModelCalendar>{
val queryy = FirebaseDatabase.getInstance()
.reference
.child("Ev")
.startAt(selected_date)
.endAt(selected_date)
return FirebaseRecyclerOptions.Builder<ModelCalendar>()
.setQuery(queryy,ModelCalendar::class.java)
.setLifecycleOwner(cont)
.build()
}
Here I apply the adaptor:
mDb = FirebaseDatabase.getInstance().reference.child("Ev")
val c = Calendar.getInstance()
val year2 = c.get(Calendar.YEAR)
val month2 = c.get(Calendar.MONTH)
val day2 = c.get(Calendar.DAY_OF_MONTH)
val dayd= checkDigit(day2)
val monthd= checkDigit(month2+1)
val datetoday = java.lang.StringBuilder()
.append(dayd)
.append("-")
.append(monthd)
.append("-")
.append(year2)
calendinf(datetoday.toString())
calendarid.setOnDateChangeListener { view, year, month, dayOfMonth ->
val month = checkDigit(month+1)
val day = checkDigit(dayOfMonth)
val datesel =StringBuilder()
.append(day)
.append("-")
.append(month)
.append("-")
.append(year)
calendinf(datesel.toString())
}
}
private fun calendinf(selected_date:String){
val options = Queryess().query2(this,selected_date)
val adaptorC = Adaptall().calendarAdapt(options, mDb,this)
calerec!!.adapter=adaptorC!!
}

I fix-it,It was the query, was missing "orderBychild()" field, most probable I mistakenly deleted otherwise cannot explain-it :))

Related

Retrieving data from push() in firebase kotlin that equal to the selected value

Hello can someone that can help me to retrieve the data of selected value from generate key or push in Realtime Database Firebase. Nothings happen when I clicking the button I think my child is not order correctly. This is the collection tree from firebase;
val btnSyncing = findViewById<TextView>(R.id.btnSync)
btnSyncing.setOnClickListener {
val user = FirebaseAuth.getInstance().currentUser
val userid = user!!.uid
database = FirebaseDatabase.getInstance()
reference = database.getReference("Profile")
val timeTextView = findViewById<TextView>(R.id.txtTime)
val dateTextView = findViewById<TextView>(R.id.txtDate)
reference.child(userid)
.child("Delivery Details").orderByChild("Date").equalTo("24/9/22")
.addListenerForSingleValueEvent(object: ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
val time = dataSnapshot.child("Time").value as String?
val date = dataSnapshot.child("Details").value as String?
timeTextView.text = time
dateTextView.text = date
}
override fun onCancelled(error: DatabaseError) {
Toast.makeText(baseContext, "Something wrong happened!", Toast.LENGTH_LONG)
.show()
}
})}

How to sum of values from Firebase Database in Kotlin?

I have a Firebase Database with several purchases in Android app, points value is assigned for each purchase, then entries are showing by following way:
When userId is log in, a button appears and when user click on it the "showInfoClient" function is called and it must show user and the amount of points. Code is:
private val database = Firebase.database
private val myref = database.getReference("compras")
fun showInfoClient(view: View) {
val userlog = FirebaseAuth.getInstance().currentUser?.displayName
val alertDialogInfo = AlertDialog.Builder(this).create()
myref.orderByChild("userId").equalTo(userlog).addListenerForSingleValueEvent(object :
ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
var sum = 0
for (data in dataSnapshot.children) {
sum += data.child("puntos").getValue(Int::class.java)!!
Toast.makeText(this#Principal, sum, Toast.LENGTH_SHORT).show()
}
}
override fun onCancelled(databaseError: DatabaseError) {}
})
alertDialogInfo.setTitle(userlog)
alertDialogInfo.setMessage("Puntos: ") // + sum
alertDialogInfo.setButton(
AlertDialog.BUTTON_POSITIVE, "OK"
) { dialog, _ ->; dialog.dismiss() }
alertDialogInfo.show()
val btnPositive = alertDialogInfo.getButton(AlertDialog.BUTTON_POSITIVE)
val layoutParams = btnPositive.layoutParams as LinearLayout.LayoutParams
layoutParams.weight = 100f
btnPositive.layoutParams = layoutParams
}
I have tried to use different options but i´m not able to set "sum" value on
alertDialogInfo.setMessage("Puntos: $sum")
Thanks in advance
Any code that needs data from the database needs to be inside onDataChange or be called from there. Code outside of onDataChange will (most likely) run before the data is loaded.
So:
val userlog = FirebaseAuth.getInstance().currentUser?.displayName
val alertDialogInfo = AlertDialog.Builder(this).create()
myref.orderByChild("userId").equalTo(userlog).addListenerForSingleValueEvent(object :
ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
var sum = 0
for (data in dataSnapshot.children) {
sum += data.child("puntos").getValue(Int::class.java)!!
}
alertDialogInfo.setTitle(userlog)
alertDialogInfo.setMessage("Puntos: ") // + sum
alertDialogInfo.setButton(
AlertDialog.BUTTON_POSITIVE, "OK"
) { dialog, _ ->; dialog.dismiss() }
alertDialogInfo.show()
val btnPositive = alertDialogInfo.getButton(AlertDialog.BUTTON_POSITIVE)
val layoutParams = btnPositive.layoutParams as LinearLayout.LayoutParams
layoutParams.weight = 100f
btnPositive.layoutParams = layoutParams
}
override fun onCancelled(databaseError: DatabaseError) {
throw databaseError.toException(); // never ignore errors
}
})
For a longer explanation see:
getContactsFromFirebase() method return an empty list
Setting Singleton property value in Firebase Listener

I am retreiving data from firebase and the recyclerview is showing it out of order

I am trying to retrieve data from firebase. All the data comes up correctly but it is out of order and I can not figure out why? The data should be read from beginning to end:
val publicFeedMap = HashMap<String, Feed>()
private fun refreshRecyclerViewMessages(){
adapter.clear()
publicFeedMap.values.forEach{
adapter.add(PublicFeedItem(it))
}
}
private fun fetchPublicFeed(){
val ref = FirebaseDatabase.getInstance().getReference("PublicFeed")
ref.addChildEventListener(object: ChildEventListener{
override fun onChildAdded(p0: DataSnapshot, p1: String?) {
p0.children.forEach {
val feedItem = p0.getValue(Feed::class.java) ?: return
publicFeedMap[p0.key!!] = feedItem
refreshRecyclerViewMessages()
}
}
override fun onChildChanged(p0: DataSnapshot, p1: String?) {
}
override fun onChildMoved(p0: DataSnapshot, p1: String?) {
}
override fun onCancelled(p0: DatabaseError) {
}
override fun onChildRemoved(p0: DataSnapshot) {
}
})
}
the data should be sorted from beginning to end
you have to order the data by adding:
orderByKey or orderByChild it would be better if you provide the data you want to use and how you want to order it
Check this:
https://beginnersbook.com/2013/12/how-to-sort-hashmap-in-java-by-keys-and-values/
Check this also:
https://firebase.google.com/docs/database/web/read-and-write

Kotlin Firebase: Can't convert object of type java.lang.String to type com.example.Model.perizinan

I am trying to load data from Firebase to RecyclerView, I need to get data from Firebase to ArrayList but I get the below error:
com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type com.example.Model.perizinan
this is my class:
class perizinan(val imageUrl:String, val namakegiatan:String, val keterangan:String, val waktuKegiatan:String, val presensiIzin:String, val tanggalkegiatan:String)
class izin(val perizinan:List<perizinan>)
this is my code:
fun readFirebaseDatabase(){
val ref= FirebaseDatabase.getInstance().getReference("Admin")
ref.addValueEventListener(object: ValueEventListener {
override fun onCancelled(p0: DatabaseError) {
Log.e("AdminActivity","cancelled")
}
override fun onDataChange(p0: DataSnapshot) {
val uid = FirebaseAuth.getInstance().uid
p0.child(uid!!).children.forEach{
it.children.forEach{
val posts = ArrayList<perizinan>()
for (snapshot in it.children) {
val post = snapshot.getValue(perizinan::class.java)
posts.add(post!!)
}
RecyclerViewAdmin.layoutManager = LinearLayoutManager(this#AdminActivity)
RecyclerViewAdmin.adapter = adminAdapter(izin(posts), this#AdminActivity)
}
}
}
})
}
below is my database structure:
You are getting that error because you are using a wrong reference when trying to get a perizinan object from the database. To solve this, please change the following line of code:
val ref= FirebaseDatabase.getInstance().getReference("Admin")
to
val ref= FirebaseDatabase.getInstance().getReference()
.child("Admin")
.child(FirebaseAuth.getInstance().uid)
.child(senderId)
and
p0.child(uid!!).children.forEach{ /* ... */ }
to
p0.children.forEach{ /* ... */ }

Get random entries in firebase real-time database

This is my code to get 5 items from realtime database:
val database = FirebaseDatabase.getInstance()
val brandReference = database.getReference("brandGame").limitToFirst(5)
brandReference.addValueEventListener(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
dataSnapshot.children.forEach {
...
}
}
}
And this is how my real-time database looks like:
What's the best way to get 5 items randomly? I know there isn't a random function in real time database yet.
If you know the number of elements in the brandGame/-reference, you could pick 5 random numbers between 1 and numberOfElements and retrieve those. This would result in multiple calls to the database.
Alternatively, you could download everything from the brandGame/-reference and just pick 5 random elements using pure Kotlin. But then you must download everything in the reference, which could be a lot.
The best option is to set up a cloud function that does the "pick 5 random options"-logic server side. https://firebase.google.com/docs/functions/ But this requires that you write some js :)
As you say, there is no built-in way to get random elements from a reference.
To get a random brand, please use the following code user side:
val rootRef = FirebaseDatabase.getInstance().reference
val brandGameRef = rootRef.child("brandGame")
val valueEventListener = object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
val brandCountList = ArrayList<String>()
for (ds in dataSnapshot.children) {
val brand = ds.child("brand").getValue(String::class.java)
brandCountList.add(brand!!)
}
val brandCount = brandCountList.size
val randomNumber = Random().nextInt(brandCount)
val randomBrand = ArrayList<String>()
randomBrand.add(brandCountList.get(randomNumber)) //Add the brand product to list
val arrayAdapter = ArrayAdapter(applicationContext, android.R.layout.simple_list_item_1, randomBrand)
list_view.adapter = arrayAdapter
}
override fun onCancelled(databaseError: DatabaseError) {
//Handle exceptions
}
}
brandGameRef.addListenerForSingleValueEvent(valueEventListener)

Resources