Here member’s key in Group is User’s key.
Task: Want to fetch comida_id froenter code herem User based on Group’s member key.
Here we are trying to first fetch member keys from Group. While fetching member key we also want to fetch User and User’s comida_id while that member’s loop is going. So the scenario will be First we are going to fetch all keys from Group based on Group’s key ( for example createTime, groupName, members ). Now from that we will execute loop on members so will get member’s key. Now while fetching this member’s key in that loop, we want to fetch comida_id from User’s, which will be fetch in that loop only.
GroupKey -> get Data(createTime, groupName, members, restaurants) -> fetch members key and comida_id ( in Loop (get member key then fetch comida_id ))
*My Code
FirebaseDatabase mDatabase_gp = FirebaseDatabase.getInstance();
mDatabase_gp.getReference("Group/"+group_key).addValueEventListener(
new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
Map<String, Object> valuesMap = (HashMap<String, Object>) dataSnapshot.getValue();
Map userkey = (Map) valuesMap.get("members");
Log.d("Members", String.valueOf(userkey));
for (Object ke: userkey.keySet())
{
Log.d("runfirst","First Run");
String key = String.valueOf(ke.toString());
Log.d("Member key",key);
// HERE WHAT CORRESPONDS TO JOIN
FirebaseDatabase User = FirebaseDatabase.getInstance();
User.getReference("User/"+key).addValueEventListener(
new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
Map<String, Object> valuesMap = (HashMap<String, Object>) dataSnapshot.getValue();
String userid = String.valueOf(valuesMap.get("comida_id"));
Log.d("comida_id",userid);
Toast.makeText(ChatSectionActivity.this,userid,Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(DatabaseError databaseError)
{
}
}
);
}
Log.d("runlast","Last Run");
}
#Override
public void onCancelled(DatabaseError databaseError)
{
}
}
);
*
In Above code we tried to achieve same thing but here this code will fetch all member keys from group first. After fetching all members it will fetch comida_ids in another loop.. So there will be like two different loops working to fetch comida_id from members. It’s not working like join query.
GroupKey -> get Data(createTime, groupName, members, restaurants) -> fetch members key (in Loop (get member key) after then fetch comida_id .
*1) I was try this solution - How to perform join query in Firebase?
**But get this error –
Incompatible types.
Required: com.google.firebase.database.DatabaseReference
Found: com.google.firebase.database.ValueEventListener
https://i.stack.imgur.com/ljlWo.png
Firebase doesn't have join queries. And what you are doing wrong is your are referencing your data base on Fireabaseuser, which is wrong.
mdatabaseReference.child("Answer").child("Answer"+QID).orderByChild("questionId").equalTo(QID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (muftiAnswer_List.size() > 0)
muftiAnswer_List.clear();
for (DataSnapshot postsnapshot : dataSnapshot.getChildren()) {
final AnswerClass muftiAnswer = postsnapshot.getValue(AnswerClass.class);
String ide=muftiAnswer.getMuftiId(); //getting AlimId From Class object
Log.e(TAG, "Alim:"+ muftiAnswer.getMuftiId());
//Using Query to get Alim Name From Data Table.!
mdatabaseReference.child("users").child("Alim").child(ide).addListenerForSingleValueEvent(new ValueEventListener() {
#Override //.orderByChild("alimId").equalTo(user_Id)
public void onDataChange(DataSnapshot dataSnapshot) {
Log.e(TAG, "AlimNode:");
for(DataSnapshot postSnapshot:dataSnapshot.getChildren())
{
Log.e(TAG, "EqualNode:");
if(postSnapshot.getKey().equals("alimName"))
{
Log.e(TAG, "AlimNameNodeSnapShot:");
//Setting Alim Name in Current Object replcing id for name
muftiAnswer.setMuftiId(postSnapshot.getValue().toString());
}
// resultMuftiAnswer_List.add(muftiAnswer);
}//End of snapshot
}//ondata Change
#Override
public void onCancelled(DatabaseError databaseError) {
// Failed to read value
Log.w(TAG, "Failed to read value.", databaseError.toException());
}
});//End OF Alim Query
}//end of comments
circular_progress2.setVisibility(View.GONE);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(Details_Activity.this, "LOLOLOL", Toast.LENGTH_SHORT).show();
}
});
You have to use nested loops for doing joins like MYSQL
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) {
}
});
Visit link for better understanding
https://firebase.googleblog.com/2013/10/queries-part-1-common-sql-queries.html
Related
I'm creating simple application with firebase. My firebase database structure is look like this,
user:{
uid:{
name:user1,
age:22,
score:80,
address:mycity,
uid:uid
}
},
contact:{
uid:{
phone:123456
}
}
And this is my database reference code.
mRef = db.getInstance().getReference("user");
mRef.orderByChild("city").equalTo(mycity)
.addValueEventListener(new ValueEventListener {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
HashMap < String, String > hashmap = new HashMap < > ();
hashmap.put("name", snapshot.child("name").getValue());
hashmap.put("score", snapshot.child("score").getValue());
userarr.add(hashmap);
contact = db.getInstance().getReference("contact").child(snapshot.child("uid").getValue());
contact.addValueEventListener(new ValueEventListener {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
contactHashmap.put("phoneNumber", dataSnapshot.child("phone").getValue());
contactarr.add(contactHashmap);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {}
});
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {}
});
}
}
I want to sort data by "score". If I sort it with "Comparator" in client side . Two arraylist data cannot be matched . How to sort data by "score".
Sorry for my bad English speaking.
Edit: I want to get user base on same region(address). And sort them base on "score" .(either ascending or descending)
Try this way
// Sort by score
Query myTopScoreQuery = databaseReference.child("user").child(mycity).orderByChild("score");
myTopScoreQuery.addChildEventListener(new ChildEventListener() {
// TODO: implement the ChildEventListener methods as documented above
// ...
});
Or
// Sort by score
Query myTopScoreQuery = databaseReference.child("user").child(mycity).orderByChild("uid/score");
myTopScoreQuery.addChildEventListener(new ChildEventListener() {
// TODO: implement the ChildEventListener methods as documented above
// ...
});
I have developed an admin side application from where I will be adding the email id, pin, city and country data to the firebase realtime database. Then I will be providing the email and pin to the customer. So my simple target is that when the customer logins, the data of city and country should be displayed on his application. To do this I have to search the database for that particular customer's node which can be done through the email id which he puts during login.
I tried my best but everytime null is returned. Please have a look at my code and help me out.
void searchQuery(String email){
DatabaseReference mFirebaseDatabaseReference = FirebaseDatabase.getInstance().getReference();
Query query = mFirebaseDatabaseReference.child("arvi-admin").orderByChild("mailId").equalTo(email);
query.addValueEventListener(valueEventListener);
}
ValueEventListener valueEventListener = new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
try {
DataModel obj = dataSnapshot.getValue(DataModel.class);
logData(""+obj.getCity()); //the values are null
}catch (Exception e){
Log.d("##","Error");
e.printStackTrace();
}
}
#Override
public void onCancelled(DatabaseError databaseError){
}
};
Firebase Database Image
To solve this, please change the following line of code:
Query query = mFirebaseDatabaseReference.child("arvi-admin").orderByChild("mailId").equalTo(email);
to
Query query = mFirebaseDatabaseReference.orderByChild("mailId").equalTo(email);
As you can see, I have removed the call to .child("arvi-admin") because the root is not a child and should not be added in your reference.
Edit:
Query query = mFirebaseDatabaseReference.orderByChild("mailId").equalTo(email);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
DataModel obj = ds.getValue(DataModel.class);
Log.d(TAG, obj.getCity());
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
query.addListenerForSingleValueEvent(valueEventListener);
I have integrated Google sign-in in my app and i am pushing some data in to fire base including user U-id.I had researched a lot and didn't get anything the problem i am facing that i want to fetch Particular data for eg If User A sign-in and push 5 data and Then User B sign-in and push 3 data.I want a query like if User A sing-in Again it will get his 5 data only and not the data which is pushed by User B.Thanks in Advance :)
By using this it fetch all the data from firebase:
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
FirebaseModel firebasemodel =
data.getValue(FirebaseModel.class);
firebasemodels.add(firebasemodel);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I have tried all that .child .orderby and .equalTo but did'nt work
My Structure is Like:
My FireBase Structure
You also need a reference to the data, which isn't included in your code block. So something along the lines of (this should be before this):
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("notepad-secure/notepad");
Firstly add a user_id key in your child data, it will look like below :
id:"",
note:"",
title:"",
user:""
user_id:"{id from which user have you uploaded data}"
And than you can call below function with specific user data like
below Note : "user_id" = id from which user have you uploaded data
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference.child("notepad").orderByChild("id").equalTo("user_id");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
// dataSnapshot is the "notepad" node with all children with id
for (DataSnapshot notepad: dataSnapshot.getChildren()) {
// do something with the individual "notepad_data"
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
To Fetch Particular values from the firebase,try this code
FirebaseDatabase database;
database.getReference().child("notepad-secure").orderByChild("id").equalTo(user).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() != null) {
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
User userdet =childSnapshot.getValue(yourclass.class);
String note=userdet.note;
//Here you will get the string values what you want to fetch
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
First U have to differentiate.U have to implement Firebase Authentication the u can get Firebase UID of every USER.
String userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
Then store seperatly in new node.
i.e Take Firebase Database Instance and
databaserefernace.child("Data").Child("userID);
When your add a user data to Firebase database, you can add it using the specific uid provided by the FirebaseAuth object like this:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
Assuming you that your database strucure look like this: Firebase root -> notepad-secure -> notepad, to retrieve data, you can use this code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference notepadRef = rootRef.child("notepad-secure").child("notepad").child(uid);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String id = dataSnapshot.child("id").getValue(String.class);
String note = dataSnapshot.child("note").getValue(String.class);
String title = dataSnapshot.child("title").getValue(String.class);
String user = dataSnapshot.child("user").getValue(String.class);
Log.d("TAG", id + " / " + note + " / " + title + " / " + user);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
notepadRef.addListenerForSingleValueEvent(eventListener);
I try to get data from the database.
Code:
mDatabaseUsers = FirebaseDatabase.getInstance().getReference().child("User")mDatabaseUsers.orderByChild("name").startAt("m");
mDatabaseUsers.keepSynced(true); mDatabaseUsers.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Map<String, String> map = dataSnapshot.getValue(Map.class);
String name = map.get("name");
Toast.makeText(AddFriendActivity.this,nick.toString(),Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I want to get all users with the letter m!
How does is work?
Thank you!
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.
So you'll need to loop over the results in dataSnapshot:
mDatabaseUsers.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
System.out.println(userSnapshot.child("name").getValue(String.class));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore errors
}
});
Also see the brief example in the Firebase documentation on using a value event to get a list of results.
So I have a list of objects stored in firebase and want to query for just one object using child equal to method but I am getting a map with single key value instead.
Code below showing what I want to achieve instead of dealing with hashmaps.
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference coutryRef = database.getReference(FireContract.PATH_COUNTRY);
Query countryQuery = coutryRef.orderByChild(FireContract.CHILD_NAME)
.equalTo(TestUtilities.TEST_COUNTRY_ALGERIA).limitToFirst(1);
countryQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Country country = dataSnapshot.getValue(Country.class);
assertEquals(TestUtilities.TEST_COUNTRY_ALGERIA, country.getName());
//get country key
String coutryKey = dataSnapshot.getKey();
}
#Override
public void onCancelled(DatabaseError databaseError) {
fail("Failed to get country: " + databaseError.getMessage());
}
});
When you fire a query, you will always get a list of results. Even when there is only a single item matching the query, the result will be a list of one item.
To handle the list, you can either use a ChildEvenListener or you can loop over the children in your ValueEventListener:
countryQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot countrySnapshot: dataSnapshot.getChildren()) {
Country country = countrySnapshot.getValue(Country.class);
assertEquals(TestUtilities.TEST_COUNTRY_ALGERIA, country.getName());
//get country key
String countryKey = countrySnapshot.getKey();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
fail("Failed to get country: " + databaseError.getMessage());
}
});