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

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

Related

How to access and store list from firebase in android java

List<String> userinterest=new ArrayList<String>();
FirebaseDatabase database= FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference();
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String userId=user.getUid();
public void UserInterest() {
myRef.child("users");
myRef.child(userId);
myRef.child("userinterest");
myRef.child("list").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
Log.d("list", snapshot.child("list").getValue().toString());
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
I tried this code But I am getting a fatal exception.
I want the List of data and store that in an ArrayList. someone please help me with this how to access the list of user interests.
from this
users
LMECILdKstfD1kgmtMQv6wOswxa2
email:"shetyheef#gmail.com"
password:"qwerty"
userinterest
list
0:"I Will agree to use personal interest"
1:"General_mix"
2:"Technolgy"
3:"Sports"
4:"Science"
5:"Maths"
The first 3 lines of this code do nothing:
myRef.child("users");
myRef.child(userId);
myRef.child("userinterest");
myRef.child("list").addListenerForSingleValueEvent(new ValueEventListener() {
...
The child(...) method returns a new DatabaseReference object, and since you're not assigning that, the first three lines are meaningless.
If you want to read from the /users/$userId/userinterest/list path, do:
myRef.child("users").child(userId).child("userinterest/list")
.addListenerForSingleValueEvent(new ValueEventListener() {
...
In addition: never leave onCancelled empty, as you're ignoring possible errors. At its minimum, it should be:
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException();
}

I need Quick refresh data from firebase database when the data is add

I just want to refresh the data as I enter the new data but my code is not working right it shows the data after reopen the same activity.
Here is my code:
Total_bgt_dataref.addListenerForSingleValueEvent(new ValueEventListener(){
#Override
public void onDataChange(#NonNull DataSnapshot snapshot){
for(DataSnapshot ds:snapshot.getChildren()){
Map<String, Object> objectMap=(HashMap<String, Object>)snapshot.getValue();
String value=(String)objectMap.get("Total_Budget");
tv_budget.setText(value);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error){
Toast.makeText(MainActivity.this,"DatabaseError Total Budget",Toast.LENGTH_SHORT).show();
}
});
Instead of addListenerForSingleValueEvent user addValueEventListener, Since addListenerForSingleValueEvent will be canceled once an event listened, but addValueEventListener will always listen to the value change event.
Total_bgt_dataref.addValueEventListener(new ValueEventListener(){
#Override
public void onDataChange(#NonNull DataSnapshot snapshot){
for(DataSnapshot ds:snapshot.getChildren()){
Map<String, Object> objectMap=(HashMap<String, Object>)snapshot.getValue();
String value=(String)objectMap.get("Total_Budget");
tv_budget.setText(value);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error){
Toast.makeText(MainActivity.this,"DatabaseError Total Budget",Toast.LENGTH_SHORT).show();
}
});
check this for more information.
Note: You must remove the listener once you are done with it, so you must keep the reference to the listener and remove it at the end.

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!
}

Access all child values of a snapshot in firebase

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.

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