How to store ServerValue.TIMESTAMP as a string in Firebase database - android

I've an a firebase recyclerview and I want to query that datas in a OrderByChild for example TOPWEEK or TOPDAYS in order to that I planning to combin ServerValue.TIMESTAMP with star counts such as
"Combin" : "1522741072_5"
first value is timestamp second value is star counts. but if I made this every time new one goes top, star counts is ignored (because of timestamp is in mili sec). I thinking that I should trim some value from timestamp. like this:
String.valueOf(ServerValue.TIMESTAMP).substring(0,4)
but it is not possible because I cant store timestamp as a string in firebase database. this is my model class
#Exclude
public Map<String, Object> haritala() {
HashMap<String, Object> result = new HashMap<>();
result.put("yazar", yazar);
result.put("baslik", baslik);
result.put("uid",uid);
result.put("favsays", favsays);
result.put("fav", favori);
result.put("mesajsays", mesajsays);
result.put("mesaj", mesaj);
result.put("Combin", ServerValue.TIMESTAMP);
return result;
}
Are there any solution

According to your last comment, I understood that the star counts does not contains a fixed value, it can be incremented by users. In this case, your solution will not work. There is another solution to have two separate properties but unfortunately, Firebase Realtime database does not support queries on multiple properties, supports only queries on a single child property. Also you should not consider augmenting your data structure to allow a reverse lookup because in that case you'll have to many nodes.
If I were you, every time I should add a new item to the database, I'll use the push() method, which will generate as the key of the item, a random key which is based on time. So by default, all your items will be sorted by creation time. In this case, you'll only need to use a query that will look like this:
Query query = rootRef.child("results").orderByChild("reuslt");
Don't forget to set the value of result property as an Integer or as a Long, not as a String because in case of string the items are ordered lexicographically.
You can consider take a look at Cloud Firestore, in which chained queries are permitted.

Related

Displaying latest into custom Info window by timestamp from Firebase [duplicate]

I am developing an Android chat application in which I need to order the conversation details by the date. My firebase data structure is mentioned below.
Now I want to retrieve and show the data on the latest date on my RecyclerView from Firebase Realtime Database based on timestamp.
I have tried the following approaches.
final DatabaseReference nm =
FirebaseDatabase.getInstance().getReference("Transaction");
Query query = nm.orderByChild("Date").limitToFirst(5);
;
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
listData.clear();
if (dataSnapshot.exists()) {
for (DataSnapshot npsnapshot : dataSnapshot.getChildren()) {
Transaction ld = npsnapshot.getValue(Transaction.class);
listData.add(ld);
}
Tadapter = new TransactionAdapter(listData);
rv.setAdapter(Tadapter);
Log.d(TAG, "Total Count" + Tadapter.getItemCount());
}
}
}
I am developing an android chat application in which I need to order the conversation details by the date.
As I see in your screenshot, your Date property is of type String. This means that you cannot call:
.orderByChild("Date")
And expect to behave as it was a Timestamp. When you order String elements, the order that you get is always lexicographically. This means that Strings doesn't consider any sort of numeric values when sorting, especially when it comes to the dates, even if the dates contain numbers, as your first element does:
Date: "30/7/2021"
So using String values when querying your database it's not an option. However, I see you already have a Timestamp property. Maybe on that property, it was supposed to do the ordering. If that was not the case, I suggest you change the type of the Date property from String to Timestamp, as explained in my answer from the following post:
How to save the current date/time when I add new value to Firebase Realtime Database
Now I want to retrieve and show the data on the latest date on my RecyclerView
This means that most likely you need to reverse the order, meaning that all your transactions have to be displayed in your RecyclerView descending. In this case, there are a few options that you have, either on the server or on the client.
Assuming that you have changed the type of your Date property from String to Timestamp, then you can simply consider storing an inverted Timestamp value like this:
Firebase-root
|
--- transactions
|
--- 1
|
--- Date: 1627714194
|
--- invertedDate: -1627714194
See, the invertedDate property holds a negative value. Since by default, the elements are ordered ascending, to be able to order the transaction desecendiong, you should simply use:
Query query = nm.orderByChild("invertedDate").limitToFirst(5);
On the other hand, there are some workarounds that can be made to achieve the same thing on the client, as explained in my answer from the following post:
How to arrange firebase database data in ascending or descending order?
Query query = nm.orderByChild("Date").limitToFirst(5);
Firebase realtime database sorts in ascending order that means those 5 nodes that you'll receive will be the oldest.
I want to retrieve and show the data in latest date
Try using limitToLast instead which will return the last 5 documents after ordering the nodes by Date field i.e. the 5 latest nodes.
Query query = nm.orderByChild("Date").limitToLast(5);
You can read more about that at sorting and filtering data.

How can I compare the child values in Firebase?

I am using firebase realtime database to track the inventory on a track. I am doing something simple. As you can see in the image above an item has been added twice to the database instead of adding the quantities. How can I check that an item with a certain SKU and location_name already exists in the database?
If you want to store the inventory per product, and products have unique keys already, consider using that existing key in the database, instead of using push() to generate a new unique ID.
So where you now do something like:
db.push().setValue(objectForSkuPVC005PBPSTA);
Instead do:
db.child("PVC005PBPSTA").setValue(objectForSkuPVC005PBPSTA);
That way you can always update the child at db.child("PVC005PBPSTA") when you need to change its quantity.
A second unrelated point: you're storing the quantity as a string. I recommend storing it as an actual number, so that you can use numerical operations (such as the new ServerValue.increment()) to manipulate it.

How to order firebase data from the latest

Firebase by default orders data from the earliest and I need it to be ordered from the latest.
I am using timestamp to do so and doesn't seem to be working.
private void filldata() {
mDatabase.child("Data").orderByChild("timestamp").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot snapshot, String s) {
System.out.println("snapshot:" + snapshot.toString());
}
}
You no need to use orderByChild() here in your case because firebase itself generate unique key which is based on a timestamp, so you can simply use orderByKey() in your query and you will get your data in latest order.
The unique key is based on a timestamp, so list items will
automatically be ordered chronologically. Because Firebase generates a
unique key for each blog post, no write conflicts will occur if
multiple users add a post at the same time.
You can find more here
I'll suggest to use
mDatabase.child("Data").orderByKey().limitToLast(no_of_items_you_want)
This will give you list of latest data
Also to get value from snapshot use
snapshot.getValue(String.class);
Since orderByChild() only sort data in ascending order, you should store an extra data item in your child node whith the value timestamp*(-1) and then sort (order) on this data item.
Your code is correct. The commonly suggested way to order will be by using a negative timestamp.
However I have noticed previously that firebase does order your results by timestamp, as you currently wish for it to do. When the device receives the results it reorders the results by arrival (suspicion).
To test this, try limit your results by using the .limitToLast(n) function, you will realize that while firebase will return the last 10 (in order of timestamp) results to you, these results will not be ordered by timestamp.
Therefore, the best solution will be to store the firebase results in a list and reorder the list using a sorting tool like a comparator

Fetching items from dynamoDB with sorting

In my project i want to fetch all records from table with sort by created_date descending order.
Also i want to add condition of fetch all item not created_by login user.
I have tried many ways but not able to achieve it.
Below is my table structure.
Here is my java code to fetch records from dynamoDB.
Map<String, Condition> filter = new HashMap<String, Condition>();
//filter.put(RealmConstant.Expo.created_by, new Condition().withComparisonOperator(ComparisonOperator.NE).withAttributeValueList(new AttributeValue().withS(userId)));
filter.put(RealmConstant.Expo.created_date, new Condition().withComparisonOperator(ComparisonOperator.LE.toString()).withAttributeValueList(new AttributeValue().withS(""+new Date())));
Expo expo =new Expo();
expo.setCreated_by(userId);
DynamoDBQueryExpression<Expo> queryExpression = new DynamoDBQueryExpression<Expo>();
queryExpression.setHashKeyValues(expo);
queryExpression.setIndexName(AppConstant.DynamoDBTableIndex.created_by_created_date_index);
queryExpression.setConsistentRead(false);
queryExpression.setRangeKeyConditions(filter);
queryExpression.setScanIndexForward(false);
return mapper.query(Expo.class, queryExpression);
As per above code i am getting all records created by me only. I want to fetch all records not created by me.
Also tried .withFilterExpression("created_by <> :val1").withExpressionAttributeValues(eav); but not working. As already question posted. Why is there no **not equal** comparison in DynamoDB queries?
and
DynamoDB: Filter Expression can only contain non-primary key attributes
The short answer is that you can’t fetch *all the items from a DynamoDB table in sorted order, by any attribute. DynamoDB just doesn’t work that way.
Think of DynamoDB as a distributed hash map of lists.
Just the same as you can’t expect to be able to get globally sorted results from such a map of lists, you can’t get them from DynamoDB either.
You can scan the whole table, and even filter, out some unwanted results as you go, but for sorting, you need to do it after you’ve fetched the records.
What you can do is retrieve items that have the same partition key, in order or the sort key.
And you can create an index where you pick an arbitrary attribute as the partition key and another as the sort key but even that approach has some limitations.
The best way to go is to really take some time and think about what you are going to do with the data. Why are trying to retrieve all items from the table in sorted order? Perhaps there is a better way to organize your data such the you din’t need to retrieve all of it.

Unable to use .startAt() with datetime in milliseconds

I have a very similar problem to this post - Firebase Query filtered by creation time and where date is greater than now
I have my dates stored in a "message" and I want to retrieve all messages after the current time.
This query works:
Query myTopPostsQuery = mFirebaseDatabaseReference.child(MESSAGES_CHILD).orderByChild("time");
this query returns no data:
Query myTopPostsQuery = mFirebaseDatabaseReference.child(MESSAGES_CHILD).orderByChild("time").startAt(System.currentTimeMillis());
This seems like it should work but from the docs I'm wondering if this is a data type problem?
In your query, you need to specify the full path to the child used for ordering:
orderByChild("date/time")
You indicate that your first query works. It may return the number of messages you expect, but if you look at them, you will find they are not ordered. The query processing is forgiving. If it doesn't find a value for the child identified by orderByChild(), it assigns a value of null and orders by these rules.

Categories

Resources