Firebase database query to fetch particular data - java

My Database struckture
This is my database in Firebase and I'm developing an Android application. Now I want to retrieve all the data from "Generated" node where my current user's userid matches the "userId" in data.
I want to know the query in Firebase to fetch that particular data.

Firebase Query firebase query
Read the Firebase Realtime Database Documentation to get some idea firebase realtime database
To Get Current User Uid
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String current_uid = user.getUid(); // user.getUid() will return null if you are not log in
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
Query query = db.child("Leads").child("Generated").orderByChild("userid").equalTo(current_uid);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// do something
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Or Try This One
db.child("Leads").child("Generated").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists())
{
for (DataSnapshot ds: dataSnapshot.getChildren())
{
SomeClass someClass = ds.getValue(SomeClass.class);
if(someClass.getUid().equals("uid")){
// i don't if it is the best practice or not but you can do with this as well
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

To access every item from that reference you will need something like this:
mDatabase.child("Leads").child("Generated").child(uid).addValueEventListener(new ValueEventListener() {
final List<String> lstItems= new ArrayList<String>();
#Override
public void onDataChange(final DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String name = (String) ds.getKey();
String values = (String) ds.getValue();
Log.e("Values",""+values );
lstItems.add(values );
}
PS: you can remove .child(uid) in your reference if you want to get all the children of Generated (it's going to be all the uids).

Related

Android studio : How do I retrieve specific data from Firebase?

private TextView welcomeText;
DatabaseReference databaseReference = database.getReference("Users").child("name");
https://i.stack.imgur.com/Qayc6.png
What I want to do is retrieve the data "name" from the Firebase database and setText for the welcomeText to the data "name".
Try this
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
reference.child("Users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
//model class assign
ModelClass Class = dataSnapshot.getValue(ModelClass.class);
String name = cartClass.getName();
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
Hey I hope you going fantastic. Make sure you have inserted your DB URL from Firebase in your FirebaseDatabase object in your code before coding the query.
So in order your project is ready you need to read the following path: DB > users > UserID > name to reach the value you are looking for. If you want to change 'name' into all of your firebase database registers you should try this.
DatabaseReference reference = FirebaseDatabase.getInstance('FirebaseDBURL').getReference();
reference.child("Users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
//Here you are reading all of your Users objects
if(dataSnapshot.getKey.equals('name')){ //Here we are identifying the attr you want to change by its key name
String text = reference.child("Users").child(datasnapshot.getValue()).getValue(String.class);
yourEditText.setText(text);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
I hope you solve your issue. However here you have such an usefull info:`

How to retrieve json from firebase which has nested child?

I have imported json file to firebase real-time database you can follow the screenshot
https://ibb.co/wyLDPC8 "database structure"
You can do it in this way
DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference();
dbRef.child("categories").addSingleValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
String name = snapshot.child("names").getValue().toString(); // it will give names node string
/// To Fetch Quotes
DataSnapshot quotesSnapshot = snapshot.child("qoutes");
for (DataSnapshot quoteSingleSnpashot : quotesSnapshot.getChildren()) {
String quote = quoteSingleSnpashot.child("quote").getValue().toString(); // it will give names node string
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}

To get data of authenticated user failure

public void loadUserInformation() {
final String uid = mAuth.getCurrentUser().getPhoneNumber();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference().child("Users");
// DatabaseReference uidRef = rootRef.child("ref").child(uid);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot postSnapshot: dataSnapshot.getChildren()){
String name=postSnapshot.child("Name").getValue().toString();
// String email=postSnapshot.child("Email").getValue().toString();
Name.setText(name);
// Email.setText(email);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(getActivity(),"Error Loading UserDetails",Toast.LENGTH_LONG).show();
}
};
rootRef.addListenerForSingleValueEvent(eventListener);
}
I know why I'm not getting the expected results, its because there's one more child after users. I'm not sure on how to access it, child(uid) gave me a NullPointerException. The present code gives me name of some random user. I want it to return name of the authenticated user i.e. myself
Database - http://ibb.co/iRnF77
Change the phone number to the userid:
FirebaseUser user=FirebaseAuth.getInstance().getCurrentUser();
String userid=user.getUid();
So you will have this database:
Users
userid
Name: namehere
Phone_Number: numberhere
//etc
then you can simply retrieve the data of the current user:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference().child("Users").child(userid);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String name=dataSnapshot.child("Name").getValue().toString();
Name.setText(name);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
You don't need the phone number to be the parent node since you already have it as an attribute Phone_Number: number_here, no need to write it twice.
Also getPhoneNumber() can be used if you did phone authentication:
https://firebase.google.com/docs/auth/android/phone-auth

Firebase get the reference of the child of a child

As you see each post has a different Id (the user id who posted) I'm trying to get the reference of this child fx3RqooRMOVRaQHGas4OWQnFK593 for example so the database reference will be like this:
DatabaseReference myRef = FirebaseDatabase.getInstance().getReference().child("Posts").child("fx3RqooRMOVRaQHGas4OWQnFK593");
But what I want is to get that reference dynamically for each post Id.
You have 2 option.
if u want to download one single post then u have to use your custom postId. you can't use pushId(). So that you will know which post u want to download and show.
how to make custom id
FirebaseDatabase.getInstance().getReference().child("Posts")
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
HashMap<String, Object> post = (HashMap<String, Object>) dataSnapshot.getValue();
total= post.size();
}
}
and then create custom id
FirebaseDatabase.getInstance().getReference().child("Posts").child("post"+total).setValue(YourValue);
option 2.
Simply download all post from the post node because u have to ..
FirebaseDatabase.getInstance().getReference().child("Posts")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
//here is your every post
String key = snapshot.getKey();
Object value = snapshot.getValue();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Bonus
if u want to show post of a particular user. (I am assuming that)
u can store the push key inside the user object in a string arrylist. then just call them one by one ...
happy coding :) :)
To achieve this, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference postsRef = rootRef.child("Posts");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String key = ds.getKey();
Log.d("TAG", key);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
postsRef.addListenerForSingleValueEvent(eventListener);
The output will be all those keys.
FirebaseDatabase.getInstance()
.getReference()
.child("Posts")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
String key = snapshot.getKey(); // key here
Object value = snapshot.getValue(); // value here
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

Retrieve all data from Firebase Database

ANDROID: I have a Firebase database like this.
In my app, I would like to compile an arraylist that displays all values from the nameofEntry [DESCRIBED BELOW]. By this I mean the "balso," the "nairboh" and so on.
I have the references:
DatabaseReference root = FirebaseDatabase.getInstance().getReference();
DatabaseReference users = root.child("Users");
DatabaseReference childRef = users.child(userID);
DatabaseReference childRefNameNode = childRef.child(nameOfEntry);
childRefNameNode.child(nameOfEntry).setValue(nameOfEntry);
//FETCH DATA
childRefNameNode.child(nameOfEntry).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String valueFromDB = dataSnapshot.getValue(String.class);
Log.i("Jimit", valueFromDB);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
But this only fetches for one entry. How can I get more entries? [All of them]?
You need to use this code snippet. You haven't used any for loop to step over your children.
EDIT: Also, update your database reference as:
//Updated ref
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Users").child(userID);*
//add listener to updated ref
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//use the for loop here to step over each child and retrieve data
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()){
String valueFromDB = childSnapshot.getValue(String.class);
Log.i("Jimit", valueFromDB);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Do let me know if it changes anything for you.

Categories

Resources