I am new to Android and Firebase.. I have stored data in Firebase DB by importing JSON file. Now I am trying to retrieve data in Android textbook. But I am unable to stringify the JSON data, which I did in JavaScript. Also I am not able to get the data in the numerical order, which I am getting in JavaScript.
Following the code DB structure:
// Initialize with secondary app.
FirebaseApp.initializeApp(this /* Context */, SITEINFO, "secondary_SITEINFO");
// Retrieve secondary app.
FirebaseApp secondary_siteinfo = FirebaseApp.getInstance("secondary_SITEINFO");
// Get the database for the other app.
FirebaseDatabase secondaryDB_siteinfo = FirebaseDatabase.getInstance(secondary_siteinfo);
final Query query1 = secondaryDB_siteinfo.getReference("");
fetch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
query1.orderByChild("01-SITEID").equalTo("EKM01").addListenerForSingleValueEvent
(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String Value1 = dataSnapshot.getValue().toString();
My Javascript code
var ref = firebase.database().ref('/').orderByChild("01-SITEID").equalTo(input_final)
ref.on("child_added", function(snapshot) {
var obj = JSON.stringify(snapshot.val());
The Firebase native SDKs for Android and iOS return native types for their respective language. They don't return JSON, nor do they have built-in options to convert the data they return to JSON.
If you need to convert the Java objects to JSON for your app, you will have to implement it yourself (or find a library).
Update
When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.
To process the result of your query (in the correct order), use DataSnapshot.getChildren():
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot: DataSnapshot.getChildren()) {
System.out.println(childSnapshot.getKey()+": "+childSnapshot.child("01-SITEID").getValue());
}
}
Related
Please help
this is my firebase structure
firebase structure
following query is working fine but i have to hardcode the push id "MZgPRv6xKK5isnnPTLn" , i dont want to hard code the value highlighted below from following query is there a way to get this reference of this push key ? to be used for query so that i can replace the "MZgPRv6xKK5isnnPTLn"
push id hard coded
Query lastQuery = dbr1.child("users").child(mAuth.getCurrentUser().getUid())
.child("-MZgPRv6xKK5isnnPTLn").child("sms").orderByKey().limitToLast(1);
lastQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dns) {
for (DataSnapshot chl : dns.getChildren())
{
Log.d("read_last_nodes", String.valueOf(dns.child("no").getValue()));
}
}
}
Follows is the code of writing into Firebase
path= dbref_1.child("users").child(mAuth.getUid()).push().getKey();
dbref_1.child("users").child(mAuth.getCurrentUser().getUid()).child(path)
.child("sms").child("SMS_no_" + i).child("no").setValue(no);
You can use 'getKey()' to get any key in firebase database. In your case to get the key you have to point to the hardcoded key, and then use getKey on the returned snapshot. After getting the key you can proceed to run your query.
DatabaseReference ref = dbr1.child("users").child(mAuth.getCurrentUser().getUid())
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dns) {
if(dns.exists) {
String key = dns.getKey();
Query lastQuery = dns.child(key).child("sms").orderByKey().limitToLast(1);
///rest of query logic
}
}
}
I am new to android studio and programming and am currently trying to make my first app. In firebase RTDB, I have multiple push ids under a single child that keep on increasing in number as the user presses certain buttons, and they all store only an integer. I want to retrieve the data from all those push ids(or keys, I don't really know what they are actually called) under the child and then sum the integers up and display the result in a textView and do it every time a new field is added. How can I do that? So far I only know how to normally send and receive data to childs sub-childs like this but i have never ever used push ids or keys before:
String recieve = datasnapshot.child("Child").child("subchild").getText().toString();
String send = "send";
databaseReferenc.child("Child").child("sunchile").setValue(send);
The data tree in firebase is as follows:
Assuming that Australia is a direct child of your Firebase Realtime Database root, to sum all those values, please use the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference australiaRef = rootRef.child("Australia");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int total = 0;
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String value = Integer.parseInt(ds.getValue(String.class));
total += value;
}
Log.d("TAG", "total: " + total);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore potential errors!
}
};
australiaRef.addListenerForSingleValueEvent(valueEventListener);
One more thing. Because you are storing numbers, it best to store them as long values and not as String values.
I'm trying to build a user to user chat application, but I'm not able to order the chat list by last message sent.
My Firebase (real time) structure is like this:
I'm trying to retrieve the data like this, but i'm not able to order by "timestamp" in the inner message.
final String uID = firebaseAuth.getCurrentUser().getUid();
Query ref = FirebaseDatabase.getInstance().getReference("Messages");
ref.orderByChild("timestamp").startAt(uID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Did anyone knows how can I order the list of users by the timestamp of the last message?
You need to change the query to the following:
final String uID = firebaseAuth.getCurrentUser().getUid();
Query ref = FirebaseDatabase.getInstance().getReference("Messages");
ref.child(uID_uID).orderByChild("timestamp").addValueEventListener(new ValueEventListener() {
You need access to the direct node under the node Messages, the node with underscore. Then you can add orderByChild("timestamp").equalTo("157644739279")
I am new in firebase, I want to sort data, by timestamp and my database is below, here key is timestamp
My code for retrieving data is below
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("MainDoor");
Query dataOrderedByKey = myRef.orderByChild("{pushId}/key");
dataOrderedByKey.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Map<String, MyListData> value = ((HashMap<String, MyListData>) dataSnapshot.getValue());
Here i am getting value is not by order of key
I am getting data like below which is not in sort order
Data in a Map is by definition not sorted. So when you call dataSnapshot.getValue(), all information about the order of the items in the DataSnapshot is list.
To maintain the order, use a data structure that supports that, such as a list, and extract the individual items in the correct order by looping over DataSnapshot.getChildren().
So something like:
dataOrderedByKey.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
System.out.println(snapshot.getKey());
MyListData value = snapshot.getValue()
}
}
...
Also you can get data from firebase in sorted order . Refer my answer at Sort Firebase data in ascending/Descending Order
You want to sort by date, right? Try it
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("MainDoor");
myRef.orderByChild('date').addChildEventListener(new ChildEventListener() {
// implement the ChildEventListener methods as documented above
});
Because of the way JavaScript objects work, the ordering of data in the JavaScript object returned by val() is not guaranteed to match the ordering on the server nor the ordering of child_added events. That is where forEach() comes in handy. It guarantees the children of a DataSnapshot will be iterated in their query order.
// Assume we have the following data in the Database:
{
"users": {
"ada": {
"first": "Ada",
"last": "Lovelace"
},
"alan": {
"first": "Alan",
"last": "Turing"
}
}
}
// Loop through users in order with the forEach() method. The callback
// provided to forEach() will be called synchronously with a DataSnapshot
// for each child:
var query = firebase.database().ref("users").orderByKey();
query.once("value")
.then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
// key will be "ada" the first time and "alan" the second time
var key = childSnapshot.key;
// childData will be the actual contents of the child
var childData = childSnapshot.val();
});
});
I have implemented firebase realtime database in my android app, everything is fine. I am trying to add a a search function and I am able to search the database with only starting word match.
Below is my database snapshot:
I am querying for movieName. Right now I am able to search if the query string is Pets/Pe/pet. But when I search for Animals, I get zero results. So, basically what I am looking for is searching the database with query text anywhere in the string. ie., I should be able to search Animals/and/pets and should get the results which contain the search query.
Below is my code so far.
mDatabaseReference.child("recent").getRef().orderByChild("movieName").startAt(query)
.endAt(query + "\uf8ff")
To seach for a string within a String please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference animalsRef = rootRef.child("Animals");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Boolean found;
String search = "Animals";
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String movieName = ds.child("movieName").getValue(String.class);
found = movieName.contains(search);
Log.d("TAG", movieName + " / " + found);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
animalsRef.addListenerForSingleValueEvent(eventListener);
As you see, we query the database for all the movie names and then search for the desired word within the movieName.
First of all check the exact child and initialize the Firebase as like. Have a look at this answer,
https://stackoverflow.com/a/34537728/5746625