Hi in my Firebase database I am trying to access one child "Chatmessages", gathering all its keys and using them to locate their corresponding keys in the child "Users" and gathering its information. I am doing this this through querying twice using eventlisteners. Although how would I apply this to chatIDref in my loadUserlist() method.
Structure of database:
rootRef = FirebaseDatabase.getInstance().getReference();
chatIdRef = rootRef.child("Chatmessages").child(last);
eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String uid = ds.getKey();
usersRef = rootRef.child("Users").child(uid);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String image = dataSnapshot.child("image").getValue(String.class);
String name = dataSnapshot.child("name").getValue(String.class);
Boolean onlineStatus = dataSnapshot.child("onlineStatus").getValue(Boolean.class);
String status = dataSnapshot.child("username").getValue(String.class);
Log.d("TAG", image + " / " + name + " / " + onlineStatus + " / " + status);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
usersRef.addListenerForSingleValueEvent(eventListener);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
chatIdRef.addListenerForSingleValueEvent(eventListener);
chatIdRef.keepSynced(true);
userlist.setHasFixedSize(true);
userlist.setLayoutManager(new LinearLayoutManager(getContext()));
return userView;
}
public void loadUserList() {
FirebaseRecyclerAdapter<User, UserViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<User, UserViewHolder>(
User.class,
R.layout.userlist_layout,
UserViewHolder.class,
chatIdRef
)
Related
What I really need is to show every value in the "Income" field in TextView.
250
105
Is this possible? If it is possible please help me.
This is how I insert values to database
private void addReport() {
Float total_Income = Float.valueOf(tv_total_income.getText().toString());
String current_date = tv_current_date.getText().toString();
SimpleDateFormat sdf = new SimpleDateFormat("MMMM");
String currentDateandTime = sdf.format(new Date());
FirebaseDatabase mDatabase = FirebaseDatabase.getInstance();
DatabaseReference mDbRef = mDatabase.getReference("Reports"+"/"+currentDateandTime+"/"+current_date).child("Date");
mDbRef.setValue(current_date);
DatabaseReference mDbRef1 = mDatabase.getReference("Reports"+"/"+currentDateandTime+"/"+current_date).child("Income");
mDbRef1.setValue(total_Income);
}
While Sairaj Sawant's answer might work, keep in mind that there is no need to attach a listener at every iteration of the loop. A more convenient solution is to attach a listener only once, like in the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference juneRef = rootRef.child("Reports").child("June");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String totalIncome = "";
for(DataSnapshot ds : dataSnapshot.getChildren()) {
totalIncome = totalIncome + ds.child("Income").getValue(String.class) + " ";
}
Log.d("TAG", totalIncome);
textView.setText(totalIncome);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore errors!
}
};
juneRef.addListenerForSingleValueEvent(valueEventListener);
This code will work only if the Income property is of type String, as it is set in your 20-06-2020 child. However, the above code will not work if the value is set as an Integer as it set in your second 21-06-2020 child. Remember, both types of values must match. You either set both as String and the above code will work, or you set them as numbers, case in which you should use this line:
totalIncome = totalIncome + ds.child("Income").getValue(Long.class) + " ";
Try accessing the children of June under Reports and looping through to get income as below :
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference reportsRef = rootRef.child("Reports").child("June");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String key = ds.getKey();
DatabaseReference keyRef = rootRef.child(key).child("income");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds1 : dataSnapshot.getChildren()) {
String income = ds1.getValue(String.class);
Log.d("TAG", income);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
keyRef.addListenerForSingleValueEvent(valueEventListener);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
reportsRef.addListenerForSingleValueEvent(eventListener);
I am trying to join between two nodes with firebase in java, but I can't relate all the data and display it in the view correctly. Any solution?
This is the data in firebase:
Person
66db3d6a-c6cf-4577-a857-eca22cd55403
name:"aaa"
surname:"bbb"
mail:"john#hotmail.com"
id:"66db3d6a-c6cf-4577-a857-eca22cd55403"
User
4ad0c3db-a5b1-40bb-bfc1-35c15ec5af9c
nameUser:"john123"
password:"******"
idPerson:"66db3d6a-c6cf-4577-a857-eca22cd55403"
idUser:"4ad0c3db-a5b1-40bb-bfc1-35c15ec5af9c"
This is my code:
private void listAll(){
Map<String, String> valuesMapJoin = new HashMap<>();
databaseReference.child("Person").orderByKey().addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()){
Map<String, String> valuesMapPerson =
(HashMap<String,String>)dataSnapshot1.getValue();
String idPerson = valuesMapPerson.get("id");
String name = valuesMapPersona.get("name");
String surname = valuesMapPersona.get("surname");
String surname = valuesMapPersona.get("mail");
databaseReference.child("User").orderByKey().equalTo(idPerson).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
Map<String, String> valuesMapUser = (HashMap<String,
String>)dataSnapshot1.getValue();
String nameUser = valuesMapUsuario.get("nameUser");
String password = valuesMapUsuario.get("password");
listDataJoin.add(name + "-" + sourname + "-" + mail + "-" + nameUser + "-
" + password);
arrayAdapter = new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_list_item_1, listDatosJoin);
listJoin.setAdapter(arrayAdapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void listAll(){
Map<String, String> valuesMapJoin = new HashMap<>();
databaseReference.child("Person").orderByKey().addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()){
Map<String, String> valuesMapPerson =
(HashMap<String,String>)dataSnapshot1.getValue();
String idPerson = valuesMapPerson.get("id");
String name = valuesMapPersona.get("name");
String surname = valuesMapPersona.get("surname");
String surname = valuesMapPersona.get("mail");
databaseReference.child("User").orderByKey().equalTo(idPerson).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
Map<String, String> valuesMapUser = (HashMap<String,
String>)dataSnapshot1.getValue();
String nameUser = valuesMapUsuario.get("nameUser");
String password = valuesMapUsuario.get("password");
listDataJoin.add(name + "-" + sourname + "-" + mail + "-" + nameUser + "-
" + password);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
arrayAdapter = new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_list_item_1, listDatosJoin);
listJoin.setAdapter(arrayAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
Use above code snippet main problem is you have adapter set inside for loop so your code not work perfectly
This is the Firebase database:
ExchangeItemsData: -> reference
lhmuj6n3g6Su1rv7XJLq5tV62yr2 -> userId
-LQQ7scByWcswW2VIPM5 -> UniqueKey inserted by .push().getKey();
// below is the data under the uniquekey
exchangeProductName:
"Pen"
imageUrl:
"https://firebasestoragse.googleapdfis.codfm/v04df/b/dbin..."
phoneNo:
5465464
productDesc:
"Used"
productName:
"GelPen"
userID:
"lhmuj6n3g6Su1rv7XJLq5tV62yr2"
I need to show all data of every user in this ExchangeItemsData reference. I've tried many ways but i failed. If anyone can help me out here it would be so nice of you.
Thanks in advance.
To get all those values that belong to all users, please use the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = rootRef.child("ExchangeItemsData");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot dSnapshot : dataSnapshot.getChildren()) {
for(DataSnapshot ds : dSnapshot.getChildren()) {
String imageUrl = ds.child("imageUrl").getValue(String.class);
String phoneNo = ds.child("phoneNo").getValue(String.class);
String productDesc = ds.child("productDesc").getValue(String.class);
String productName = ds.child("productName").getValue(String.class);
String userID = ds.child("userID").getValue(String.class);
Log.d(TAG, productName);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage());
}
};
ref.addListenerForSingleValueEvent(valueEventListener);
The output in the logcat will be all the product names of all products of all users.
Try this code to retrieve values from your database
public class Demo extends Activity{
FirebaseAuth mAuth;
String currentUId;
DatabaseReference usersDb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
mAuth=FirebaseAuth.getInstance();
currentUId=mAuth.getUid();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("ExchangeItemsData");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists() && dataSnapshot.hasChildren()){
for (DataSnapshot userId : dataSnapshot.getChildren()) {
if(!userId.getKey().equals(currentUId)) {
usersDb.child(userId).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot1) {
if(dataSnapshot1.hasChildren()){
for (DataSnapshot userKey : dataSnapshot1.getChildren()) {
String exchangeProductName = dataSnapshot1.child(userKey).child("exchangeProductName").getValue().toString();
String imageUrl = dataSnapshot1.child(userKey).child("imageUrl").getValue().toString();
String phoneNo = dataSnapshot1.child(userKey).child("phoneNo").getValue().toString();
String productDesc = dataSnapshot1.child(userKey).child("productDesc").getValue().toString();
String productName = dataSnapshot1.child(userKey).child("productName").getValue().toString();
String userID = dataSnapshot1.child(userKey).child("userID").getValue().toString();
//From here do whatever you want to do with those values
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
}
}
}
}
}
I am trying to get the "status" of the ride that is presently in my "History" node but first I had to get the "rideKey".
Global variables: String rideKey, String key.
History node:
{
"History" : {
"-LGXaukR30LTjrL3ZNpt" : {
"driver" : "ptnVOKounjXE9VrmZCCvKoZWluf1",
"rating" : 0,
"ridePrice" : 5.25,
"rider" : "C0RjB5NPZcTvWz9XiUAhpTDOK0C2",
"status" : "accepted",
"timestamp" : 1530662726
}
}
}
To get the rideKey, I did this:
DatabaseReference keyRef = FirebaseDatabase.getInstance().getReference("History");
keyRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
rideKey = String.valueOf(mDatabase.child("History").push().getKey());
Log.d(TAG, "getKey: key = " + rideKey);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
This gives me all the keys in History, how can I get the most recent?
Now, I, also need to get the "status" of the request.
But, when I try to get the status, it keeps coming up null.
I have tried putting another ValueEventListener inside the rideKey value event but still null
Any ideas as to what I am doing wrong?
Much appreciated.
EDIT
Log.e(TAG, "I made it to getKeyAndStatus");
DatabaseReference keyRef = FirebaseDatabase.getInstance().getReference("History");
keyRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
**// Log.e(TAG, "I made it to getKeyAndStatus: onDataChange");**
Iterable<DataSnapshot> children = dataSnapshot.child("History").getChildren();
for (DataSnapshot child : children){
Log.d(TAG, "getKey: key = " + child.getKey());
Ride ride = child.getValue(Ride.class);
Log.e(TAG, "ride = " + ride);
Log.d(TAG, "Driver = " + ride.getDriver());
Log.d(TAG, "Rating = " + ride.getRating());
Log.d(TAG, "Rider = " + ride.getRider());
Log.d(TAG, "Price = " + ride.getRidePrice());
Log.d(TAG, "status = " + ride.getStatus());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
The above code only makes it as far as the Log "I made it to getKeyAndStatus: onDataChange"
EDIT - Results
To solve this, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference historyRef = rootRef.child("History");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
Ride ride = ds.getValue(Ride.class);
Log.d(TAG, "Driver = " + ride.getDriver());
Log.d(TAG, "Rating = " + ride.getRating());
Log.d(TAG, "Rider = " + ride.getRider());
Log.d(TAG, "Price = " + ride.getRidePrice());
Log.d(TAG, "status = " + ride.getStatus());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
historyRef.addListenerForSingleValueEvent(valueEventListener);
The output in the logcat will be the values of your properties.
Note, when using the following line of code:
rideKey = String.valueOf(mDatabase.child("History").push().getKey());
You are generating another key instead of getting the existing one. Use the push() method only when you add objects not when you read them.
DatabaseReference keyRef = FirebaseDatabase.getInstance().getReference("History");
keyRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
rideKey = String.valueOf(mDatabase.child("History").push().getKey());
Log.d(TAG, "getKey: key = " + rideKey);
DatabaseReference statusRef = FirebaseDatabase.getInstance().getReference("History").Child(rideKey).Child("status");
statusRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
History history = new History(); //If you make class for history
history = dataSnapshot.getValue(History.class);
textViewStatus.setText(history.getStatus());
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
DatabaseReference historyRef = FirebaseDatabase.getInstance().getReference().child("History");
historyRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child : dataSnapshot.getChildren()){
Log.d(TAG, "getKey: key = " + child.getKey());
Ride ride = child.getValue(Ride.class);
Log.d(TAG, "Driver = " + ride.getDriver());
Log.d(TAG, "Rating = " + ride.getRating());
Log.d(TAG, "Rider = " + ride.getRider());
Log.d(TAG, "Price = " + ride.getRidePrice());
Log.d(TAG, "status = " + ride.getStatus());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
//
// "driver" : "ptnVOKounjXE9VrmZCCvKoZWluf1",
// "rating" : 0,
// "ridePrice" : 5.25,
// "rider" : "C0RjB5NPZcTvWz9XiUAhpTDOK0C2",
// "status" : "accepted",
// "timestamp" : 1530662726
class Ride{
// Remove #Exclude https://firebase.google.com/docs/reference/android/com/google/firebase/database/Exclude
private String driver;
private int rating;
private float ridePrice;
private String rider;
private String status;
private long timestamp;
public Ride() {
// Empty Constructor
}
// Getter & Setter
}
I have a problem, when I want get value from firebase, getValue() return null
DataSnapshot appleSnapshot and DataSnapshot dataSnapshot - in console I see Key and Value correctly in Firebase too
Database Structure
Debugging
DataSnapshot setting - return Key but don't return Value (null)
String settingKey - return correctly String Key
String settingValue - return null
Why i cant get Value from my deeper childs?
private void readData(final ValidateJoinInterface validateJoinInterface, final String name, final String password, final String user) {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot appleSnapshot : dataSnapshot.getChildren()) {
DataSnapshot setting = appleSnapshot.child(name).child("Settings").child("Password");
String settingKey = (String) appleSnapshot.child(name).child("Settings").child("Password").getKey();
String settingValue = (String) appleSnapshot.child(name).child("Settings").child("Password").getValue();
}
validateJoinInterface.validateJoin(correctName, correctPassword, correctUserId);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e("DTAG", "onCancelled", databaseError.toException());
}
});
}
Assuming that the name varaible holds a String value like in your example Aa and also assuming that Aa is a direct child of your Firebase root, to solve this, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference settingsRef = rootRef.child(name).child("Settings");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String name = dataSnapshot.child("Name").getValue(String.class);
String password = dataSnapshot.child("Password").getValue(String.class);
Log.d("TAG", name + " / " + password);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
settingsRef.addListenerForSingleValueEvent(valueEventListener);
The output will be: Aa / Aaa.
You can getting any value like :
FirebaseDatabase.getInstance().getReference().child(name).child("Settings").child("Password")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot messageSnapshot : dataSnapshot.getChildren()) {
Log.d(TAG,"KEY - "+messageSnapshot.getKey() + "VALUE - "+messageSnapshot.getValue());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Crashlytics.logException(databaseError.toException());
sendMessageListener.onSendMessageFailure(databaseError.getMessage());
}
});