Firebase data sorting by date stamp - android

Ia am working on an app that receives datamessages with timestamp in the format "yyyy/MM/dd kk:mm:ss". here is the JSON data format.
"NOT20170828132901" :
{
"code" : "Your order status has been updated to Rejected",
"date" : "2017/08/28 13:29:01",
"title" : "Order update SPB20170825095233542"
}
i want to sort the NOTNUMBER based on the latest timestamp. I tried with limitToLast(i) and also limitToFirst(i) but in vein. The result is Ascending order. Iwant the datestamp to be sorted in Descending order. I also tried using startAt(futuredatestamp).endAt(pastdatestamp) but not working. I want to sort in this ay:
"NOT20170828140827" : {
"code" : "Your order status has been updated to Rejected",
"date" : "2017/08/28 14:08:27",
"title" : "Order update SPB20170825095233542"
},
"NOT20170828140436" : {
"code" : "Your order status has been updated to Delivered",
"date" : "2017/08/28 14:04:36",
"title" : "Order update SPB20170825095233542"
},
"NOT20170828132901" : {
"code" : "Your order status has been updated to Rejected",
"date" : "2017/08/28 13:29:01",
"title" : "Order update SPB20170825095233542"
},
"NOT20170828115852" : {
"code" : "Your order status has been updated to Rejected",
"date" : "2017/08/28 11:58:52",
"title" : "Order update SPB20170825095233542"
},
"NOT20170828014147" : {
"code" : "Your order status has been updated to IN TRANSIT",
"date" : "2017-08-28 01:41:47",
"title" : "Order update : SPB20170825095233542"
}
Little confused in using filter parameters.
Please help me. Thank in advance

Making an assumption that you are displaying the data from Firebase in a Recyclerview, add this code.
mLayoutManager = new LinearLayoutManager(MyActivity.this);
mLayoutManager.setReverseLayout(true);
mLayoutManager.setStackFromEnd(true);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(yourAdapter);
What the code above does, it reverses the contents of the recyclerview.

The best practice to save date and time in a Firebase database, is to save it as a TIMESTAMP using ServerValue.TIMESTAMP like this:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
Map map = new HashMap();
map.put("time", ServerValue.TIMESTAMP);
yourRef.child("yourNode").updateChildren(map);
Remember, you are saving the TIMESTAMP as a Map but you are retrieving it as a long. To get the data back, i suggest you using this method:
public static String getTimeDate(long timeStamp){
try{
DateFormat dateFormat = getDateTimeInstance();
Date netDate = (new Date(timeStamp));
return dateFormat.format(netDate);
} catch(Exception e) {
return "date";
}
}
Then the orderBy() method in your query will work for sure.

Related

Firebase Realtime Database Filter Data in Nested List

I wanted to retrieve filtered data from db according to extra_Cat value like 31
I am able to retrieve full data easily but unable to put filter in it
Note: I have checked almost every solution, If duplicate please reply then tag duplicate
my code is
DBConnection dbConnection=new DBConnection();
postRef=dbConnection.database.getReference("Data");
postRef.child("extra_Cat").orderByKey().equalTo("*31*").limitToLast(500).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
long as= dataSnapshot.getChildrenCount();
Log.d("Data", String.valueOf(as));
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
}
});
and JSON is
"32161" : {
"author_name" : "Talented+Desk",
"cat_ID" : "%2A7%2A",
"cat_name" : "%E0%A4%96%E0%A5%87%E0%A4%B2",
"content" : "A4%B5A4%A8%E0%A4%BF%E0%A4%AF%E0%A4%AE+%E0%A4%B9%E0%A5%88%E0%A4%82%7C%E2%80%9D%3C%2Fp%3E%0A",
"extraCat" : [ "*31*", "*14*" ],
"fea_image" : "https%3A%2F%2Fwww.talentedindia.co.in%2Fwp-content%2Fuploads%2F2018%2F03%2Faajeevan-pratibandh-Steve-Smith.jpg",
"post_comment" : "0%A4%BF%E0%A4%AF%E0%A5%8B%E",
"post_date" : "2018-03-26",
"post_id" : "32161",
"post_slug_name" : "kangaroos-protest-against-less-punishment",
"post_status" : "publish",
"post_time" : "10%3A45%3A40",
"post_video" : "",
"slider_image1" : "",
"slider_image2" : "",
"slider_image3" : "",
"slider_image4" : "",
"title" : "%E0%A4%94%B8%E0%A4%9C%E0%A4%BE+%E0%A4%AA%E0%A4%B0+%E0%A4%B5%E0%A4%BF%E0%A4%B0%E0%A5%8B%E0%A4%A7"
},
You cannot create a query based on values that exist within an array. As I see in your database, extraCat is an array which contains 2 values, *31* and *14*.
In order to solve this, you need to change your database structure a little bit. So your extraCat node should look like this:
extraCat
|
--- "*31*": true
|
--- "*14*": true
As you can see, the extraCat node the is now a Map. The corresponding query should look like this:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRef.child("Data")
.orderByChild("extra_Cat/*31*")
.equalsTo(true)
.limitToLast(500)
.addValueEventListener(/* ... */)
First you are using wrong reference path. The current you are using is Data/extra_cat. As I see in your Firebase structure it should be Data/32343/extraCat.
You can't use .child("extra_Cat").orderByKey().equalTo("*31*") because the *31* is not of the extra_Cat keys value. The value is in the list.

Getting rank of user from firebase database in android

I have a real time firebase database that stores a list of users and it's stored in the following format(Json)
{
"users" : {
"-L29HeOZCmYu9UGJLMQR" : {
"name" : "John Doe",
"phoneNumber" : "+555-1566",
"points" : 21,
"rank" : 10,
"userId" : "-L29HeOZCmYu9UGJLMQR"
},
"-L2ASCuStoH7CTaqgBgG" : {
"name" : "Jenna Rose",
"phoneNumber" : "+555-3562",
"points" : 96,
"rank" : 0,
"userId" : "-L2ASCuStoH7CTaqgBgG"
},
....// A lot more users.
}
So my question is, how do I get the rank of the user in terms of the "points" variable? Also, how do I prepare a list of the top 10 or the top 100 etc..?
There is no way to get the rank of a specific user, without loading all users.
But you can get the top N users by using Firebase's query mechanism to sort and filter data. For example:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("users");
Query top10query = ref.orderByChild("points").limitToLast(10);
top10query.addChildEventListener(...
The children will be in ascending order. You'll have to revert them client-side, for example by adding each subsequent child to the top of the list.

Firebase - Filtering Query Data

I have a group of comments for different blog posts.
The problem now is every comment displays on every blog post.
Im calling the data with
myref= FirebaseDatabase.getInstance().getReference().child("comments");
Which returns all comments.
This is the data JSON
{
"comments" : {
"-KgnRe9d5s471yDWVYBk" : {
"_id" : "56e35e39106a750e008c33b5",
"_blogID" : "56ba5f6a894eeb0e008c86c0",
"commentKey" : "-KgnRe9d5s471yDWVYBk",
"detail" : "test comment",
"user" : "john",
"votes" : 0
}
Id like to filter all comments by "_blogID"
Thanks
You can use a Query like this: Query query = myref.child(commentKey).orderByChild("_blogID");

Wrong serialization JSON in String field

I'm developing app using QuickBlox services. I have String field with JSON in content. This is my JSON:
{"answers":[[{"name":"first"}],[{"name":"second"}],[{"name":"third"}],[{"name":"fourth"}],[{"name":"fifth"}],[{"name":"sixth"}]]}
Here is problem. When I want to get my field with JSON from QBCustomObject, it is serialized to this (without quotes and square braces):
[{
answers :
{
name : first
},
{
name : second
},
{
name : third
},
{
name : fourth
},
{
name : fifth
},
{
name : sixth
}
}]
What can I do in this situation?
I found in QBCustomObjectDeserializer class that code:
if(value.contains("[")) {
String[] values2 = value.replace("[", "").replace("]", "").replace("\"", "").split(",");
Can I change rules of deserialization in QuickBlox SDK? Can I use my own deserializer?
Anyone can help resolve my problem please?
Fixed in development branch
https://github.com/QuickBlox/quickblox-android-sdk/tree/development
will be rolled out in our next upcoming release

How to retrieve Firebase data and bind it to a list view?

I am new to Firebase, and am trying to implement it into my Android app. At this moment, I have a list view where I want to show scheduleTime and scheduleName. Let's call this list view lvTodaySchedule.
Next, this is how my data in Firebase looks like
{
"schedule" : {
"-JvA3muNBCoTISLalZZq" : {
"date" : "24 July 2015",
"schedule description" : "Bring some sandwiches and apples",
"schedule name" : "Picnic",
"selected route" : "Route 1",
"time" : "0:52"
},
"-JvA3muNdSdSasdlZAsS" : {
"date" : "24 July 2015",
"description" : "Run around like mad for 20 minutes",
"schedule name" : "CARDIO",
"selected route" : "Route 1",
"time" : "0:41"
}
}
}
What I want to do is retrieve the date, time and name. So basically in SQL logic, retrieve time and name WHERE date = 24 JULY 2015, and the display it ORDER BY time.
The firebase tutorial teaches me to retrieve a dataSnapshot (which is an Object) of the above data, but I have no idea what to do with it.
I also want to display all these info into the list view, so I was wondering if it's possible to retrieve the data and put them in an array or something.

Categories

Resources