Comparing data from Firebase - java

Hi guys well I'm getting a null and i dont know why.. i'll apreciate if u can help me.
this is my json on Firebase.
usuarios{
krum{
dni: "43193622"
email: "pedroccc"
login: "krum"
nombre:"pedro"
pass: "1234" }
and this is my method:
login_text = (EditText) findViewById(R.id.txtLogin);
onClickListener:
final String log_child = login_text.getText().toString();
final String pass_child = pass_text.getText().toString();
mDatabase = FirebaseDatabase.getInstance().getReference("usuarios").child(log_child);
mDatabase.child("pass").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String mpass = dataSnapshot.getValue(String.class);
pass = mpass;
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
then i compare pass with pass_child with equals and i getting that pass is null.. any idea? thank you
PD. In Firebase all settings are true

Try this:
final String log_child = login_text.getText().toString();
final String pass_child = pass_text.getText().toString();
mDatabase = FirebaseDatabase.getInstance().getReference("usuarios").child(log_child);
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot data : dataSnapshot.getChildren()){
String mpass = data.getValue().toString();
pass = mpass;
if(pass.equals(pass_child)){
//code here
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Adding the for loop will enable you to get the pass from the database. Since onDatachange is asynchronous(means it does not wait until it finishes retrieving data, and it goes to other methods after it, then when it retrieves the data it comes back to the method onDatachange) then you have to compare inside the method onDatachange

Related

Get values only from second request

I have a problem i get value from Firebase, but the email only fills up after activity run second time.
private ArrayList<String> currentList = new ArrayList<>();
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("userTable").child(user.getUid()).child("Container");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childDataSnapshot : dataSnapshot.getChildren()) {
String string = childDataSnapshot.getKey();
currentList.add(string);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
//Toast.makeText(getContext(), currentList.size(),
// Toast.LENGTH_LONG).show();
String size = String.valueOf(listCurrent.size());
firstNameOfCurrentList.setText(size);
First time size = 0;
Second time = 3(true result);
update UI after getting response.hope now it will work fine for you
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childDataSnapshot : dataSnapshot.getChildren()) {
String string = childDataSnapshot.getKey();
currentList.add(string);
}
//Toast.makeText(getContext(), currentList.size(),
// Toast.LENGTH_LONG).show();
String size = String.valueOf(listCurrent.size());
firstNameOfCurrentList.setText(size);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Firebase listener is async, which means it will run in the background and not stop the code until you recieve a response.
In your code you don't wait for the value to be returned from the server, that why size=0.
what you need to do is check the size inside the listener and after the for loop :
for (DataSnapshot childDataSnapshot : dataSnapshot.getChildren()) {
String string = childDataSnapshot.getKey();
currentList.add(string);
}
String size = String.valueOf(listCurrent.size());
firstNameOfCurrentList.setText(size);
This way you will wait for the value to be returned from firebase and then get the list size.

SingleValueEventListener do not get the value after button click

I need to get nickname value from Firebase Real time database after button is clicked. So i made singleValueListner() in button´s onClick method. But it don´t work.
I have tried debug it, but code didn´t get into singleValueEventListener()
Button getName = (Button)findViewById(R.id.getName);
getName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatabaseReference db = FirebaseDatabase.getInstance().getReference().child("Member").child(user.getUid());
db.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
TextView tv = (TextView)findViewById(R.id.tv);
tv.setText(data.child("nickname").getValue().toString());
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
});
Database JSON structure:
{
"Member" : {
"1Zuv6VZZ0kPluwc33f1QQQ7DZD93" /* UID */ : {
"-LgIHwiAjfuh5pjK7wzl" : {
"actualScore" : 0,
"bestScore" : 0,
"email" : "some#email.com",
"nickname" : "Vitek",
"season" : 0
}
}
}
}
Database structure:
https://drive.google.com/file/d/15B4b6Rb_WAiS6fioI9gItyijrbDiVjzJ/view
I need to get nickname, I think this is writen good, but not. So, what is wrong?
To get the value of your nickname property, please use the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("Member").child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String nickname = dataSnapshot.child("nickname").getValue(String.class);
Log.d(TAG, nickname);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
uidRef.addListenerForSingleValueEvent(valueEventListener);
The output in your logcat will be:
Vitek
So there is no need to loop through the DataSnapshot object in order to get the value of your nickname property. If you don't get this result, please check the logcat to see if you have an error message printed out.
You are only referring up to user's id but there is also a parent key of user detail which you need to reference.
tv.setText(data.child("LgiH------").child("nickname").getValue().toString());
but try to remove that second key from your registering user's code because it is not helpful.
You have made a mistake in refering your firebase root node. just change your line as below :
DatabaseReference db = FirebaseDatabase.getInstance().getReference("Member");
Now,just call your singlevalue event.
db.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
TextView tv = (TextView)findViewById(R.id.tv);
tv.setText(data.child("nickname").getValue().toString());
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
This will do your stuff. try debugging your code with log at step by step.

Getting Data from Firebase realtime database, Android Studio, Java

I am looking for a way to get data from the firebase real-time database in a format like an array[] or a String.
My database looks like this:
Link to image of database
Or:
Database
|
-->Users
|
-->UID1
-->UID2
This is at the root of the database
I want to get a list of all of the UIDs in the "Users" child.
This is the code I have so far and am a bit stuck on:
DatabaseReference databaseReference = firebaseDatabase.getReference("Users");
databaseReference.addValueEventListener(
new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String UIDs = dataSnapshot.getValue(String.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I am a bit of a rookie as it comes to java, android studio, and firebase. I am trying to get the data in a format I know how to use like a String or an Array[] of Strings. I looked around if other people had maybe asked the same question, but I could get the answers to those questions to work/didn't understand them.
Thanks in advance for your time!
To get the a list of uids, 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) {
List<String> list = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String uid = ds.getKey();
list.add(uid);
}
//Do what you need to do with your list
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
usersRef.addListenerForSingleValueEvent(valueEventListener);
I recommend you to use the list only inside the callback otherwise it will be empty. If you want to use it outside the onDataChange() method, I recommend you see the last part of my anwser from this post in which I have explained how it can be done using a custom callback. You can also take a look at this video for a better understanding.
For your above question I will give both ways: ArrayList or String with delimiters
ArrayList<String> uids = new ArrayList<String>();
FirebaseDatabase.getInstance().getReference("Users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()) {
uids.add(snapshot.getKey());
}
}
}
#Override
public void onCancelled(DatabaseError error) {
}
});
For String
String uids = "";
FirebaseDatabase.getInstance().getReference("Users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()) {
uids += snapshot.getKey() + ",";
}
}
}
#Override
public void onCancelled(DatabaseError error) {
}
});
This gives an output such as: uid1,uid2,uid3,.....uidn,
You can try this:
DatabaseReference ref=
FirebaseDatabase.getInstance().getReference("Users");
ref.addValueEventListener(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
});
name[] is an array of strings!

Firebase realtime database - how to get parent name based on a value of one of its keys

The structure looks like this:
users
|----username1
|----uid:value
username2
|----uid:value
I'm trying to find the best way to get the username value based of the value of it's uid,
This need to be in Java code (Android), So far I found the following code:
Query uid = reference.child("users").orderByChild("uid").equalTo(uid);
uid.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
String keys=datas.getKey();
if (keys.equals(uid)) {
// uid found
} else {
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Try this code and create a model class to fetch value of Uid
DatabaseReference users= FirebaseDatabase.getInstance().getReference().child("users");
users.orderByChild("uid").equalTo(uid).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot post:dataSnapshot.getChildren()){
//Use a model class to fetch user id like below
UIDDetails u=post.getValue(UIDDetails.class);
String user_id=u.getUid();
//Here all values will be equal to youy required uid if exists more than one
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Please add below code into your file:
DatabaseReference users= FirebaseDatabase.getInstance().getReference().child("users");
final Query userQuery = users.orderByChild("uid");
userQuery.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
map.clear();
if(child.getkey().toString().equalsIgnoreCase(uid)){
//Get the node from the datasnapshot
String myParentNode = dataSnapshot.getKey();
for (DataSnapshot child: dataSnapshot.getChildren())
{
String key = child.getKey().toString();
String value = child.getValue().toString();
map.put(key,value);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
databaseError.toException();
}
});

Firebase keeps changing the value and adding new child

I am trying to load data from firebase database and then I want to add some more data to it and in the end I want it to upload back. But the problem is when the data is being uploaded back it is not stopping after updating the data. It looks like it is under loop and doing the task again and again.
mTempDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.hasChild(mAuth.getCurrentUser().getUid())){
final DatabaseReference newTemp = mTempDatabase.child(mAuth.getCurrentUser().getUid());
final long qntCount = (long) dataSnapshot.child(mAuth.getCurrentUser().getUid()).child("QuantityCount").getValue();
final long foodamount = (long) dataSnapshot.child(mAuth.getCurrentUser().getUid()).child("QuantityCount").getValue();
//final long countfood = (long) dataSnapshot.child(mAuth.getCurrentUser().getUid()).child("QuantityCount").getValue();
mDatabaseBestseller.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String foodname = (String) dataSnapshot.child(food_key).child("foodname").getValue();
long foodprice = (long) dataSnapshot.child(food_key).child("foodprice").getValue();
long mfoodprice = foodprice + foodamount;
long mqntCOunt = qntCount +1;
newTemp.child("QuantityCount").setValue(mqntCOunt);
newTemp.child("FoodPrice1").setValue(mfoodprice);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mTempDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(!dataSnapshot.hasChild(mAuth.getCurrentUser().getUid())) {
final DatabaseReference newTemp = mTempDatabase.child(mAuth.getCurrentUser().getUid());
mDatabaseBestseller.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String foodname = (String) dataSnapshot.child(food_key).child("foodname").getValue();
long foodprice = (long) dataSnapshot.child(food_key).child("foodprice").getValue();
newTemp.child("QuantityCount").setValue(1);
newTemp.child("CountFood1").setValue(1);
newTemp.child("Food1").setValue(foodname);
newTemp.child("FoodPrice1").setValue(foodprice);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
viewHolder.mFoodAddLayout.setVisibility(View.INVISIBLE);
viewHolder.mIncrLayout.setVisibility(View.VISIBLE);
}
});
According to my understanding I have did wrong math while retrieving the data and adding the data back.
addValueEventListener() will always listening to database reference value changes.if you want to stop listening you have to use removeEventListener(valueListener),
But addListenerForSingleValueEvent() executes onDataChange method immediately and after executing that method once, it stops listening to value changes.
You need to use the .addListenerForSingleValueEvent() instead of .addValueEventListener(). The difference is, the second one keep updating every time a value is changed in the database, which keep happening as you update your value inside the function. But, the first method that I am suggesting, just read the values once, which is what you need here.

Categories