I have a firebase database with the next structure:
PPostdb-e1e1d
Datos
USERID
name
mail
USERID
Post
PostTITLE
PostTITLE
text
I'm developing an app for publish simple post, before I added the option to publish a post, I was getting the user's data and showing it in an activity using the nex code:
mFirebaseDatabase = FirebaseDatabase.getInstance();
myRef = mFirebaseDatabase.getReference();
...
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
showPersonalData(dataSnapshot);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
private void showPersonalData(DataSnapshot dataSnapshot) {
FirebaseUser user = firebaseAuth.getCurrentUser();
userID=user.getUid().toString();
for(DataSnapshot ds : dataSnapshot.getChildren()){
UserInformation uInfo = new UserInformation();
uInfo.setNAME(ds.child(userID).getValue(UserInformation.class).getNAME());
uInfo.setMAIL(ds.child(userID).getValue(UserInformation.class).getMAIL());
name.setText(uInfo.getNAME());
mail.setText(uInfo.getMAIL());
}
But now when someone publish a post, I can't get the user's data and show it in my activity for that information, when I try to open that activity, it stop working.
How can I solve that problem? I think is an error in the Reference, but I can't solve it.
Related
I am trying to retrieve a list of friends for a user so I can display them in a list view. The friends and user info is structured like this in my firebase database:
So basically, I want to take the user ids listed in the friends part and query my users data to get all the info under every node that is in that set of user ids. How can I achieve this using the android firebase database sdk querying? I would like to be able to retrieve all the users in a single database query.
Thanks.
You cannot get that data in single query, you need to query your database twice. This is a common practice when it comes to Firebase. Assuming that friends and users nodes are direct childs of your Firebase root, to achieve this, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference friendIdRef = rootRef.child("friends").child(friendId)
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String key = ds.getKey();
DatabaseReference usersRef = rootRef.child("users").child(key);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot dSnapshot : dataSnapshot.getChildren()) {
String username = dSnapshot.child("username").getValue(String.class);
Log.d("TAG", username);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
usersRef.addListenerForSingleValueEvent(eventListener);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
friendIdRef.addListenerForSingleValueEvent(valueEventListener);
It will print all user names of those particular users. One more thing to note, is that you don't need to add in your database those friends that have the value of false, only those with the value of true.
I have stored data into the firebase real time database, but unable to retrieve a set of data from the database.. below i have attached a pic which shows the skeleton of my firebase database
Tell me how i will retrieve status data from database..
Sorry i changed my database structure like below..
Database Structure
After clicking the status
Assuming that the screen-shot is coorect and the structure is Firebase-root -> messages -> status, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference statusRef = rootRef.child("status");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String status = ds.getValue(String.class);
Log.d("TAG", status);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
statusRef.addListenerForSingleValueEvent(eventListener);
I need to delete a user from the group chat once he clicks the exit group button. The above picture is how my database looks like
Suppose I want to delete the user with user_id: 15213
Here's my code:
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference groupMemberRef = database.getReference().child("group_users/"+chatGroup.group_id+"/"+userId);
groupMemberRef.removeValue();
While the code is technically correct, the entry isn't getting removed from the database.
I have never tried deleting a node the way you implemented. But I did as below:
DatabaseReference groupMemberRef = database.getReference().child("group_users/"+chatGroup.group_id+"/"+userId);
groupMemberRef.setValue(null);
See if it works..
To solve this, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRef.child("group_users/" + chatGroup.group_id).orderByChild("user_id").equalsTo(15213);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
ds.getRef().removeValue();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {}
};
query.addListenerForSingleValueEvent(valueEventListener);
I've been trying to retrieve an element from my Firebase database using its key. I have a class User and users are present in database.
I want to retrieve an object user using its key with this method :
public User getConnectedUserByUId(final String uid){
DatabaseReference database = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = database.child("users");
final List<User> connectedUser= new ArrayList<User>();
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot item: dataSnapshot.getChildren()) {
if (item.getKey()==uid)
{
User user= dataSnapshot.getValue(User.class);
connectedUser.add(user);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return connectedUser.get(0);
}
but it returns an empty list every time.
The issue is here:
if (item.getKey()==uid)
since you are comparing 2 String in java you have to use the method
string.equals(Object other) not the == operator.
Moreover, since you know the key of the data in Firebase you can use it to get the reference without cycling all children.
Something like:
DatabaseReference database = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = database.child("users").child(uid);
Here you try to check a very specific ID only on changed data. Instead, try using a Firebase Query with filterByKey and not using your own function to achieve that. Here's sample code that I would use to try to replace your function:
DatabaseReference database = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = database.child("users");
Query connectedUser = ref.equalTo(uid);
connectedUser.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
// TODO: handle the post here
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
// ...
}
});
As specified in the Firebase documentation here: https://firebase.google.com/docs/database/android/lists-of-data#filtering_data
in the line : User user= dataSnapshot.getValue(User.class);
you have to put : User user= item.getValue(User.class);
and you have to check the id after you get the user:
if (user.getKey()==uid){
connectedUser.add(user);
}
There are 2 mistakes and a minor issue:
you are using == to compare two String objects. In java, this is true only if they are the same reference. Use equals instead.
addValueEventListener only adds a listener that gets invoked once after you add it and then every time something changes in the value you are listening to: this is an asynchronous behaviour. You are trying to get data synchronously instead. Please read something about this.
you are fetching useless data: you only need an object but you are fetching tons of them. Please consider to use the closest reference you can to the data you are fetching.
So, in conclusion, here's some code. I'd like to point out right now that forcing synchronous acquisition of naturaly asynchronous data is a bad practice. Nevertheless, here's a solution:
public User getConnectedUserByUId(final String uid){
DatabaseReference database = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = database.child("users").child(uid);
Semaphore sem = new Semaphore(0);
User[] array = new User[1];
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot item: dataSnapshot.getChildren()) {
if (item.getKey()==uid)
{
User user= dataSnapshot.getValue(User.class);
array[0] = user;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
try
{
sem.tryAcquire(10, TimeUnit.SECONDS);
}
catch (Exception ignored)
{
}
return array[0];
}
EDIT: I've just seen that this post is very old. I'm not sure how I ended up here.
I am begginer in Firebase and my problem is:
I have to get one user id of any of the recently added users but the user can't be the current user.
Until now I have done this but it isnt working.
DatabaseReference databaseusers = FirebaseDatabase.getInstance().getReference().child("Users");
Query query=databaseusers.limitToLast(50);
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
if(!snapshot.getValue().toString().equals(currentuseruid)){
player2uid=snapshot.getValue().toString();
}
}
Use getKey() to get a node's key
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
if (!snapshot.getKey().equals(currentuseruid)) {
player2uid = snapshot.getKey();
}
}
Hope this helps :)