Not getting Child Data back from Firebase in android - java

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.

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

Reading the value of a child without knowing the value key

I want to get a specific data value (it is circled in green) that was previously pushed. But when I run this code it also displays the key.
This is the Structure
The class in which I push the data:
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String uid = user.getEmail();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");
reference.child(user.getUid()).child("Distance").push().setValue(LastValueRounded);
reference.child(user.getUid()).child("Speed").push().setValue(averagespeed);
reference.child(user.getUid()).child("Time").push().setValue(getTimerText());
The class where I'm supposed to read the data:
mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
String uid = user.getEmail();
DatabaseReference reference =
FirebaseDatabase.getInstance()
.getReference("Users");
reference.orderByChild("email")
.equalTo(uid)
.addValueEventListener(
new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
if (snapshot.child("Distance").getValue() != null) {
String distance1 = snapshot.child("Distance").getValue().toString();
String speed1 = snapshot.child("Speed").getValue().toString();
String time1 = snapshot.child("Time").getValue().toString();
distance.setText(distance1);
speed.setText(speed1);
time.setText(time1);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.w("ERROR", "onCancelled", databaseError.toException());
}
});
The displayed data
I suspect your "getValue()" returns a Map object. You may want to try:
String distance1 = (String)(snapshot.child("Distance").getValue().get("MJw...9") );
When you are using the following reference:
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");
reference.orderByChild("email")
.equalTo(uid)
.addValueEventListener(/* ... /*);
It means that you are trying to get all children under the "Users" node where the "email" field holds the value of the UID of the authenticated users, but this is not correct since under the "Users" node there are no such children. To be able to get only the values that correspond to those pushed elements, please use the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("Users").child(uid);
uidRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
DataSnapshot snapshot = task.getResult();
for (DataSnapshot distanceSnapshot : snapshot.child("Distance").getChildren()) {
distance.setText(distanceSnapshot.getValue(String.class));
}
for (DataSnapshot speedSnapshot : snapshot.child("Speed").getChildren()) {
speed.setText(speedSnapshot.getValue(String.class));
}
for (DataSnapshot timeSnapshot : snapshot.child("Time").getChildren()) {
time.setText(timeSnapshot.getValue(String.class));
}
} else {
Log.d("TAG", task.getException().getMessage()); //Don't ignore potential errors!
}
}
});

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.

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

Categories