Querying Firebase on Android - android

This is my data:
{
"users" : {
"00c49c66-7ac8-9a48-7c4541d8bac6" : {
"email" : "d#gmail.com",
"gender" : "m",
"name" : "deepak",
"user_id" : "00c49c66-7ac8-9a48-7c4541d8bac6"
},
"1cb9c1de-1fcf-a2cc-bf78c84e03c8" : {
"email" : "e#gmail.com",
"gender" : "f",
"name" : "ekta",
"user_id" : "1cb9c1de-1fcf-a2cc-bf78c84e03c8"
},
"38211c3f-6c48-8987-0c698b9b9b52" : {
"email" : "c#gmail.com",
"gender" : "m",
"name" : "chirag",
"user_id" : "38211c3f-6c48-8987-0c698b9b9b52"
},
"a536cf1f-419f-9658-cfb5f5a8ec78" : {
"email" : "a#gmail.com",
"gender" : "m",
"name" : "aniket",
"user_id" : "a536cf1f-419f-9658-cfb5f5a8ec78"
},
"c80d828d-48d7-a79a-9cc558cd1960" : {
"email" : "b#gmail.com",
"gender" : "f",
"name" : "bhakti",
"user_id" : "c80d828d-48d7-a79a-9cc558cd1960"
}
}
}
Now I want to get 'name' and 'id' where 'gender' is "m"
Please can anyone tell me how to fire a query like this from Android client to firebase.
I tried tutorials provided by firebase and few other links but didn't got through.
Most of solutions are in Javascript I need it for Android in firebase's java api.
I tried this
public class ActivityHome extends Activity {
String strLoggedInUserID;
TextView tvData;
Firebase fbRef = new Firebase("https://myurl.com/users");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
tvData = (TextView) findViewById(R.id.tvData);
Query queryRef = fbRef.orderByChild("gender").equalTo("m");
Bundle extras = getIntent().getExtras();
strLoggedInUserID = extras.getString("userID");
fbRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
queryRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
//long longChildCount = dataSnapshot.getChildrenCount();
// tvData.setText(dataSnapshot).toString();
tvData.setText(s);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
//tvData.setText(s);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
}
}

Your querying code looks correct, but you're not printing the user.
Since you're adding a ChildEventListener, it will be called for each child:
queryRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
//long longChildCount = dataSnapshot.getChildrenCount();
// tvData.setText(dataSnapshot).toString();
tvData.setText(s);
}
The dataSnapshot parameter contains information about a single user. To print their key, name and email:
queryRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
System.out.println(dataSnapshot.key());
System.out.println(dataSnapshot.child("name").getValue());
System.out.println(dataSnapshot.child("email").getValue());
}
Alternatively, you can listen to all children at once with a ValueEventListener.
private static class User {
String email;
String gender;
String name;
#JsonProperty("user_id")
String userId;
public String getEmail() { return email; }
public String getGender() { return gender; }
public String getName() { return name; }
public String getUserId() { return userId; }
}
queryRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child: dataSnapshot.getChildren()) {
User user = child.getValue(User.class);
System.out.println(user.getEmail());
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
In this last snippet I also use a User class for getting the data from DataSnapshot. As your application grows, this will be more convenient than constantly calling DataSnapshot.child().
This is covered in the section on reading data in the Firebase documentation.

Related

Retrieving specific data nested under push keys in Firebase Database

Situation: I'm trying to retrieve a string from the key "title" under the first push key (most recent object) inside my Realtime Database, but I keep getting "null".
MainActivity.java
...
mDatabaseReference.limitToFirst(1).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
ExecutiveOrder executiveOrder = snapshot.getValue(ExecutiveOrder.class);
Log.i("MainActivity", "Title: " + executiveOrder.getTitle());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e("Executive Order", "The read failed: " + databaseError.getDetails());
}
});
...
ExecutiveOrder.java
package com.example.cleeg.part;
import com.google.firebase.database.IgnoreExtraProperties;
#IgnoreExtraProperties
public class ExecutiveOrder {
private String mTitle;
private String mDate;
private String mSummary;
private String mText;
// Default constructor
public ExecutiveOrder() {}
public ExecutiveOrder(String title, String date, String text) {
mTitle = title;
mDate = date;
mText = text;
}
public String getTitle() { return mTitle; }
public String getDate() { return mDate; }
public String getSummary() { return mSummary; }
public String getText() { return mText; }
}
UPDATE: The problem was that I didn't have setters in my ExecutiveOrder.java
There are couple of changes to be done. It worked fine to me on very similar DB structure:
mDatabaseReference definition should not include "Executive Branch", because the branch is actually the value to be returned as object
of executiveOrder
I would recommend to change ValueEventListener to ChildEventListener, and update #Override methods accordingly (the names of the methods are slightly different).
I updated you code with needed changes - it should work. Please try. Well... as I can't test it on exact same DB, it may include couple of typos. Apologize if so. But it worked on very similar DB.
mDatabaseReference = mFirebaseDatabase.getReference();
ChildEventListener recentListener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
if (dataSnapshot.getChildrenCount() > 0) {
for (DataSnapshot ds1 : dataSnapshot.getChildren()) {
ExecutiveOrder executiveOrder = ds1.getValue(ExecutiveOrder.class);
String title = executiveOrder.getTitle();
Log.i("MainActivity", "Title: " + title);
}
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
}
};
mDatabaseReference.addChildEventListener(recentListener);
There is a mismatch between variable names of the class and the corresponding database entries. The key in the database has the name "title" whereas you declare it as "mTitle" in your ExecutiveOrder.java class. Therefore, you are getting 'null'. Change the variable names in your ExecutiveOrder.java to match the "key" names exactly in the database and it should work fine.
All the best!!

Firebase orderbychild().equalto() showing null

This is my JSON Structure:
{
"users" : {
"userKey1" : {
"deviceToken" : "deviceTokenID",
"displayName" : "Name here",
"dob" : "28/6/2017",
"email" : "efg#wxy.com",
"gender" : "M"
},
"userKey2" : {
"deviceToken" : "deviceTokenID",
"displayName" : "Name here",
"dob" : "28/1/2017",
"email" : "abc#xyz.com",
"gender" : "M",
}
}
}
In my android Firebase file, I type this:
Query findUser = mDatabase.child("users").orderByChild("email").equalTo("abc#xyz.com");
findUser.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Log.i("findUser","Snapshot: " + dataSnapshot.toString());
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I get the following log:
06-28 22:06:50.190 30962-30962/in.sample.project I/findUser: Snapshot: DataSnapshot { key = users, value = null }
I do not know why I am getting null when cleary I have a child who's email node matches "abc#xyz.com".
You need a foreach loop to get the user in your findUser query because your query contains a collection.
Query findUser = mDatabase.child("users").orderByChild("email").equalTo("abc#xyz.com");
put this part in your eventlistener
....
public Iterable<DataSnapshot> getChildren (){
for (DataSnapshot child : parent.getChildren()) {
....
}
}
Needed to add security rules.
rules: {
"users" : {
".indexOn": "email",
}
}
I guess, that did the trick. Hope it helps someone. :)

Firebase android query with more than one "EqualTo"

This is my Firebase structure:
"Braccianti" : {
"-KehahFy7z2IrUdchwxk" : {
"Associazione" : "-KehahFy7z4ngUdchwxk",
"Cellulare" : "3402659753",
"Cognome" : "Prova",
"DataDiNascita" : "12/04/1985",
"Nome" : "Bracciante"
},
"ashaosdfao" : {
"Associazione" : "gsdfskjdfsdf",
"Cellulare" : 234235246,
"Cognome" : "Example",
"DataDiNascita" : "10/12/2000",
"Nome" : "exam"
}
"dfsdfsdfsdf" : {
"Associazione" : "ewsvbdtgsdgf",
"Cellulare" : 23523975553,
"Cognome" : "Ex",
"DataDiNascita" : "17/01/1994",
"Nome" : "ghjghj"
}
}
I'd like to get "dfsdfsdfsdf" and "-KehahFy7z2IrUdchwxk" with a single query, so i thought about doing like this:
Query QueryAssociazioni = FirebaseDatabase.getInstance().getReference("Aziende/"+main.getNomeAzienda()+"/Associazioni");
QueryAssociazioni = QueryAssociazioni.equalTo("dfsdfsdfsdf").equalTo("-KehahFy7z2IrUdchwxk");
But it doesn't work.
How can i solve my problem?
Firebase doesn't allow multiple queries, but you can always add a ChildEventListener and check if the child's value :
QueryAssociazioni.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
String child = dataSnapshot.getValue().toString();
if(child.equals("dfsdfsdfsdf") || child.equals(("-KehahFy7z2IrUdchwxk"))){
//Do something with the value
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
QueryAssociazioni.child("Braccianti")
.orderByChild("Associazione") //key name
.equalTo("Associazione") //value
Try this way...
Thanks.

Firebase querying data

{
"random_key 1" : {
"id": 0,
"text": "This is text"
},
"random_key 2" : {
"id": 1,
"text": "This is text"
}
}
If I'm storing my data like this, and I want to get the node where id is equal to 0. How can I do that?
The above is the child of issue, which is a child of root.
In your case you would have to setup a Query like this:
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference.child("issue").orderByChild("id").equalTo(0);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
// dataSnapshot is the "issue" node with all children with id 0
for (DataSnapshot issue : dataSnapshot.getChildren()) {
// do something with the individual "issues"
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
#Linxy's answer is correct but since you'll be reading a list of items from the database, it's better to use a child event listener instead of the value event listener.
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference.child("issue").orderByChild("id").equalTo(0);
query.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
//Do something with the individual node here`enter code here`
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
This code works for me
Query query = mFirebaseDatabase.child("issue").orderByChild("id").equalTo(0)
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(final DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
//If email exists then toast shows else store the data on new key
if (!data.getValue(User.class).getEmail().equals(email)) {
mFirebaseDatabase.child(mFirebaseDatabase.push().getKey()).setValue(new User(name, email));
} else {
Toast.makeText(ChatListActivity.this, "E-mail already exists.", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(final DatabaseError databaseError) {
}
});
How I can use this SQL query in firebase?
SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;
For an easy-to-use cross platform integration of Firebase you can also have a look at V-Play Engine for mobile apps
FirebaseDatabase {
id: firebaseDb
Component.onCompleted: {
//use query parameter:
firebaseDb.getValue("public/bigqueryobject", {
orderByKey: true, //order by key before limiting
startAt: "c", //return only keys alphabetically after "c"
endAt: "m", //return only keys alphabetically before "m"
limitToFirst: 5, //return only first 5 sub-keys
})
}
}

How can i get each child? Firebase getValue [android]

How could i get all the childs from my database?
This code get the first Element, how can i get Element_2,3 and successive? The best i accomplised is serialize the first country and print it.
My Database:
{
"Capitals" : {
"Country_1" : {
"Country" : "Macedonia",
"Capital" : "Skopje"
},
"Country_2" : {
"Country" : "Madagascar",
"Capital" : "Antananarivo"
},
"Country_3" : {
"Country" : "Malawi",
"Capital" : "Lilongwe"
}
}
My Code
#Override
public void onStart(){
super.onStart();
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference capitalsRef = database.getReference("Capitals");
compresoresRef.orderByChild("Ref").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
countryModel cm = dataSnapshot.getValue(countryModel.class);
String country = cm.getCountry();
String capital= cm.getCapital();
textData1.setText(country);
textData2.setText(capital);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
The dataSnapshot while executing looks like:
DataSnapshot { key =Country_1, value = {Country=Macedonia, Capital=Skopje} }
You should use an ArrayList for store all childs that you get from Firebase using addChildEventListener
ArrayList<countryModel> countryList = new ArrayList<countryModel)();
compresoresRef.orderByChild("Ref").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
countryModel cm = dataSnapshot.getValue(countryModel.class);
countryList.add(cm);
...
}
}
Or if you use addValueEventListener for retrieve data, it will look like
compresoresRef.addValueEventListener(new ValueEventListener() {
public void onDataChange(DataSnapshot snapshot) {
countryList.clear();
for (DataSnapshot postSnapshot: snapshot.getChildren()) {
countryModel cm = postSnapshot.getValue(countryModel.class);
countryList.add(cm);
}
}
public void onCancelled(FirebaseError firebaseError) {
System.out.println("The read failed: " + firebaseError.getMessage());
}
});
Try this
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
for(DataSnapshot post:dataSnapshot.getChildren())
{
countryModel countryModel cm = post.getValue(countryModel.class);
}
}

Categories

Resources