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

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:`

Related

How to get all of the information in firebase table by using one of the data that is inside the table

I need to get the date and timing data by using the userid (DcEUNNJSB20WhmyL1IsJsk7YnQ1). Can someone guide me on this problem? Thanks in advance.
databaseReference= FirebaseDatabase.getInstance().getReference("appointment");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String userid1 = FirebaseAuth.getInstance().getCurrentUser().getUid();
for(DataSnapshot dataSnapshot1: dataSnapshot.child("appointment").getChildren()){
if(dataSnapshot1.getValue(AppointmentObject.class).getUserid().equals(userid1)){
AppointmentObject thera= dataSnapshot1.getValue(AppointmentObject.class);
a.add(thera);
}
}
adapter=new MyRecyclerviewPAppointment(MainActivityPAppointment.this, a);
rv.setAdapter(adapter);
}
You're looking for a query. In this case, since you're trying to order/filter on a child property, you'll want to use orderByChild(...). Something like:
databaseReference = FirebaseDatabase.getInstance().getReference("appointment").child("qNTrPz0B5hVlafqzRueEbbiUqj1");
Query query = databaseReference.orderByChild("userid").equalTo("DcEUNNJSB20WhmyL1IsJsk7YnQ1");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot childSnapshot: dataSnapshot.getChildren()){
System.out.println(childSnapshot.getKey());
System.out.println(childSnapshot.child("date").getValue(String.class));
}
}
public void onCancelled(#NonNull DatabaseError databaseError) { throw databaseError.toException(); }
}

Multiple Query and Ref Firebase Database Android

My firebase database looks like this:
From this query
String currentUserID = FirebaseAuth
.getInstace()
.getCurrentUser()
.getUid();
DatabaseReference favorsRef = FirebaseDatabase
.getInstance()
.getReference()
.child("favors");
Query myChatsQuery = favorsRef
.orderByChild("uid")
.equalTo(currentUserID);
I need to create other query to get just the tuples from myChatsQuery who has the child called "messages". If the tuple doesn't have the child "messages", I don't want to insert it in my new query.
So, How I can create a query from other query?
Help me please,
Thanks in advance.
Unfortunately, orderByChild() does not work on multiple same fields at once, so you may have to do the job in two steps.
First you can run an orderByChild() query looking for the currentUserId and then add all those that match to an ArrayList and then run orderByChild() in those found uids for messages.
This looks something like this, in code:
reference.orderByChild("uid").equalTo(currentUserId).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists())
array.add(dataSnapshot.getValue(String.class);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
)};
This code above adds uids matching currentUserId to the ArrayList array.
databaseReference.child(array.get(0)).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.child("messages").exists())
// do your thing
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
)};
You can also just use a for loop to go through all the values in the array.
To solve this, please use the following code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRef.child("favors").orderByChild("uid").equalTo(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
if(ds.child("messages").exists()) {
//Do what you need to do
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage());
}
};
query.addListenerForSingleValueEvent(valueEventListener);
As you can see, you can solve this by querying the database only once.

Firebase database query to fetch particular data

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

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