Unable to read data from Firebase Realtime database - java

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

Related

How to retrieve the push id value

In this code I need to save the data in firebase database as (Registration Data1 then UID then push id)
btn3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
String uid = firebaseUser.getUid();
databaseReference = FirebaseDatabase.getInstance().getReference().child("Registration
Data1").child(uid).push();
String sp1 = spinner.getSelectedItem().toString();
String sp2 = spinner2.getSelectedItem().toString();
String sp3 = spinner3.getSelectedItem().toString();
Data DBdata = new Data(sp1,sp2,sp3,uid);
databaseReference.setValue(DBdata);
//Toast.makeText(this,"Data Added",Toast.LENGTH_SHORT).show();'''
And in this code I need to retrieve the data in recyclerview
databaseReference = FirebaseDatabase.getInstance().getReference().child("Registration Data1");
mDBListener = databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot teacherSnapshot : dataSnapshot.getChildren()) {
Data DB = teacherSnapshot.getValue(Data.class);
DB.setKey(teacherSnapshot.getKey());
mTeachers.add(DB);
}
mAdapter.notifyDataSetChanged();
mProgressBar.setVisibility(View.GONE);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(Public.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
mProgressBar.setVisibility(View.INVISIBLE);
}
});
The question is how to retrieve the data under push id without make .child(UID)?

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

How to retrieve all data from Android Firebase database databaseRef->userID->uniqueKey

This is the Firebase database:
ExchangeItemsData: -> reference
lhmuj6n3g6Su1rv7XJLq5tV62yr2 -> userId
-LQQ7scByWcswW2VIPM5 -> UniqueKey inserted by .push().getKey();
// below is the data under the uniquekey
exchangeProductName:
"Pen"
imageUrl:
"https://firebasestoragse.googleapdfis.codfm/v04df/b/dbin..."
phoneNo:
5465464
productDesc:
"Used"
productName:
"GelPen"
userID:
"lhmuj6n3g6Su1rv7XJLq5tV62yr2"
I need to show all data of every user in this ExchangeItemsData reference. I've tried many ways but i failed. If anyone can help me out here it would be so nice of you.
Thanks in advance.
To get all those values that belong to all users, please use the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = rootRef.child("ExchangeItemsData");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot dSnapshot : dataSnapshot.getChildren()) {
for(DataSnapshot ds : dSnapshot.getChildren()) {
String imageUrl = ds.child("imageUrl").getValue(String.class);
String phoneNo = ds.child("phoneNo").getValue(String.class);
String productDesc = ds.child("productDesc").getValue(String.class);
String productName = ds.child("productName").getValue(String.class);
String userID = ds.child("userID").getValue(String.class);
Log.d(TAG, productName);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage());
}
};
ref.addListenerForSingleValueEvent(valueEventListener);
The output in the logcat will be all the product names of all products of all users.
Try this code to retrieve values from your database
public class Demo extends Activity{
FirebaseAuth mAuth;
String currentUId;
DatabaseReference usersDb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
mAuth=FirebaseAuth.getInstance();
currentUId=mAuth.getUid();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("ExchangeItemsData");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists() && dataSnapshot.hasChildren()){
for (DataSnapshot userId : dataSnapshot.getChildren()) {
if(!userId.getKey().equals(currentUId)) {
usersDb.child(userId).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot1) {
if(dataSnapshot1.hasChildren()){
for (DataSnapshot userKey : dataSnapshot1.getChildren()) {
String exchangeProductName = dataSnapshot1.child(userKey).child("exchangeProductName").getValue().toString();
String imageUrl = dataSnapshot1.child(userKey).child("imageUrl").getValue().toString();
String phoneNo = dataSnapshot1.child(userKey).child("phoneNo").getValue().toString();
String productDesc = dataSnapshot1.child(userKey).child("productDesc").getValue().toString();
String productName = dataSnapshot1.child(userKey).child("productName").getValue().toString();
String userID = dataSnapshot1.child(userKey).child("userID").getValue().toString();
//From here do whatever you want to do with those values
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
}
}
}
}
}

How to retrieve value from firebase without getting the unique key

I am trying to retrieve an url from Firebase in Android. However, my problem is that I can't retrieve the url without also getting the unique key of the child.
The value I am trying to retrieve is the following:
Down below is the code I use to retrieve the data from firebase.
final FirebaseDatabase database = FirebaseDatabase.getInstance();
myRef = database.getReference().child("LoadItems");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot child : dataSnapshot.getChildren() ){
String key;
key = child.getKey();
Log.d(TAG, "onDataChange: " + key);
Log.d(TAG, "onDataChange: " + child.getValue());
}
}
#Override
public void onCancelled(DatabaseError databaseError) { }
});
So what I am trying to get is what the url alone.
There is no need to know any key in order to get that URL. So please use the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference shoesRef = rootRef.child("LoadItems").child("Shoes");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String url = ds.getValue(String.class);
Log.d(TAG, url);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
shoesRef.addListenerForSingleValueEvent(valueEventListener);

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