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

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");
}
});
}

Related

Unable to read data from Firebase Realtime database

Just trying to get url the url that I have stored in that node. It is a audio file url that I have stored in the storage.
ValueEventListener changeListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
String change = snapshot.getValue(String.class);
if(snapshot.hasChildren()){
if(snapshot.hasChild("song")){
String song_url = (String) snapshot.child("song").getValue();
Log.d("tansen","[SUCCESS] url: "+song_url);
}
else{
Log.d("tansen","[FAILURE] snapshot.hasChild()");
}
}
else{
Log.d("tansen","[FAILURE] snapshot.hasChildren()");
}
}
#Override
public void onCancelled(DatabaseError error) {
}
};
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference dbRef = database.getReference("/tansen-37eb3-default-rtdb/song");
dbRef.addValueEventListener(changeListener);

Receive numeric data from the Firebase Database

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

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();
}

Getting different String from snapshot.getKey(); and mAuth.getUid(); Without .push();

String I am getting from snapshot.getKey(); is different from any other String, although I am not doing push() if i virtually compare the values of my mAuth.getUid(); string and snapshot.getKey(); they both are same, but programmatically it is not showing.
I tried concatinating my snapshot.getKey(); string in textView.setText(snapshot.getKey();); also but nothing is shown in the screen.
Please note I am not posting my whole Fragment code.
In the code below the if statement is not getting true value.
FirebaseUser mAuth = FirebaseAuth.getInstance().getCurrentUser();
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference databaseReference = database.getReference();
DatabaseReference userref = databaseReference.child("Votes").child("Chat");
final HashMap<String, String> hash = new HashMap<>();
likeButton = (ImageView) view.findViewById(R.id.heartImage);
likeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
hash.put("chatVoteLike", "Yes, I would like it");
userref.child(mAuth.getUid()).setValue(hash);
likeButton.setImageResource(R.drawable.red_heart);
}
});
userref.orderByKey().addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
String uID = snapshot.getKey();
Log.i("uId from", "firebase ---" + uID);
if (uID == mAuth.getUid()){
likeButton.setImageResource(R.drawable.red_heart);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
The problem is Solved using using uID.equals(mAuth.getUid()) instead of uID == mAuth.getUid()

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