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
}
Related
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.contains(java.lang.CharSequence)' on a null object reference
I will make the game I want, when the person from the game makes the room available from the database, everything really happens, but here's the problem, an error occurs that the element is not found, this is because this code here:
private void addRoomEventListener(){
messageRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (role.equals("host:")){
if (snapshot.getValue(String.class).contains("guest:")){
step.setEnabled(true);
Toast.makeText(DuelGame.this, "" +
snapshot.getValue(String.class).replace("guest:", ""),Toast.LENGTH_SHORT ).show();
}
}else {
if (snapshot.getValue(String.class).contains("host:")){
step.setEnabled(true);
Toast.makeText(DuelGame.this, "" +
snapshot.getValue(String.class).replace("host:", ""),Toast.LENGTH_SHORT ).show();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
messageRef.setValue(message);
}
});
}
anyway reads from the database from the same room things that no longer exist, they are deleted, how can I make the activity completely pause when I exit it, I specify finish();but it still does not work.
Also tried this this.finishAffinity();,but the effect is the same.
I use this code in onDestroy to remove path in database:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
Query applesQuery = ref.child("rooms").orderByChild(roomName);
applesQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot appleSnapshot: dataSnapshot.getChildren()) {
appleSnapshot.getRef().removeValue();
finish();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG, "onCancelled", databaseError.toException());
}
});
My JSON firebase database:
{
"players": {
"popka negra": {
"loses": 8,
"name": "jack",
"wins": 12
}
},
"rooms": {
"jack": {
"message": "host: Your opponent make step! "
}
}
}
All values:
FirebaseDatabase database;
DatabaseReference messageRef;
String playerName = "";
String roomName = "";
String role = "";
String message = "";
database = FirebaseDatabase.getInstance();
SharedPreferences preferences = getSharedPreferences("PREFS", 0);
playerName = preferences.getString("playerName", "");
Bundle extras = getIntent().getExtras();
if (extras != null){
roomName = extras.getString("roomName");
if (roomName.equals(playerName)){
role = "host:";
}else {
role = "guest:";
}
}
messageRef = database.getReference("rooms/" + roomName + "/message");
message = role + " Your opponent make step! ";
messageRef.setValue(message);
I am facing an issue which is, I did not know how to update the product quantity where the product already exist in my cart activity. I am trying to retrieve my data from firebase, but not able to do so.
Here is my code:
private void addToCart() {
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("User Type").child(firebaseAuth.getUid());
databaseReference
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
if (dataSnapshot.child(firebaseAuth.getUid()).child("Cart").child(productID).exists()){
//update to firebase
String addedQty1 = "" + snapshot.child("addedQuantity").getValue();
int getQty = Integer.parseInt(addedQty1);
int currentQty = Integer.parseInt(addedQty);
int newAddedQty = getQty + currentQty;
String addedNewQty = String.valueOf(newAddedQty);
HashMap<String, Object> hashMap1 = new HashMap<>();
hashMap1.put("addedQuantity", "" + addedNewQty);
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("User Type");
databaseReference.child(firebaseAuth.getUid()).child("Cart").child(productID).updateChildren(hashMap1)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
//updated
progressDialog.dismiss();
Toast.makeText(ViewProductDetails.this, "Added successfully.", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
//failed to update
progressDialog.dismiss();
Toast.makeText(ViewProductDetails.this, "" + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
} else {
//Add to firebase
final String timestamp = "" + System.currentTimeMillis();
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("cartID", "" + timestamp);
hashMap.put("accountID", "" + accountID);
hashMap.put("productID", "" + productID);
hashMap.put("orderFrom", "" + shopName);
hashMap.put("discountNote", "" + discountNote);
hashMap.put("originalPrice", "" + oriPrice);
hashMap.put("discountPrice", "" + discountedPrice);
hashMap.put("price", "" + price);
hashMap.put("productTitle", "" + productTitle);
hashMap.put("productCategory", "" + category);
hashMap.put("productSize", "" + size);
hashMap.put("productQuantity", "" + availableQty);
hashMap.put("addedQuantity", "" + addedQty);
//add to firebase
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("User Type");
databaseReference.child(firebaseAuth.getUid()).child("Cart").child(productID).setValue(hashMap)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
progressDialog.dismiss();
Toast.makeText(ViewProductDetails.this, "Added successfully.", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
//failed to update
progressDialog.dismiss();
Toast.makeText(ViewProductDetails.this, "" + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
I have shared the code snippet where "else" statement works fine whereas "if" statement is failed to run. Hope anyone can help me. I really appreciate it!
Your basic solution should look like this pseudocode:
if (product already in cart) {
get current product count from cart
increment product count
store new count back in cart
}
That is one test and three actions. Check that all four are present and that all four work. If you can, it is better to test them separately so you can isolate errors more easily.
I have JsonString by receive DataSnapShot:
myRef.child("user").orderByChild("u_email").equalTo(name).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String c = dataSnapshot.getValue().toString();
Log.w(Login.TAG, "Data: "+ c);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
in normal if i know the key (-L3Mh7kKl04GSrndbrVD) ill code:
JSONObject a = new JSONObject(c);
JSONObject jsonUser = a.getJSONObject("-L3Mh7kKl04GSrndbrVD");
But i dont have that key, How i can get that value (name, pass, img, ...) with code, im newbie. Thanks all alot
try this:
DatabaseReference references=FirebaseDatabase.getInstance().getReference().child("user");
references.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot data: dataSnapshot.getChildren()){
String name=data.child("name").getValue().toString();
String password=data.child("pass").getValue().toString();
String img=data.child("img").getValue().toString();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Here the reference is the user node, then using the for loop it will iterate inside every push id to give you the values (name,img,pass,...).
Try this
myRef.child("user").orderByChild("u_email").equalTo(name).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String c = dataSnapshot.getValue().toString();
Log.w(Login.TAG, "Data: "+ c);
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String u_img = ds.child("u_img").getValue(String.class);
String u_pass = ds.child("u_pass").getValue(String.class);
String u_address = ds.child("u_address").getValue(String.class);
Log.d("TAG",u_img + " / " + u_pass + " / " + u_address);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
database rules
my database
I have a problem with writing data in firebase database
It must give an id for the data using method postId()
Sometimes its give me a right id and another time wrong id or updata data in an id was created
the id must be like this for all user post
[user1]
postId1
postId2
postId3
postId4
postId5
.
.
postId100000
[user2]
postId1
postId2
postId3
postId4
postId5
.
.
postId100000
........................................................................
if (auth.getCurrentUser() != null) {
mDatabase.child("AdUsersINFO").child(auth.getCurrentUser().getUid()).child(POSTID).setValue(adver,
new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if (databaseError == null) {
Toast.makeText(getContext(), "Data is saved successfully", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getContext(), "Data isn,t saved , please try again", Toast.LENGTH_LONG).show();
}
}
});
mAdUserDatabse = FirebaseDatabase.getInstance().getReference().child("AdUsersINFO").child(auth.getCurrentUser().getUid()).child(POSTID);
mAdUserDatabse.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
mAdUserDatabse.child("userid").setValue(auth.getCurrentUser().getUid());
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void postId() {
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference().child("AdUsersINFO");
rootRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
if (snapshot.hasChild(auth.getCurrentUser().getUid())) {
// run some code
mAdUserDatabse = FirebaseDatabase.getInstance().getReference().child("AdUsersINFO");
mAdUserDatabse.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snap : dataSnapshot.getChildren()) {
Log.e(snap.getKey(), snap.getChildrenCount() + "");
if (snap.getChildrenCount() != 0) {
postId = "postId" + String.valueOf(snap.getChildrenCount() + 1);
SharedPreferencesUtils.setStringPreference(getActivity(), "postId", postId);
} else {
postId = "postId" + String.valueOf(1);
SharedPreferencesUtils.setStringPreference(getActivity(), "postId", postId);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
} else {
postId = "postId" + String.valueOf(1);
SharedPreferencesUtils.setStringPreference(getActivity(), "postId", postId);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
please save my life
You're running a loop and overwriting value of postId again and again, so the postId is equal to the count of last child. So you're always getting the postId count for last user.
so have a look again at the part
for (DataSnapshot snap : dataSnapshot.getChildren()) {
Log.e(snap.getKey(), snap.getChildrenCount() + "");
if (snap.getChildrenCount() != 0) {
postId = "postId" + String.valueOf(snap.getChildrenCount() + 1);
SharedPreferencesUtils.setStringPreference(getActivity(), "postId", postId);
} else {
postId = "postId" + String.valueOf(1);
SharedPreferencesUtils.setStringPreference(getActivity(), "postId", postId);
}
}
Consider using separate key for every user's postId or make a function to get key for one user something like this
public void getPostId(String userId) {
final String postId = "post";
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference().child("AdUsersINFO").child(userId);
rootRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
long c = snapshot.getChildrenCount();
if(c==) postId = postId+"1";
else postId = postId+ c+1;
},
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
};
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
)