how to get count of child inside the parent child - java

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) {
}
});
};

Related

Multiple query orderBy clauses Firebase - Java

I am trying to query my Messages table for three things. The first is any messages with that involve the current user logged in. Then, I want to get the user id of the person the current user has a coversation with. And finally, I want to check if any of the messages were seen. But right now my query only runs the first and last queries and not the second one. But I don't know why.
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userMessageKeyRef = dbRef.child("Messages").child(firebaseUser.getUid());
userMessageKeyRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot snapshot1 : snapshot.getChildren()) {
String messageToID = snapshot1.getKey();
DatabaseReference messageRef = dbRef.child("Messages").child(firebaseUser.getUid()).child(messageToID);
Query query = messageRef.orderByChild("to").equalTo(firebaseUser.getUid());
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
long count = dataSnapshot.getChildrenCount();
if (dataSnapshot.exists()) {
DatabaseReference messageKeyRef = dbRef.child("Messages").child(firebaseUser.getUid()).child(messageToID);
Query query2 = messageKeyRef.orderByChild("isSeen").equalTo(false);
query2.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataShot) {
if (dataShot.exists() && count > 0) {
//Log.d("TAG2", "count if: " + count2);
messages_text.setText("" + Math.toIntExact(count));
messages_text.setVisibility(View.VISIBLE);
} else {
messages_text.setVisibility(View.GONE);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
} else {
messages_text.setVisibility(View.GONE);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
//Log.d("TAG1", "User to: " + messageToID);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
Your first addValueEventListener already loads all data for the current user, so there is no need to go back to the database to load that data again. Instead you should check the properties of each message in your application code with something like:
DatabaseReference userMessageKeyRef = dbRef.child("Messages").child(firebaseUser.getUid());
userMessageKeyRef.addValueEventListener(new ValueEventListener() {
for (DataSnapshot parentSnapshot : snapshot.getChildren()) {
for (DataSnapshot messageSnapshot : addValueEventListener.getChildren()) {
String messageToID = messageSnapshot.getKey();
String toValue = messageSnapshot.child("to").getValue(String.class);
Boolean isSeenValue = messageSnapshot.child("isSeen").getValue(Boolean.class);
if (toValue.equals(firebaseUser.getUid()) && isSeenValue == true) {
...
}
}
}
});

Check value of child in Firebase DB Java

I am trying to select data from my database and I want to check if a specific child node has a one or a zero as it's value. If it has a 1 then I don't want to show info from that specific user. If it has a zero then I want to show info from that specific user.
I did it in a method above the one I'm working on(I followed this answer How to get child of child value from firebase in android?) and I got it working no problem. But I can't do the same for my other method and I have been trying all day now.
As of right now, the only result I am getting is the list not showing up at all. Can someone please help me ?
Method that works:
private void getPosts() {
followingList = new ArrayList<>();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Video_Posts");
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
myPosts.clear();
//followingList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Post post = snapshot.getValue(Post.class);
if (followingList.isEmpty()) {
if (!post.getPublisher().equals(firebaseUser.getUid())) {
DatabaseReference zonesRef = FirebaseDatabase.getInstance().getReference("Users");
DatabaseReference zone1Ref = zonesRef.child(post.getPublisher());
DatabaseReference zone1NameRef = zone1Ref.child("acc_closed");
zone1NameRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Log.i(TAG, dataSnapshot.getValue(String.class));
if (dataSnapshot.getValue(String.class).equals("1")) {
//Toast.makeText(getContext(), "Account closed", Toast.LENGTH_SHORT).show();
} else if (dataSnapshot.getValue(String.class).equals("0")) {
//Toast.makeText(getContext(), "Not closed.", Toast.LENGTH_SHORT).show();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRef
.child("Follow")
.child(firebaseUser.getUid())
.child("following")
.child(post.getPublisher());
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
//Do something
Toast.makeText(getContext(), "Following.", Toast.LENGTH_SHORT).show();
} else {
//Do something else
myPosts.add(post);
Collections.shuffle(myPosts);
//Toast.makeText(getContext(), "Something.", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
query.addListenerForSingleValueEvent(valueEventListener);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
//Log.w(TAG, "onCancelled", databaseError.toException());
}
});
} else if (myPosts == null) {
Toast.makeText(getContext(), "Nothing.", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getContext(), "List is not empty.", Toast.LENGTH_SHORT).show();
for (String id : followingList) {
assert post != null;
if (!post.getPublisher().equals(id)) {
myPosts.add(post);
Toast.makeText(getContext(), "Something.", Toast.LENGTH_SHORT).show();
} else if (myPosts == null) {
Toast.makeText(getContext(), "Nothing.", Toast.LENGTH_SHORT).show();
}
}
}
}
adapterExplorer.notifyDataSetChanged();
progressBar.setVisibility(View.GONE);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
Method that doesn't work:
private void searchUsers(String s) {
Query query = FirebaseDatabase.getInstance().getReference("Users");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (search_bar.getText().toString().equals("")) {
recyclerView.setVisibility(View.INVISIBLE);
}
mUsers.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
User user = snapshot.getValue(User.class);
DatabaseReference zonesRef = FirebaseDatabase.getInstance().getReference("Users");
DatabaseReference zone1Ref = zonesRef.child(user.getId());
DatabaseReference zone1NameRef = zone1Ref.child(user.getAcc_closed());
//mUsers.add(user);
zone1NameRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapS) {
if (snapS.getKey().equals("1")) {
} else if (snapS.getKey().equals("0")){
//if (!snapS.exists()) {
Log.d("TAG", snapS.toString());
mUsers.add(user);
//}
}
//}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Log.d("Error name", error.getMessage());
}
});
}
userAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Log.d("Error name", error.getMessage());
}
});
}
Database:
"Users": {
"4mFQt8Lf3CTNrQF74sy8wwyFoLh1": {
"acc_closed": "0",
"bio": "",
"dateAdded": "19-06-2022 17:28:56",
"date_time": 1655674136805,
"device_token": "feGjHNzaR7S8yaV2HKg0rt:APA91bEXAiYwT52niHVxR2ENrcaKXSNs11Z5ss-g2gsDwTs4wbjqjcrN4ZUmemqiMzp6SZM6UXD5TFrc1JND_DoEgd-Ni9wMeCa73EzvKBAaj5aXJf1GjgjSsTVwBg1A6VvhvVwF1VSX",
"fullname": "Brandon",
"id": "4mFQt8Lf3CTNrQF74sy8wwyFoLh1",
"imageurl": "https://firebasestorage.googleapis.com/v0/b/gone-b14f5.appspot.com/o/default.jpg?alt=media&token=befece91-9248-45ee-ab6f-b1b3d217c6b4",
"username": "bran1",
"verified": "false"
},
EDIT:
The code above (searchUsers) kind of works. When I put text into the search bar nothing shows up. But when I hit the back button and remove the keyboard the data shows up. It's like I'm actually waiting for data to change.
The simple fix is that you should call notifyDataSetChanged after you modified the data that the adapter shows, where right now you're calling it before that.
So move the call to userAdapter.notifyDataSetChanged() to right after mUsers.add(user):
Query query = FirebaseDatabase.getInstance().getReference("Users");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (search_bar.getText().toString().equals("")) {
recyclerView.setVisibility(View.INVISIBLE);
}
mUsers.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
User user = snapshot.getValue(User.class);
DatabaseReference zonesRef = FirebaseDatabase.getInstance().getReference("Users");
DatabaseReference zone1Ref = zonesRef.child(user.getId());
DatabaseReference zone1NameRef = zone1Ref.child(user.getAcc_closed());
zone1NameRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapS) {
if (snapS.getKey().equals("1")) {
} else if (snapS.getKey().equals("0")){
Log.d("TAG", snapS.toString());
mUsers.add(user);
userAdapter.notifyDataSetChanged(); // 👈
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Log.d("Error name", error.getMessage());
}
});
}
}
There is some more (but not related to the problem) room for optimization here, as the dataSnapshot you get in the outermost listener already contains the data for *alldata under/Users`.
So there's no need to add an other listener to get the acc_closed value for each user. Instead you can just navigate the initial snapshot like this:
Query query = FirebaseDatabase.getInstance().getReference("Users");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (search_bar.getText().toString().equals("")) {
recyclerView.setVisibility(View.INVISIBLE);
}
mUsers.clear();
for (DataSnapshot userSnapshot : dataSnapshot.getChildren()) {
DataSnapshot snapS = userSnapshot.child("acc_closed");
String accClose = snapS.getValue(String.class)
if (accClose.equals("0")){
Log.d("TAG", accClose);
mUsers.add(userSnapshot.getValue(User.class));
userAdapter.notifyDataSetChanged();
}
}
}
Finally: your code retrieves all /Users to then only use the users who have acc_close being equal to "0". This wastes (your and your user's) bandwidth, especially as you're adding more users. It's much better to use a query to retrieve only the necessary data from the server/database:
DatabaseReference usersRef = FirebaseDatabase.getInstance().getReference("Users");
Query query = usersRef.orderByChild("acc_closed").equalTo("0");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (search_bar.getText().toString().equals("")) {
recyclerView.setVisibility(View.INVISIBLE);
}
mUsers.clear();
for (DataSnapshot userSnapshot : dataSnapshot.getChildren()) {
mUsers.add(userSnapshot.getValue(User.class));
}
userAdapter.notifyDataSetChanged();
}

How to retrieve the values of "Total"

This is my firebase database structure.
I want to fetch the values of "Total" of all children of "Bill". I have tried to fetch the data but my code is not working. Here is my code.
DatabaseReference billReference = FirebaseDatabase.getInstance().getReference().child("Bill");
billReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int i = 0;
for (DataSnapshot ds : dataSnapshot.getChildren()) {
fetchCount++;
Toast.makeText(getApplicationContext(),""+keys[i],Toast.LENGTH_LONG).show();
String temp = ds.child(keys[i]).child("Breakfast").child("11-2018").child("Total").getValue().toString();
breakfastBills.add(names[i] + " : " + temp);
i++;
}
if (fetchCount == 4) {
AlertDialog.Builder builder = new AlertDialog.Builder(bill_details_manager.this);
builder.setTitle("Bill Details for Breakfast");
builder.setItems(breakfastBills.toArray(new String[breakfastBills.size()]), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
progressDialog.dismiss();
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
What is wrong with this code ?
DatabaseReference billRef = FirebaseDatabase.getInstance().getReference();
billRef.child("Bill").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot allValueSnap) {
for (DataSnapshot snapshot: allValueSnap.getChildren()){
String key = snapshot.getKey();
if (key != null) {
billRef.child("Bill").child(key).child("Breakfast").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot keySnapshot) {
for (DataSnapshot dateSnapshot:keySnapshot.getChildren()){
String keyDate = dateSnapshot.getKey();
long totalValue =(long) keySnapshot.child(keyDate).child("Total").getValue();
Log.i("totalBreakFast","STotal: "+String.valueOf(totalValue));
breakfastBills.add(totalValue);
}
if(!keySnapshot.exists()){
Log.i("totalBreakFast","NoData: ");
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
This code is getting all values of "Total".

android: get the child of child

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
}

how i can get my info through the random key by push

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) {
}
});

Categories