Firebase android, how find data - android

How do I find user data from Firebase database?
This is how my database looks like:
I'm saving my data under tokens:
String token = FirebaseInstanceId.getInstance().getToken();
if (token == null) return;
databaseReference = FirebaseDatabase.getInstance().getReference(token);
I need to find all location coordinates from all users and set up marker, but everything that I made, it's accessing to current user:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference(FirebaseInstanceId.getInstance().getToken());
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child : dataSnapshot.getChildren()){
double allLat = (double) dataSnapshot.child("lat").getValue();
double allLng = (double) dataSnapshot.child("lng").getValue();
mMap.addMarker(new MarkerOptions().position(new LatLng(allLat, allLng)).title("Пользователь"));}
}

DatabaseReference userRef = FirebaseDatabase.getInstance().getReference();
userRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
HashMap<String,Object> hm = (HashMap<String, Object>) dataSnapshot.getValue();
String allLat = String.valueOf(hm.get("lat"));
String allLng = String.valueOf(hm.get("lng"));
Log.e("!_#_#------> ", allLat + " " + allLng);
}
#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) {
}
});

Related

How i can find child in Firebase?

I have a structure of Firebase database:
DB
-User
--UID
----UsersMessages
-------uniqueID
-------textMessage
-------typeOfMessage
Code
private void takeDataFromFirebase(){
Query my_message= mRef.child(USERS_CHILD)
.orderByChild(USER_MESSAGES);
my_message.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String
{
}
#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) {
}
});
}
But I need to get all Messages from my users. How can I get those? How I can search only childs "Messages" without "Users" and take "Message text value". Can I? How I can add this information to ListView?
To get all messages across all users, please use the following code:
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
String uid = firebaseUser.getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference messagesRef = rootRef.child(USERS_CHILD).child(uid).child("Messages");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String messageText = ds.child("MessageText").getValue(String.class);
Log.d("TAG", messageText);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
messagesRef.addListenerForSingleValueEvent(eventListener);
Your output will be:
asasddd
asasddd
asasddd
To get the messages from the users, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("Users");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String userKey = ds.getKey();
DatabaseReference messagesRef = usersRef.child(userKey).child("Messages");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot dSnapshot : dataSnapshot.getChildren()) {
String messageText = dSnapshot.child("MessageText").getValue(String.class);
Log.d("TAG", messageText);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
messagesRef.addListenerForSingleValueEvent(eventListener);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
usersRef.addListenerForSingleValueEvent(valueEventListener);
First, you need to get DatabaseRefence with something like:
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("User/...pathToMessage/Messages");
Then you can load all your messages with a callback:
databaseReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
// callback to get all your messages from user.
if (dataSnapshot == null) return;
MessageModel mess = dataSnapshot.getValue(MessageModel.class);
// display message 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(DatabaseError databaseError) {
}
});

How to get particular value using `DataSnapshot` in `Firebase`

I want to get particular value using from DataSnapshot.
I am attaching the screenshot here so kindly check and help me to get particular value from Realtime Database.
Actually I am implementing chat application in which I want to get value of user from group_list.
Here is my code.
private void loadTotalGroupList() {
referenceMainUrl = FirebaseDatabase.getInstance().getReferenceFromUrl("https://pure-coda-174710.firebaseio.com");
referenceGroupList = referenceMainUrl.child("group_list");
//Check if child is available or not.
referenceGroupList.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
Log.e("dataSnapshot"," ==>"+dataSnapshot);
Map<String, Object> newPost = (Map<String, Object>) dataSnapshot.getValue();
Log.e("newPost"," ==>"+newPost);
Log.e("user: ","==>" + newPost.get("user")); // Here I am getting null value
} else {
Log.e("Child not found", " >>>");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
and log showing like this. DataSnapshot { key = group_list, value = {First Group={-KtBH9gnTszNxcXjNu9A={message=assaasas, user=sakib}}} }
I have resolved my issue by using addChildEventListener
referenceGroupList.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String prevChildKey) {
Log.e("dataSnapshot KEY", " ==>" + dataSnapshot.getKey());
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String prevChildKey) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String prevChildKey) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Here dataSnapshot.getKey() returns all sub child of it.
You're listening to the location /group_list in your code. That means a a snapshot from that location will contain the following:
/First Group
/-KtBH9gnTszNxcXjNu9A
message = "..."
user = "..."
If you want to get the user value from that location, you'll have to dig into it using each intermediate path:
dataSnapshot.child("First Group").child("-KtBH9gnTszNxcXjNu9A").child("user").getValue()
Or more simply:
dataSnapshot.child("First Group"/-KtBH9gnTszNxcXjNu9A/user").getValue()
You can't skip the middle paths in the snapshot. Alternatively, you may want to listen to a location closer to the value you want:
referenceMainUrl.child("group_list/First Group/-KtBH9gnTszNxcXjNu9A");
This code runs in a loop and gives you values for all the 'user's
DatabaseReference dRef = FirebaseDatabase.getInstance().getReference().child("group_list").child("First_Group");
dRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
String userName = snapshot.child("user").getValue(String.class);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

Get Last Item in nested database firebase android

This is my data structure:
Here I want to retrieve the Latitude and Longitude of the last item of Location child based on the id = "sd".
Here's the code:
Query query = mDatabase.child("Users").orderByChild("Id").equalTo(busId);
// busId = "sd"
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot user : dataSnapshot.getChildren()) {
Query lastItem = user.getRef().child("Location").orderByKey().limitToLast(1);
lastItem.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String lat = dataSnapshot.child("Latitude").getValue().toString();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
break;
}
}
How can I do that? Thanks
Please use this code for Android:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userRef = rootRef.child("Users");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String Id = ds.child("Id").getValue(String.class);
if(Id.equals("sd")) {
Query q = ds.child("Location").getRef().orderByKey().limitToLast(1);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot child : dataSnapshot.getChildren()) {
Double latitude = child.child("Latitude").getValue(Double.class);
Double longitude = child.child("Longitude").getValue(Double.class);
Log.d("TAG", latitude + " / " + longitude);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
q.addListenerForSingleValueEvent(valueEventListener);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
userRef.addListenerForSingleValueEvent(eventListener);

Firebase get all key

HI everyone I want to catch all the keys on my firebase database:
Users-
26dfg678-
Name: jack
Job: Farmer
43jkhjh4-
Name: bill
Job: ICT
I want to catch the id: 26dfg678 and 43jkhjh4 and put them in an array. This is my code:
final DatabaseReference database_nomi = firebaseDatabase.getReference().child("Users");
database_nomi.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
//here
**name[0] = dataSnapshot.getKey();
Provee.setText(name[0]);**
}
#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) {
}
});
if i do this it takes only the last but i want all..
To do this you need to read through your Firebase snapshot using a ValueEventListener (and addListenerForSingleValueEvent).
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
int i = 0;
for(DataSnapshot d : dataSnapshot.getChildren()) {
name[i] = d.getKey();
i++;
}
}
}//onDataChange
#Override
public void onCancelled(DatabaseError error) {
}//onCancelled
});
This code uses a foreach to read all dataSnapshot children, saving its key in an array at each iteration.

How to fetch the username list in listview in Android from Firebase database?

I have registered and saved users through my app and now I want to fetch the list of usernames as shown below from Firebase database. How do I do it in list view? my database is shown below:
ArrayList<MODELCLASSNAME> Users=new ArrayList<>();
DatabaseReference df=FirebaseDatabase.getInstance().getReference().child("users");
df.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapShot user : dataSnapshot.getchildren()){
Users.add(dataSnapshot.getValue(MODELCLASSNAME.class));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
//Now loop through your arraylist
get your database reference
firebaseDatabase = FirebaseDatabase.getInstance();
mPostDb = firebaseDatabase.getReference("User");
Now query your table
Query query = mPostDb.orderByKey();
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapShot user : dataSnapshot){
// Do what ever you whatever you want with this user object
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Try this method:
public void retrieveNames() {
Query myQuery = mDatabase.orderByChild("name").equalTo("INSERT-HERE-A-NAME-FOR-YOUR-SEARCH");
myQuery.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Iterator iterator = dataSnapshot.getChildren().iterator();
//FOR YOUR DATA STRUCTURE -
while (iterator.hasNext()) {
String image_uri = (String) ((DataSnapshot) iterator.next()).getValue();
String name = (String) ((DataSnapshot) iterator.next()).getValue();
String username = (String) ((DataSnapshot) iterator.next()).getValue();
YourUserObject User = new YourUserObject (image_uri, name, username);
YourArrayList.add(User);
}
YourAdapter.notifyDataSetChanged();
}
#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) {
}
});
}

Categories

Resources