Android studio - get collection from user in firebase using java - java

I'm trying to get the "bet" collection from the firebase database (on android studio, using java).
this is the collection
pic1
pic2
,I got User class that has the fields
"full_name","email","password".
what should i do with the "bet" collection?
I tried
reference = FirebaseDatabase.getInstance().getReference().child("Users");
db = FirebaseFirestore.getInstance();
db.collection("Users").document(UserID).get().addOnCompleteListener(task ->{
if(task.isSuccessful() && task.getResult() != null){
String number_bet = task.getResult().getString("bet");
}
} );
It failed and i couldn't find any solutions
,I can access the other fields, for example
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
User user1 = snapshot.getValue(User.class);
if(user1 != null){
user_submit.setText(user1.bet_display);
}
}
all that i need is to get the drawn number (0-36) value(in that case String)
thanks!

that worked for me.
DatabaseReference reference=FirebaseDatabase.getInstance().getReference().child("Users");
reference.child(UserID).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
String str2 = snapshot.child("bet").child(""+NUMBER).getValue().toString(); }
}
#Override
public void onCancelled(#NonNull DatabaseError error) { }
});
NUMBER is the path, it drawn every time..
just got to the right path by snapshot.child(some key).child(some key)....getValue().toString()

Related

How to make two Firebase database calls one inside the other Java Android

I want to make two database calls one inside the other and make use of the first call data. Since firebase database calls are asynchronous this is not behaving the way I want.
I HAVE two database nodes Users, Chats.
I want first query through one Users at a time and take the user id and then query through the Chats model and check if the id in Users and Chats nodes are same
Something like this.
database.getReference().child("Users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
list.clear();
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
users = dataSnapshot.getValue(Users.class);
users.setUserId(dataSnapshot.getKey());
database.getReference().child("Chats").child(auth.getUid() + users.getUserId()).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(snapshot.exists()){
//ADD USER TO LIST UPDATE UI
list.add(users);
}
else{
//DON'T ADD USER
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
Hope I made the problem clear.

How to retrieve data from Firebase when data didn't change

I'm quite confused with listeners and Firebase. I understand that the only way to retrieve data from Firebase is listeners. I'm using addListenerForSingleValueEvent to retrieve the username value, which it works well only when that value changes or when I execute this code for a second time. Username value shouldn't change at all but I still need to read it often. How do you read from FB when no changes had occurred?
FirebaseAuth mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("forum")
.child("level1exercice1").child("post").child("username");
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
value = snapshot.getValue(String.class);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
Have you tried reading it as a snapshot and then storing it as a cookie for future use?
The following code is from Firebase Docs:
FirebaseDatabase.DefaultInstance
.GetReference("Leaders").OrderByChild("score").LimitToLast(1)
.ValueChanged += HandleValueChanged;
}
void HandleValueChanged(object sender, ValueChangedEventArgs args) {
if (args.DatabaseError != null) {
Debug.LogError(args.DatabaseError.Message);
return;
} // Do something with the data in args.Snapshot
}

Android Firebase database limitToLast(1) weird behaviour

I have a very simple code:
// get users poll date, and set in relevant text view
Query query = gameRef.child("users_loto").child("zaalkIb4W0V7MGbekLhqjP34IQi1").orderByChild("pollRank").limitToLast(1);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
nDate = Long.parseLong(ds.child("pollRank").getValue().toString().substring(0, 14));
user_result.setText(String.valueOf(nDate));
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
};
query.addListenerForSingleValueEvent(valueEventListener);
I ordered it by pollRank - it is the same number as the child name.
It seems to return the last value of the relevant node:
But instead, it always returns the one before :
A very weird behavior...
Any thoughts about why it happens?
Tnx for #ShehanWisumperuma!
gameRef.keepSynced(true) was the correct answer to my issue!!!
Tnx for all of you who tried to help me!

How can I read values from Firebase Realtime Database by using a Java method in AndroidStudio?

My Firebase Realtime Database has been built by loading an object of the Java class HashMap. In my Android Studio app I'm trying to write a method that takes a String (the key) as input, searches through the database and if the string is found it returns the associated Float (the value), otherwise it returns 0. How can I do this? Any help would be really appreciated!
EDIT: I've tried to follow the suggestions, adapting them to my particular case, but I didn't manage to solve the problem yet.
I wrote the following code in MainActivity:
DatabaseReference myRef;
Float tempValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
myRef = FirebaseDatabase.getInstance().getReference("myRoot");
tempValue=0f;
...
}
public void retrieveValueFromDatabase(String childName, final MainActivity activity){
myRef.child(childName).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Float value=dataSnapshot.getValue(Float.class);
if (value==null){
value=0f;
}
activity.tempValue=value;
//First Toast
//Toast.makeText(activity,"tempValue = "+tempValue.toString(), Toast.LENGTH_LONG).show();
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
}
public void useValues(){
retrieveValueFromDatabase(childName,this);
//Second Toast
//Toast.makeText(this,"tempValue = "+tempValue.toString(), Toast.LENGTH_LONG).show();
//code using tempValue from here
...
}
If I uncomment the first toast, the correct value inside tempValue is shown, but if I uncomment the second toast, the value of tempValue shown is the default one (0.0). What am I missing?
You need to use addValueEventListener to retrieve data from the database:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("myRoot").orderByChild("name").equalTo("peter");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.i("Database", dataSnapshot.child("floatValue").getValue(Long.class));
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
})
Here, you add a reference to the root node, then query using equalTo() to check if name = peter exists in the database and return the float value.
You should read the guide:
https://firebase.google.com/docs/database/android/read-and-write

Android firebase no data query

Im using the Android SDK for firebase database.
In the database I have a structure where I keep the messages ordered by user, that way if I need their messages I just query by user.
myDatabase -> messages -> JonDoe
-> "You forgot your mail"
-> "Buy groceries"
-> JaneDoe
-> "Dog's birthday!"
The problem is if the user doesnt exist the listener keeps waiting forever, and I want to show "You have no messages" in that case. (For example, if I query the user "CharlesDoe" in the example above)
Is there a way to check if a reference exists before/after/during a query?
try this:
DatabaseReference root =FirebaseDatabase.getInstance().getReference();
DatabaseReference user = root.child("myDatabase").child("messages");
user.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
if (snapshot.child("CharlesDoe").exists()) {
// run some code
}else{
Toast.makeText(this,"no messages",Toast.Length_LONG).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Here it will query on node messages and then it will check if the child exists and do the required.
Try this on
DatabaseReference root =FirebaseDatabase.getInstance().getReference();
DatabaseReference user =
root.child("myDatabase").child("messages").child("CharlesDoe");
user.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
if (snapshot.exists()) {
// run some code
}else{
Toast.makeText(this,"no messages",Toast.Length_LONG).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

Categories

Resources