Android Firebase Retrieving data as a list from multiple nods - android

I am using firebase realtime database in my first android app. I'm trying to retrieve data from firebase as an arraylist of "username" but i'm constantly having the Query returning a null result. i'm very new to firebase so i'm really struggling with data retrieval errors.
"Marchand" : {
"Taha" : {
"adress" : "58 avenu St Eugène ",
"blockage" : false,
"latitude" : 35.7498635,
"longitude" : -0.5566705,
"mail" : "mailmail#gmail.com ",
"password" : "123456",
"signalement" : 0,
"telephone" : "0666666666",
"username" : "Taha"
},
"Yasmine" : {
"adress" : "Address kkdndbdk ",
"blockage" : false,
"latitude" : 35.7498636,
"longitude" : -0.5566704,
"mail" : "randommail#gmail.com",
"password" : "bobo",
"signalement" : 0,
"telephone" : "06999999",
"username" : "Yasmine"
}
.
.
.
This is one of my attempts, i tried to use the order-by-child method to iterate through the multiple nods that i have but i'm sure that it's not the right way to do this, this gives me null poiter exceptions because the datasnapshot is returning a NULL value :
referenceMarchand = rootNode.getReference("Marchand");
final ArrayList<String> types = new ArrayList<>();
Query users = referenceMarchand.orderByChild("username");
users.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
types.add(dataSnapshot.child("username").toString());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});

lets make use of some functions of firebase, Lets see it works for you.
part 1)
we will save it another way around
"Merchant" : {"Name" : "Taha"
"ID" :"-KSMCMCMnnkd"},//Firebase generated id
{"Name" : "Yasmine"
"ID" :"-KSMCMccccnkd"},//Firebase generated Id
...........
Part 2)
And Save the Details
"Details" : {
"ID" : "-KSMCMCMnnkd" //Firebase generated id
"adress" : "58 avenu St Eugène ",
"blockage" : false,
"latitude" : 35.7498635,
"longitude" : -0.5566705,
"mail" : "mailmail#gmail.com ",
"password" : "123456",
"signalement" : 0,
"telephone" : "0666666666",
"username" : "Taha"},
{
"ID":"-KSMCMccccnkd" //Firebase generated id
"adress" : "Address kkdndbdk ",
"blockage" : false,
"latitude" : 35.7498636,
"longitude" : -0.5566704,
"mail" : "randommail#gmail.com",
"password" : "bobo",
"signalement" : 0,
"telephone" : "06999999",
"username" : "Yasmine"}
In Part 1)
DatabaseRefrence ref = FirebaseDatabase.getInstance("/Path");
String id = ref.child("Merchant").push().getKey(); //Firebase generated id
Merchant merchant = new Merchant();
merchant.setId(id);
merchant.setName("SomeName");
ref.child("Merchant").child(id).setValue(merchant);
Part 2)
Detail detail = new Detail();
detail.setAddress("Some Address");
detail.setBlockage("false");
detail.setLatitude("SomeValue");
detail.setEmail("someText#gmail.com");
......
ref.child("Details").child(id).setValue(detail);
Now
List<Merchant> merchants = new ArrayList<>();
List<Detail> details = new ArrayList<>();
ref.child("Merchant").addValueEventListener(new ValueEventListener(){
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(Datasnapshot snapshot:dataSnapshot){
Merchant merchant = snapshot.getValue(Merchant.class);
merchants.add(merchant);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
ref.child("Details").addValueEventListener(new ValueEventListener(){
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(Datasnapshot snapshot:dataSnapshot){
Detail detail = snapshot.getValue(Detail.class);
details.add(detail);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Now you can get the details for some merchant or save it in local database for later querying.

Related

Is there any query to retrieve the data present in list firebase android

I want to retrieve only that post where postCategory matches the user interest.
How can I achieve this type of query. Any Help??
Below is my json file of database..
"Posts" : {
"-MAKobGjdhMfJFwZ1kol" : {
"postCategory" : "Animals",
"postDesc" : "still",
"postImage" : "Image Link",
"postPersonName" : "Name",
"postPersonUid" : "CLQA22uZpLS1ErIrnoBTrC3xqBw2",
"postTitle" : "ek"
},
"Users" : {
"CLQA22uZpLS1ErIrnoBTrC3xqBw2" : {
"email" : "email",
"interest" : {
"-MA14zFcNfs1JAjux129" : {
"name" : "Developer"
},
"-MA14zFgzhL-MOBB7D6h" : {
"name" : "Shopping"
}
},
"name" : "Name",
"uid" : "CLQA22uZpLS1ErIrnoBTrC3xqBw2"
}
In firebase database you cannot have such queries.
You should use Firestore (https://firebase.google.com/docs/firestore) for such advanced queries.
firestore/query-data
firestore
To get all posts with postCategory equal to Animals, you'd do:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Posts");
Query query = ref.orderBy("postCategory").equalTo("Animals");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
Log.i(TAG, postSnapshot.getKey()+": "+postSnapshot.child("postTitle").getValue(String.class));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
}
If you want to retrieve posts for multiple categories, you'll have to perform a separate query for each of those and merge the results on your client.
I'd also recommend changing how you store the categories for a user. The idiomatic way is:
"Users" : {
"CLQA22uZpLS1ErIrnoBTrC3xqBw2" : {
"email" : "email",
"interest" : {
"Developer": true,
"Shopping": true
}
},
The reasons this is more common is that it automatically ensures that each value can occur only once in the interest object, since property names are by definition unique.

It is possible to retrieve in such a way data from Firebase?

I would like to know how can I retrieve the key of this object based on the object content. I'm using a realtime firebase database.
JSON code :
"Places" : {
"-M11-OIIHbKTVqCJ-Swv" : {
"name" : "Farmacia Pagani Dr. Roberto",
"others" : {
"Abilify" : 100,
"Acetaminophen" : 120,
"Acyclovir" : 140,
"Adderall" : 160
}
},
"-M11-OJJCGAPdJUknLXX" : {
"name" : "FARMACIA DR. TUMIATTI MARIANO",
"others" : {
"Abilify" : 100,
"Acetaminophen" : 120,
"Acyclovir" : 140,
"Adderall" : 160
}
}
I want to retrieve M11-OIIHbKTVqCJ-Swv if I have the name : Farmacia Pagani Dr. Roberto"
The code I wrote :
mUserDatabase = FirebaseDatabase.getInstance().getReference("Places");
Query query = mUserDatabase.orderByChild("name").equalTo(nameOfThePharmacy);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
System.out.println("The key is : "+dataSnapshot.getKey());
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
This code doesn't work, it returns : "Places" but I want the key of the object that contains the field name that equals with = ad example Farmacia Pagani Dr. Roberto , the output should be : -M11-OIIHbKTVqCJ-Swv

Firebase nested ValueEventListener

I have the following database structure -
{
"linking" : {
"shift-assign" : { // for every shift its assigned users
"key1" : {
"111" : true,
"222" : true
},
"key2" : {
"111" : true
}
},
"user-assign" : { // for every user its assigned shifts
"111" : {
"key1" : true,
"key2" : true
},
"222" : {
"key1" : true
}
}
},
"shifts" : {
"20191117" : {
"key1" : {
"endTime" : "00:00",
"numOfEmps" : 3,
"startTime" : "00:00",
"wage" : 0
},
"key2" : {
"endTime" : "00:00",
"numOfEmps" : 1,
"startTime" : "00:00",
"wage" : 0
}
}
},
"users" : {
"111" : {
"id" : "111",
"password" : "111"
},
"222" : {
"id" : "222",
"password" : "222"
},
"99999" : {
"id" : "99999",
"password" : "123",
}
}
}
Where a user can be assigned to several shifts and a shift can contain several users.
I'm currently trying to fetch all of the users assigned to a certain shift.
So the idea was attaching a ValueEventListener to linking/shift-assign/{shift-key}, run a loop and for every user-key , reference users/{user-key} and attach an inner ValueEventListener to read user object and add it to a userList.
Something like this :
mDatabase.child("linking/shift-assign").child(shiftKey)
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
for(DataSnapshot ds : dataSnapshot.getChildren()){
mDatabase.child("users").child(ds.getKey())
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot2) {
mUser user = dataSnapshot2.getValue(mUser.class);
userList.add(user);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {}
});
}
adapter = new UsersAssignedAdapter(UsersAssignedActivity.this, userList);
lv.setAdapter(adapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {}
});
I debugged it and noticed that the for loop is finished before the inner ValueEventListener is called, which is why I'm getting an empty list in my adapter. I'm guessing this is due to its asynchronous behavior.
So my question is - is there any way I can query all user ids and for each one perform another query?

Firebase Iterate through entire database

I am trying to receive all the data from a firebase database, so I can place it into a Users class however I do not know how I will iterate through the entire database as I cannot interger (the i variable in the for loop) insert values into the child field.
My code is this:
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists())
{
String fullname = (String) dataSnapshot.child(userId).child("Fullname").getValue();
String country = (String) dataSnapshot.child(userId).child("Country").getValue();
String profilePicture = (String) dataSnapshot.child(userId).child("ProfilePicture").getValue();
String username = (String) dataSnapshot.child(userId).child("Username").getValue();
Toast.makeText(getApplicationContext(), "Testing with: " + fullname + country + profilePicture + username, Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), "Count : (4) - " + dataSnapshot.getChildrenCount(), Toast.LENGTH_SHORT).show();
showProfiles(dataSnapshot);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Database:
{
"Users" : {
"4PdlTlv3qjZ3BmDvrJyUut9Fnq43" : {
"Country" : "xx",
"Fullname" : "hh",
"ProfilePicture" : "htm/o/Images%2FSearchAdapter%2F4PdlTlv3qjZ3BmDvrJyUut9Fnq43%2FProfilePicture%2FProfilePic_2019.03.06.10.47.54.jpg.jpg?alt=media&token=b647708e-c6d5-4b45-bef0-3dc40301b73a",
"Username" : "hmack001"
},
"COg4r4io9hezhFpmK3adPucUXA93" : {
"Country" : "spain",
"Fullname" : "nat",
"ProfilePicture" : "hcom/o/Images%2FSearchAdapter%2FCOg4r4io9hezhFpmK3adPucUXA93%2FProfilePicture%2FProfilePic_2019.03.06.19.14.17.jpg.jpg?alt=media&token=8620b321-5cef-42f0-a828-dbb7c37c8e7d",
"Username" : "nat"
},
"Tw1xRxViygNsLqrQiaaMAvAduIu1" : {
"Country" : "uk",
"Fullname" : "harvey\n",
"ProfilePicture" : "t.com/o/Images%2FUsers%2FTw1xRxViygNsLqrQiaaMAvAduIu1%2FProfilePicture%2FProfilePic_2019.03.03.05.26.35.jpg.jpg?alt=media&token=c290e75a-5f92-4271-bcb5-c644fe1b14ef",
"Username" : "RGB"
},
"vOxr1RoDqgWogKK1lp9pfpTHc6w2" : {
"Country" : "scotland ",
"Fullname" : "greg greg",
"ProfilePicture" : "ot.com/o/Images%2FSearchAdapter%2FvOxr1RoDqgWogKK1lp9pfpTHc6w2%2FProfilePicture%2FProfilePic_2019.03.04.12.30.22.jpg.jpg?alt=media&token=27b024cf-0691-4121-8a27-26acf101ebc2",
"Username" : "greg"
},
"xecUOPeyMcQaQrgkU9ouDgK90Ai1" : {
"Country" : "ggh",
"Fullname" : "Da apply ",
"ProfilePicture" : "2FProfilePic_2019.03.03.04.58.50.jpg.jpg?alt=media&token=f35854c2-3ff9-4d18-9f7a-10c13f066c68",
"Username" : "gg"
}
}
}
I am aware that there is no attempt in this code to retrieve information from all the users fields, I do not understand the logic behind iterating through the database as I dont see where I can do Item 1, Item 2 etc.
Use this
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
System.out.println(childSnapshot.getKey());
System.out.println(childSnapshot.child("Country").getValue(String.class));
}

What is construction of Json DB for Android Firebase Realtime Database?

I uploaded such json to firebase console of realtime database. And to get some "words" im trying get child "words" with orderByChild ... startAt and so on...
Someone on this forum told me there is no any child in "words". Whats wrong?
{
"words" : {
"1" : {
"id" : 1,
"lang1" : "s1",
"lang2" : "d1",
"type" : "a"
} ,
"2" : {
"id" : 2,
"lang1" : "s2",
"lang2" : "d2",
"type" : "a"
} // ...
}
}
And my Java code:
Query fb = FirebaseDatabase
.getInstance()
.getReference()
.child("words")
.orderByChild("lang1")
.startAt("s2")
.limitToFirst(20);
BTW. I can not get any responce. This listener does not return anything.
fb.add... ValueEventListener() {
... void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
Word w = singleSnapshot.getValue(Word.class);
Log.i(TAG, new Gson().toJson(w));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "onCancelled", databaseError.toException());
}
});

Categories

Resources