Access all child values of a snapshot in firebase - java

This is my Firebase Realtime Database.
I want to read memberRollNo , and memberMobileNo of the node whose name(key) is equal to nname. I am only able to read memberRollNo with my code and Textview for memberMobileNo shows out to be blank.
DBRef = FirebaseDatabase.getInstance().getReference();
DBRef.child("Members").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String roll = dataSnapshot.child(nname).child("memberRollNo").getValue(String.class);
DRollNo.setText(roll);
String mob = dataSnapshot.child(nname).child("memberMobile").getValue(String.class);
DMobile.setText(mob);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
DRollNo and DMobile are textview.

Change this:
String mob = dataSnapshot.child(nname).child("memberMobile").getValue(String.class);
into this:
String mob = dataSnapshot.child(nname).child("memberPhone").getValue(String.class);
In your database, you do not have a child called memberMobile. The name inside the method child() needs to be the same as in the database to be able to retrieve it.

Related

Retrieve data from FireBase database in android, java by searchin with an ID

I tried to implement a code in java to retrieve data from database( firebase) by searching with an ID and show it in the form.
In here i have already saved some data and now when i type the id, it need to show the data of the id in this same form.
btnShow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
searchID = txtid.getText().toString().trim();
DatabaseReference readRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference dref = readRef.child("Student");
Query query = dref.orderByChild("id").equalTo(searchID);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.hasChildren()){
txtID.setText((dataSnapshot.child("id").getValue().toString()));
txtName.setText((dataSnapshot.child("name").getValue().toString()));
txtAdd.setText((dataSnapshot.child("address").getValue().toString()));
txtConNo.setText((dataSnapshot.child("conNo").getValue().toString()));
}
else
Toast.makeText(getApplicationContext(),"No Source to Display",Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
});
This is the java code i implemented to do that. But when i run the program and give the correct id in database it is always showing as "No source to display"( There are data in my database and save function is working properly)
I am a beginner in android studio and firebase. Please modify the above code and tell me how can i search by ID.
Thankyou.
Try the following:
if(dataSnapshot.exists()){
for(DataSnapshot ds : dataSnapshot.getChildren()){
txtID.setText((ds.child("id").getValue().toString()));
txtName.setText((ds.child("name").getValue().toString()));
txtAdd.setText((ds.child("address").getValue().toString()));
txtConNo.setText((ds.child("conNo").getValue().toString()));
}
}
Your reference is at node Student therefore you need to loop and then use ds to access the attributes. Also, don't forget to check for errors inside onCancelled:
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore potential errors!
}

addListenerForSingleValueEvent keeps duplicating output

I use addListenerForSingleValueEvent to add value into the child "code" of the current user, but instead the data duplicated.
Here is the database before the coding
This is the coding for the addListenerForSingleValueEvent
b4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mAuth = FirebaseAuth.getInstance();
mUser = mAuth.getCurrentUser();
final String UserId = mUser.getUid();
mReference = FirebaseDatabase.getInstance().getReference("Users");
final DatabaseReference currentUserId = mReference.child(UserId);
currentUserId.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
user.setCode(riasec1);
currentUserId.child(UserId).setValue(user);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
});
Here is the database after the coding is executedWhy is the whole user being duplicated instead of only value "code" inserted?
When you call
currentUserId.child(UserId).setValue(user);
you are saying "add WHOLE user in to node with name 'UserId'".
In general you are fetching WHOLE User, updating one field and updating again.
So when would you like to update a child without rewriting the entire object u should pass node name, e.g.
currentUserId.child(UserId).child("code").setValue(riasec1);
In this call you say:
find node with proper ID (UserId)
find node "code"
set new value (riasec1)

How can I get one object data from my Firebase by ref

I am trying to get an object from my firebase.
I try to get my Trip object, but I get a null value.
This is my db image
this is my code
db_ref = db.getReference("Trips").child(dataguide+" "+data).child(data);
db_ref.child(data).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
trip2 = snapshot.getValue(Trip.class);
}
#Override
public void onCancelled(DatabaseError databaseError) { }
});
so I ask why
In
db_ref.child(data).addValueEventListener(new ValueEventListener()
remove child(data) cause you are already inside the child there is no chiled names ...so change the code to this
"data"db_ref.addValueEventListener(new ValueEventListener()

How to retrieve data child of child from firebase / Android

Here is my firebase database
Here is the info.class
Here is the insert
I want to get all the data from firebase to List View
How can i get all data under "information" data list ?
please help
db = FirebaseDatabase.getInstance();
ref = db.getReference("infomation");
protected void onStart() {
super.onStart();
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
infoList.clear();
for (DataSnapshot infoSnapshot : dataSnapshot.getChildren()){
info info = infoSnapshot.getValue(info.class);
infoList.add(info);
}
InfoList adapter = new InfoList(Welcome.this, infoList);
listViewInfo.setAdapter(adapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
In your insertion part, you need to change it like below,
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("information");
ref.child( FirebaseAuth.getInstance().getCurrentUser().getUid()).setValue(in);
but if you want to save data like save the data like
information >uid> random value > then the data
that use change data retrieving part like below
for (DataSnapshot infoSnapshot : dataSnapshot.getChildren().getChildren()){
info info = infoSnapshot.getValue(info.class);
infoList.add(info);
}

Firebase - Trying to retrieve data of each user into a list

Each user in my app can send and get friend requests. When the user checks his friends requests, I want the app to go through each user who sent him a friend request and retrieve his information from the Realtime Database.
This is my code in order to accomplish this:
public void check_For_Friends_And_Requests(){
String loggedUser=SaveSharedPreference.getLoggedEmail(getApplicationContext());
final DatabaseReference mDatabase= FirebaseDatabase.getInstance().getReference();
final DatabaseReference userRef=mDatabase.child("Users").child(loggedUser);
userRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
final List<User> friendRequestsReceived_UserList=new ArrayList<>();
for (DataSnapshot postSnapshot: dataSnapshot.child("friend_requests_received").getChildren()) {
final String senderEmail=postSnapshot.getKey();
Toast.makeText(getApplicationContext(),
senderEmail, Toast.LENGTH_SHORT).show();
if (senderEmail!=null){
mDatabase.child("Users").child(senderEmail).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Toast.makeText(getApplicationContext(),
dataSnapshot.child("name").getValue(String.class), Toast.LENGTH_SHORT).show();
friendRequestsReceived_UserList.add(
new User(
senderEmail,
dataSnapshot.child("name").getValue(String.class),
dataSnapshot.child("level").getValue(Integer.class),
dataSnapshot.child("skill").getValue(Double.class)));
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
UserListAdapter friendRequestsReceived_Adapter =
new UserListAdapter(getApplicationContext(),
R.layout.friend_requests_received_listview_row,
friendRequestsReceived_UserList);
friendRequestsReceived_ListView.setAdapter(friendRequestsReceived_Adapter);
}
else
connectionErrorGoToMain();
}
#Override
public void onCancelled(DatabaseError databaseError) {
connectionErrorGoToMain();
}
});
}
I have in this code 2 ValueEventListeners. I add the user information to the list in the inner one. The problem is that the list is empty at the end of this process.
I would like to fill a list view with this information using these lines:
UserListAdapter friendRequestsReceived_Adapter =
new UserListAdapter(getApplicationContext(),
R.layout.friend_requests_received_listview_row,
friendRequestsReceived_UserList);
friendRequestsReceived_ListView.setAdapter(friendRequestsReceived_Adapter);
When I put them inside the innner listener, it works fine, but I don't want to set the adapter for each user in the list, only after the for loop.
I'm attaching a screenshot with my database structure (I don't need to get all of the parameters):
The list is empty because you are declaring friendRequestsReceived_UserList outside the inner onDataChange() method. This is happening due the asynchronous behaviour of onDataChange() method which is called before you are adding those new objects to the list. So, in order to solve this, just move the declaration of the list inside the inner onDataChange() method like this:
if (senderEmail!=null){
mDatabase.child("Users").child(senderEmail).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
final List<User> friendRequestsReceived_UserList=new ArrayList<>(); //Moved here
Toast.makeText(getApplicationContext(), dataSnapshot.child("name").getValue(String.class), Toast.LENGTH_SHORT).show();
friendRequestsReceived_UserList.add(
new User(
senderEmail,
dataSnapshot.child("name").getValue(String.class),
dataSnapshot.child("level").getValue(Integer.class),
dataSnapshot.child("skill").getValue(Double.class)));
UserListAdapter friendRequestsReceived_Adapter =
new UserListAdapter(getApplicationContext(), R.layout.friend_requests_received_listview_row, friendRequestsReceived_UserList);
friendRequestsReceived_ListView.setAdapter(friendRequestsReceived_Adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
As you probably see, i set the adapter also inside the inner method. If you want to use that list outside the onDataChange() i suggest you reading my answer from this post.

Categories