I am trying to fetch the last 30 days posts from firebase and I am trying to use the timestamp in the posts in order to do so. But I am not able to fetch the data.
Kotlin Code:
var database:DatabaseReference=Firebase.database.reference
database.orderByChild("timestamp")
val postListener = object : ValueEventListener {
@RequiresApi(Build.VERSION_CODES.O)
override fun onDataChange(dataSnapshot: DataSnapshot) {
// Get Post object and use the values to update the UI
for(postSnapshot in dataSnapshot.children)
{
if(postSnapshot.child("timestamp").value.toString().toInt()>Time.from(Instant.now().minusSeconds(30*24*60*60)).toString().toInt())
{
val Post = postSnapshot.getValue(PostsModel::class.java)
postsList.add(Post!!)
}
}
}
override fun onCancelled(databaseError: DatabaseError) {
// Getting Post failed, log a message
Timber.d("failed")
}
}
CodePudding user response:
You need to add a condition that the time must be more than a month ago, then you will produce a list of suitable data. The error can also be at another level that you did not provide (data organization or perhaps you did not connect a listener)
Firebase.database.reference
.whereGreaterThan("timestamp", Calendar.getInstance().also { it.add(Calendar.MONTH, -1) }.timeInMillis)
CodePudding user response:
You're declaring a listener, but you're not attaching it to the database. Until you call addValueEventListener
, addListenerForSingleValueEvent
, or get()
.
I recommend studying the Firebase documentation on reading data as it shows how to do those.