Receive numeric data from the Firebase Database - java

I want to display a numerical value for a score in a TextView, but the application always closes.
This is my code
FirebaseDatabase database = FirebaseDatabase.getInstance();
FirebaseUser currentFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference myRef = database.getReference("users").child(currentFirebaseUser.getUid());
// Read from the database
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String valuePoints = dataSnapshot.child("current_points").getValue(String.class);
mTextViewPoints = findViewById(R.id.current_points);
mTextViewPoints.setText(valuePoints);
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
// Log.w(TAG, "Failed to read value.", error.toException());
}
});
}```
Other values that contain letters are numbers he displays, but when it comes only to numbers he closes.
Where am I going wrong?

Dear Vanderclin Rocha,
Initially, the TextView cannot be defined in callback ValueEventListener, you should be defined when the view gets started.
The issue in your code textView return null, you can do debugging and see it.
and this is the current way to get data and set it into TextView.
FirebaseDatabase database = FirebaseDatabase.getInstance();
FirebaseUser currentFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference myRef = database.getReference("users").child(currentFirebaseUser.getUid());
TextView mTextViewPoints = findViewById(R.id.current_points);
// Read from the database
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String valuePoints = dataSnapshot.child("current_points").getValue(String.class);
mTextViewPoints.setText(valuePoints);
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
// Log.w(TAG, "Failed to read value.", error.toException());
}
});
}
I hope this helps you

Related

getvalue() in query return null from Firebase Realtime Database

the databas
setContentView(R.layout.activity_main);
Button readBtn = (Button) findViewById(R.id.readBtn);
EditText testInputTxt = (EditText) findViewById(R.id.testInputTxt);
rootRef = FirebaseDatabase.getInstance().getReference().child("Login");
Query query = rootRef.orderByChild("LoginUserName").equalTo(testInputTxt.getText().toString());
readBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
String passwordUser = snapshot.child("LoginPassword").getValue(String.class);
testInputTxt.setText(passwordUser+"tatata");
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
});
the query works fine it detects that the user is existexists but i wanted to retrieve the value of LoginPassword but it returns null i tried the for DataBase....:snapshot code but it won't detect
Since you are using a Query object, it means that you can potentially get multiple results from the database. That being said, you have to loop through the results using a call to .getChildren() as seen in the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference loginRef = rootRef.child("Login");
Query query = loginRef.orderByChild("LoginUserName").equalTo(testInputTxt.getText().toString());
query.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
for (DataSnapshot ds : task.getResult().getChildren()) {
String passwordUser = ds.child("LoginPassword").getValue(String.class);
testInputTxt.setText(passwordUser+"tatata");
}
} else {
Log.d("TAG", task.getException().getMessage()); //Don't ignore potential errors!
}
}
});
Please also note that if two users have the same "LoginUserName", then your TextView will always display the value of the last one. So always be sure to have unique user names. To check if a user name already exists, please check my answer from the following post:
Checking if a particular value exists in the Firebase database

I want to retrieve a current user's ID from firebase and write it in another node, but it just keeps denying

So basically I made a String mojID which is equal to firebase's current user, I want to pass it as a child in a node but it says it is a null pointer exception and I have already used it in another parts of a code which does not return the fault.
I am attaching some of my code.
final DatabaseReference chatRef1 = FirebaseDatabase.getInstance().getReference("ChatLista");
chatRef1.child(mojID);
chatRef1.child(userID);
chatRef1.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(!dataSnapshot.exists()){
chatRef1.child("id").setValue(userID);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
final DatabaseReference chatRef2 = FirebaseDatabase.getInstance().getReference("ChatLista");
chatRef2.child(userID);
chatRef2.child(mojID);
chatRef2.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(!dataSnapshot.exists()){
chatRef2.child("id").setValue(mojID);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Then there is function that takes the ID:
private void ProvjeriStatus(){
FirebaseUser user = firebaseAuth.getCurrentUser();
if(user!=null){
//user ulogovan
mojID = (String)user.getUid();
}
//ako nije vraca na login
else {
startActivity(new Intent(this,login.class));
finish();
}
}
I even tried casting it as you can see it and it just says I don't need a cast, because it is already a String? Then why does it return null? The only explanation I have come up with is that it is an object not a string and by that .child wants a string as a argument not an object.
You can add UserId via FirebaseUser.. You can refer Below code .. maybe it will help
you
FirebaseUser currentFirebaseUser;
DatabaseReference databaseReference;
currentFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();
databaseReference = FirebaseDatabase.getInstance().getReference();
databaseReference.child("Users").child(currentFirebaseUser.getUid()).child("User
Id").setValue(currentFirebaseUser.getUid());
If you want to retrieve UserId from database Refer Below code..
DatabaseReference myRef = database.getReference("Users");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if ((dataSnapshot.child(currentFirebaseUser.getUid()).child("UserId").getValue() == null)) {
databaseReference.child("Users").child(currentFirebaseUser.getUid())
.child("UserId").setValue(currentFirebaseUser.getUid());
} else {
String Id= (String) dataSnapshot.child(currentFirebaseUser.getUid()).child("UserId").getValue();
}

Android Studio is not reading the retreived data from Firebase realtime database

I am trying to read data from Firebase but it is not read by android studio although I am using the tutorial
I tried to copy the link that is sent by Android Studio to Firebase:
DatabaseReference myRef = database.getReference("USERS").child(uID).child("DeviceID");
textview.setText(myRef.toString());
and past the result in the browser and it shows me the result in firebase but when I try to use it to get data it is not retrieving anything.
here is how I am trying to read it by calling a function:
textview.setText(ReadDeviceId);
''''''''''''''''''''''''''''''''''''
private String ReadDeviceId(){
FBUser = FirebaseAuth.getInstance().getCurrentUser();
uID = FBUser.getUid();
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("USERS").child(uID).child("DeviceID");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
r_deviceID = dataSnapshot.getValue(String.class);
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
r_deviceID = "no userID";
}
});
return r_deviceID;
}
'''''''''''''''''''''''''''''''''''''''''''
Knowing that my firebase database security rule is:
'''''''''''''''''''''''''''''''''
{
"rules": {
".write": "auth != null",
".read": true
}
}
'''''''''''''''''''
but nothing is displayed
you can try this code
private String ReadDeviceId(){
FBUser = FirebaseAuth.getInstance().getCurrentUser();
uID = FBUser.getUid();
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef =
database.getReference("USERS").child(uID).child("DeviceID");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(Datasnapshot snapshot : dataSnapshot.getChildren)
{
//try to map it with your on model class and replace the String with your model class
r_deviceID = snapshot.getValue(String.class)
}
//r_deviceID = dataSnapshot.getValue(String.class);
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
r_deviceID = "no userID";
}
});
return r_deviceID;
}
In your ReadDeviceId() function, you are returning the value of r_deviceID before it is set (event listeners are not synchronous). Therefore, your textview.setText(ReadDeviceId()); will always be textview.setText(null);, which will show nothing.
For your use case, you should change addValueEventListener to addListenerForSingleValueEvent and set the textview's value from within the handler itself like this:
private String ReadDeviceId(){
FBUser = FirebaseAuth.getInstance().getCurrentUser();
uID = FBUser.getUid();
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("USERS").child(uID).child("DeviceID");
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
textview.setText(dataSnapshot.getValue(String.class));
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
textview.setText("no userID");
}
});
}

I cannot just seem to reference the child under User ID from firebase database

I have tried all the ways to reference the child (username) under, UID generated for displaying a string value in text view from Firebase database, but it won't just show up
Database:
DatabaseReference mDatabaseReference = FirebaseDatabase.getInstance().getReference().child("Users").child("uid").child("username");
mDatabaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
String username = Objects.requireNonNull(dataSnapshot.getValue()).toString();
mName.setText(("username" + username ));
} else {
mName.setText(null);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
TextView:
it always goes to the else part, what am I doing wrong?
The child that you are referencing in your code does not exist in the database, that is why it always goes to the else part.
DatabaseReference mDatabaseReference = FirebaseDatabase.getInstance().getReference().child("Users").child("uid").child("username");
In your database, you don't have a child called uid, under the node Users you have different user ids, therefore you need to do the following:
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String userId = user.getUid();
DatabaseReference mDatabaseReference = FirebaseDatabase.getInstance().getReference().child("Users").child(userId).child("username");
This will retrieve the id of the current login user and you will be able to retrieve the Username.

Not getting Child Data back from Firebase in android

Here is the following structure of database in firebase
Code
I am getting the current user and then checking the whether the id is null or not and get reference of child and getting key of child. Further more i am getting null in string variable where i tried to get values.
private void Check_data() {
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user.getUid() != null) {
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("user_info");
DatabaseReference myRef1=myRef.child(user.getUid());
myRef1.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//GenericTypeIndicator<Map<String, String>> genericTypeIndicator = new GenericTypeIndicator<Map<String, String>>() {};
// Map<String, String> map = dataSnapshot.getValue(genericTypeIndicator);
String name = dataSnapshot.child("name").getValue(String.class);
String email = dataSnapshot.child("email").getValue(String.class);
Name.setText(name);
email_txt.setText(email);
/* if (image != null) {
Glide.with(MainActivity.this)
.load(image)
.centerCrop()
.into(photo_url);
}*/
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
In your database, you have random ids that are generated using push()
You should first when adding data to the database use the userid:
FirebaseUser user=FirebaseAuth.getInstance().getCurrentUser();
String userid=user.getUid();
the userid is unique for each user.
then to retrieve the data inside the userid:
DatabaseReference myRef = database.getReference("user_info");
DatabaseReference myRef1=myRef.child(userid);
myRef1.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String name = dataSnapshot.child("name").getValue(String.class);
String email = dataSnapshot.child("email").getValue(String.class)
}
});
When the id has - at the beginning it means its a random id.

Categories