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
// ...
});
Related
I want to retrive division and rno from for all key in array and compare those values in array with two other strings. how to do that?
You can get all children. try below code:
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference reference = database.getReference();
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds: dataSnapshot.getChildren()) {
String rno = ds.child("rno").getValue().toString();
String div = ds.child("division").getValue().toString();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I don't understand your question. But you can play on those who fulfill the requirements of the child and fulfill the conditions.
DatabaseReference roomRef = dbRef.child("Everybody Room List Messages");
ValueEventListener roomEventListener = new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dsKey : dataSnapshot.getChildren()) {
for (DataSnapshot dsNick : dsKey.getChildren()) {
if (dsNick.child("nick").getValue().toString().equals(Nick)) {
dsNick.child("image").getRef().setValue("");
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
};
roomRef.addListenerForSingleValueEvent(roomEventListener);
UPDATE
So, if I understand, you need this code:
FirebaseDatabase database = FirebaseDatabase.getInstance();
database.getReference().addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot item: dataSnapshot.getChildren()) {
String snapDiv = item.child("division").getValue().toString();
String snapRno = item.child("rno").getValue().toString();
if(snapDiv.equals(divi) && snapRno.equals(roll)){
//Here you can do everythings you need because division and rno value are those you are searching.
}
}
}
});
I can't understand completly your question.
You need to retrieve for each child his division and rno value. After that you need to compare them with other variables. But in the session these variables are 2 and fixed or you need to compare with a list of pairs?
After that, assuming that the above question will be clarify, if strings are matches, you need to update the value of sub1, sub2,...,sub5 fields?
Please, give us more informations to understand your situation and give you more support.
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.
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
I am trying to query last 5 items and then listen only to new childs. However,
when I add new child, childeventlistener returns the last child from thos 5 i queried earlier.
query = myRef.orderByKey().limitToLast(5);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
// dataSnapshot is the "issue" node with all children with id 0
int oldSize = mData.size();
List<ChatMessageEntity> data = new ArrayList<>();
for (DataSnapshot issue : dataSnapshot.getChildren()) {
// do something with the individual "issues"
ChatMessageEntity chat = issue.getValue(ChatMessageEntity.class);
data.add(0,chat);
}
mData.addAll(data);
adapter.notifyItemRangeInserted(oldSize, mData.size());
}
query.addChildEventListener(newMessageListener);
}
#Override public void onCancelled(DatabaseError databaseError) {
}
});
With this type of scenario you're better off using a ChildEventListener. This has a method onChildAdded that will be called for (up to) five children initially and then for each new child added later.
query = myRef.orderByKey().limitToLast(5);
query.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
ChatMessageEntity chat = issue.getValue(ChatMessageEntity.class);
data.add(0,chat);
adapter.notifyItemInserted(mData.size()-1);
}
...
#Override public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore these
}
});
The above code works, but is missing handling of previousChildName (as children that arrive later might not be added to the end of the list), onChildChanged, onChildMoved and onChildRemoved. Adding handling for all of these is a fun exercise, but quite a bit of work and a bit tricky to get right. If you want to complete the work, I recommend taking a look at the RecyclerViewAdapter in FirebaseUI and its work horse FirebaseArray - which are nicely battle tested.
For more information see the Firebase documentation on listening for child event.
The best i make up is to load required number of items, save key of the newst one. Remove item with that key from list. Create new query which starts from key of the newest and add childEventListener to it.
query = myRef.orderByKey().limitToLast(20);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
// dataSnapshot is the "issue" node with all children with id 0
int oldSize = mData.size();
//List<ChatMessageEntity> data = new ArrayList<>();
for (DataSnapshot issue : dataSnapshot.getChildren()) {
// do something with the individual "issues"
ChatMessageEntity chat = issue.getValue(ChatMessageEntity.class);
chat.key = issue.getKey();
mData.add(chat);
//data.add(0, chat);
}
//mData.addAll(data);
}
Log.e("mcheck", "onDataChange: " + mData.get(0).message);
Query query;
if (mData.size() > 0) {
query = myRef.orderByKey().startAt(mData.get(mData.size() - 1).key);
olderstKey = mData.get(0).key;
mData.remove(mData.size() - 1);
adapter.notifyItemRemoved(mData.size()-1);
adapter.notifyItemRangeInserted(0, mData.size());
//adapter.notifyDataSetChanged();
query.addChildEventListener(newMessageListener);
} else {
myRef.addChildEventListener(newMessageListener);
}
}
#Override public void onCancelled(DatabaseError databaseError) {
}
});
How can I get the
"Dancing in the dark"
from this snapshot if the snapshot does not exist:? I figure it must be saved in the snapshot somewhere. Please read inline code comments..
private void addListenerForSingleValueEvent(String streetAddress, StringBuilder targetAddress){
DatabaseReference firebase = FirebaseDatabase.getInstance().getReference();
firebase.child("catalog/trax").orderByChild("namn").equalTo("Dancing in the dark")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
if (snapshot.exists()) {
// do sowm work on existing data
} else {
// How can I get the "Dancing in the dark" from the snapshot?
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(Application.getInstance(), databaseError.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
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. By listening to a value event you get all matching results in one snapshot, so you have to iterate over the children.
DatabaseReference firebase = FirebaseDatabase.getInstance().getReference();
firebase.child("catalog/trax").orderByChild("namn").equalTo("Dancing in the dark")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot item: snapshot.getChildren()) {
// In this loop item is the snapshot of a single item.
// This means we can get the namm of the item
System.out.println(item.child("namm").getValue(String.class));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(Application.getInstance(), databaseError.getMessage(), Toast.LENGTH_LONG).show();
}
});