Retrieve a single entry from firebase - java

Below is my firebase data.
users
a81b0dec-671e-4840-9977-e932274928fb
email: "s#s.com"
screenname: "SSS"
totalmoney: "0"
uid: "a81b0dec-671e-4840-9977-e932274928fb"
c934beeb-51d2-4919-bff0-64153abff1dd
email: "p#p.com"
screenname: "PPP"
totalmoney: "0"
uid: "c934beeb-51d2-4919-bff0-64153abff1dd"
e0187af9-20a9-4088-a86c-7fb8cf3b4d47
email: "o#o.com"
screenname: "OOO"
totalmoney: "0"
uid: "e0187af9-20a9-4088-a86c-7fb8cf3b4d47"
How can I retrieve the node with uid = "a81b0dec-671e-4840-9977-e932274928fb".
Here's what I have tried so far, but it's not working.
String uid = "a81b0dec-671e-4840-9977-e932274928fb";
Query query = fb.orderByChild("uid").equalTo(uid);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot data) {
// TODO Auto-generated method stub
Log.i("SINGLE VALUE EVENT", data.toString());
}
#Override
public void onCancelled(FirebaseError error) {
// TODO Auto-generated method stub
}
});

Your current code executes a query. Since a query can match multiple child nodes, it returns a list of values. Even when there is only one matching result, it returns a list of one.
You can handle this in your code by iterating through the children:
public void onDataChange(DataSnapshot data) {
for (DataSnapshot userSnap: data.getChildren) {
Log.i("SINGLE VALUE EVENT", userSnap.child("email").getValue(String.class));
}
}
But in this case you don't even need a query, since you've (wisely) also stored the users under their uid. That means you can directly access the user by that uid, which saves some code and will be faster:
String uid = "a81b0dec-671e-4840-9977-e932274928fb";
DatabaseReference user = fb.child(uid);
user.addListenerForSingleValueEvent(new ValueEventListener() {
public void onDataChange(DataSnapshot data) {
Log.i("SINGLE VALUE EVENT", data.child("email").getValue(String.class));
}
public void onCancelled(FirebaseError error) {
Log.e(TAG, error);
}
});

You shouldn't duplicate the id, instead use:
ref.orderByKey().equalTo()
You can find what you are searching for there:
https://www.firebase.com/docs/android/guide/retrieving-data.html

To make your code more dynamic..you could declare a string for getting the uid values
EditText edt = (EditText)findViewById(R.id.editText);
String edtText = edt.getText().toString().trim();
String uid = edtText;
DatabaseReference db = fb.child(uid);
db.addListenerForSingleValueEvent(new ValueEventListener() {
public void onDataChange(DataSnapshot snapshot) {
Toast.makeText(this, "Email for supplied user is : " + snapshot.child("email").getValue(String.class), Toast.LENGTH_SHORT).show();
}
public void onCancelled(FirebaseError error) {
Toast.makeText(this,"Error as a result of " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
});

If you know for sure that you're expecting only one entry (in this case since every record has a unique id), using psudo code I'd say, retrieve the 0 index of returned data.

Related

How to check if user entered userid already exists in the firebase through java?

I've tried so many ways to check if a user id is already in the firebase but all method are in vain.
Below is my code to check if user id exists but whatever data I enter it does not show the required error.
userid = findViewById(R.id.userid);
String userVal = userid.getEditText(). getText().toString();
boolean userquery = FirebaseDatabase.getInstance().getReference().child("user").orderByChild("userid").equals(userVal);
if(userquery) {
userid.setError("This user name already exists");
return;
}
Whenever I try to add existing value in the input it accepts the value and overwrites in the database.
Here is the screenshot of my firebase database.
Your code so far only sets up a query. It doesn't actually execute the query, so there's no way it can detect whether the data exists. To execute a query, you have to attach a listener to it.
So in your case, that could be something like:
boolean userquery = FirebaseDatabase.getInstance().getReference().child("user").orderByChild("userid").equals(userVal);
userquery.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (!task.isSuccessful()) {
Log.e("firebase", "Error getting data", task.getException());
}
else if (task.getResult().exists()) {
userid.setError("This user name already exists");
}
}
});
On older SDK versions the equivalent would be:
boolean userquery = FirebaseDatabase.getInstance().getReference().child("user").orderByChild("userid").equals(userVal);
userquery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
userid.setError("This user name already exists");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
}

Cannot get reference to my auto generated push IDs in android

I am making an android app through android studio in java language. I have linked it to firebase Realtime database. There are auto generated push IDs as the last child. I want to retrieve my database values back in an activity. I am facing problem in giving reference to the push IDs.
This is what I have tried.
myRef = myfire.getReference().child("Data").child(strUID).child("Traffic").child("Wedding");
final String uid =myRef.getKey();
myRef.child(uid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() == null) {
Toast.makeText(getApplicationContext(),"Data Not Available",Toast.LENGTH_LONG).show();
} else {
String stData1 = (Objects.requireNonNull(dataSnapshot.child("stData1").getValue())).toString();
String stData2 = (Objects.requireNonNull(dataSnapshot.child("stData2").getValue())).toString();
String stData3 = (Objects.requireNonNull(dataSnapshot.child("stData3").getValue())).toString();
String stData4 = (Objects.requireNonNull(dataSnapshot.child("stData4").getValue())).toString();
category basic = new category(stData1,stData2,stData3,stData4);
tvBalance.setText(stData4);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
Please provide a practical example.
Edit
This is my database structure:------------
Data>>
user id>>>>
Traffic>>>>
Wedding>>>>
Auto ID>>>
>stData1
>stData2
>stData3
>stData4 //I want to get this last value//
my json file
{
"Data" : {
"UyhzVqsz1BVFKoePa2NEmlPFu382" : {
"Traffic" : {
"Wedding" : {
"-MYKeSN8GZ8WbI-8TfVB" : {
"stData1" : "15 Apr 2021,06:43:00:pm",
"stData2" : "Wedding",
"stData3" : "kkk",
"stData4" : "100"
}
}
}
}
}
}
The only ways to get a node is by either knowing its full path, or by knowing the path to the parent node, and then some unique value under the node. Neither seems to be the case for the stData4 in your JSON, so you'll have to load the entire Wedding node and then loop over the results to get the part you want.
This isn't too bad though:
myRef = myfire.getReference("Data").child(strUID).child("Traffic/Wedding");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (!dataSnapshot.exists()) {
Toast.makeText(getApplicationContext(),"Data Not Available",Toast.LENGTH_LONG).show();
} else {
for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
String stData1 = childSnapshot.child("stData1").getValue(String.class);
String stData2 = childSnapshot.child("stData2").getValue(String.class);
String stData3 = childSnapshot.child("stData3").getValue(String.class);
String stData4 = childSnapshot.child("stData4").getValue(String.class);
}
category basic = new category(stData1,stData2,stData3,stData4);
tvBalance.setText(stData4);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
The code above assumes that:
strUID has the value UyhzVqsz1BVFKoePa2NEmlPFu382

Creating Specific Child While Messages Are Retrieving Android Studio

I am trying to make a message section in my app.
Model Description:
You can ignore DUYURU, it isn't related with topic.
child of DUYURU means author's uid.
Number represents messages unique index.
Model
My java-android code:
mRef = FirebaseDatabase.getInstance().getReference("Tests").child("DUYURU");
mRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
posts.clear();
for (DataSnapshot userMessages:snapshot.getChildren()) {
//These 2 values become null since childs are not exist
String sender = userMessages.child("sender").getValue(String.class);
String photoUri = userMessages.child("photoUri").getValue(String.class);
String uid = userMessages.getKey();
for (DataSnapshot dataSnapshot: userMessages.getChildren()) {
Post post = dataSnapshot.getValue(Post.class);
post.setPostInfo(sender,photoUri,uid);
post.setIndex(Integer.parseInt(dataSnapshot.getKey()));
posts.add(post);
}
}
Collections.sort(posts,Collections.<Post>reverseOrder());
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Log.e(TAG, "onCancelled: ",error.toException() );
}
});
Then sender's value becomes null since there is no child called sender.
So how can i create a child if not exists while messages are retrieving.
//checking if object is not exist in for loop
if (!userMessages.hasChild("sender")) {
mRef.child(userMessages.getKey()).child("sender").setValue("sendername");
}

Retrieve String from Realtime Firebase Database

I am trying to retrieve a string from the database but everytime I try it shows an error which says "Failed to convert value of type java.util.HashMap to String" a guy on Stackoverflow had my same problem, ii followed the answer that helped him but it's still not working for me
I tried to map the code as an hashmap but it keeps showing me error
This is the model
public ButtonInformationSend(String testoNotifica) {
TestoNotifica = testoNotifica;
}
public String getTestoNotifica() {
return TestoNotifica;
}
public void setTestoNotifica(String TestoNotifica) {
this.TestoNotifica = TestoNotifica;
}
and this is the code
myRef.addValueEventListener(new ValueEventListener() {
#Override public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
ButtonInformationSend buttonInformationSend = dataSnapshot.getValue(ButtonInformationSend.class);
creaNotifica(buttonInformationSend);
}
#Override public void onCancelled(#NonNull DatabaseError databaseError) {}
});
the error i get is this Failed to convert value of type java.util.HashMap to String
If you have this database:
Users
id
name : peter
Then the variable myRef should be referencing the node id to be able to retrieve a String, if myRef is referencing the root node then you would get the error:
Failed to convert value of type java.util.HashMap to String
Therefore you should do the following:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Users");
ref.child(id).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String name = dataSnapshot.child("name").getValue(String.class);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
In Java, you cannot directly convert a Hashmap to a string as they are two different types.
DataSnaphhot.getValue()
returns a hashmap of all the data found at your reference, if your reference points to a node of data in the database. What you need to do is get the hashmap from the data snapshot and then get the relevant data needed from that hashmap, Here is an example of that:
HashMap<String, Object> data = (HashMap<String,Object>) dataSnapshot.getValue();
try {
String value1 = (String) data.get("Value1");
String value2 = (String) data.get("Value2");
String value3 = (String) data.get("Value3");
} catch (Exception e) {
e.printStackTrace();
}
Hope this helps.

Understanding if data exists in Firebase

I am using the following to fetch a username from Firebase. But in this case, how do I get to know, if the username exists or not.
Firebase firebaseRef = new Firebase("<Firebasae_URL>/Users");
Query query=firebaseRef.orderByChild("username").equalTo("username");
So in your case the code should be like this, to find an username exists in your database.
Firebase firebaseRef = new Firebase("<Firebasae_URL>/Users").child("username");
firebaseRef.addListenerForSingleValueEvent(new ValueEventListener) {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
// User Exists
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
The solution I found to check if a query return value was
let docRef = db.collection('videos').select('id').where('id','==',quoteData.id);
docRef.get().then(function(doc){
if(doc.size > 0){
// return value
}
else{
// no return value
}
})

Categories