How to get the key of a pushed value - java

In Firebase Realtime Database on Android, I want to retrieve this id "-Mb1sSv-FCNr9ElxZIwN".
databaseReference = FirebaseDatabase.getInstance().getReference().child("Registration Data1");
mDBListener = databaseReference.orderByKey().limitToLast(1).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mTeachers.clear();
for (DataSnapshot teacherSnapshot : dataSnapshot.getChildren()) {
Data DB = teacherSnapshot.getValue(Data.class);
DB.setKey(teacherSnapshot.getKey());
mTeachers.add(DB);
}
mAdapter.notifyDataSetChanged();
mProgressBar.setVisibility(View.GONE);
}

It looks to me that KAsr ... dhz1 is the user ID that comes from the authentication process. If so, that UID should also be added to your reference. So to be able to get this id "-Mb1sSv-FCNr9ElxZIwN", please change the following reference:
databaseReference = FirebaseDatabase.getInstance().getReference().child("Registration Data1");
To:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
databaseReference = FirebaseDatabase.getInstance().getReference().child("Registration Data1").child(uid);
Meaning that:
DB.setKey(teacherSnapshot.getKey());
Will set the above key to the "DB" object.

Related

Firebase onDataChange() method is not entered [duplicate]

I am trying to retrieve data from Firebase, but I don't know how. I have the following data structure in Firebase [1]: https://i.stack.imgur.com/vN7Ge.png:
![enter image description here][1]
I can retrieve the category title(sleep, Stress Relief, and Relax), but don't know how to retrieve the author.
dataSnapshot.child("author").getValue(String.class)) ; doesn't work.
.
databaseReference = FirebaseDatabase.getInstance().getReference().child("Category");
}
public void getDataFromFirebase() {
List<ParentItem> parentItemsList = new ArrayList<>();
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
String category = dataSnapshot.child("Category").getValue(String.class));
String author = dataSnapshot.child("author").getValue(String.class));
}
Log.d("TAG", "onDataChange: "+ parentItemsList);
}
UPDATE
now I have the following code to retrieve data, but onDataChange () is never reached.
list.add("Milena"); // this word shows in recyclerview
databaseReference = FirebaseDatabase.getInstance().getReference().child("Category");
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
list.add("M");
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String category = ds.child("Category").getValue(String.class);
list.add(category);
for (DataSnapshot data : dataSnapshot.getChildren()) {
author = data.child("author").getValue(String.class);
list.add(author);
}
}
}
firebase rules:
{
"rules": {
".read": "auth==true",
".write": "auth==true"
}
}
I have line list.add("Milena") to make sure the problem is with firebase, not the recycler view itself. Recycler view shows only the word "Milena". And I have line as the first line of OnDataChange method list.add("M"). The recycler view doesn't shows the letter.
I already added google-services.json file to my app and added this line to manifest <uses-permission android:name="android.permission.INTERNET"/>
Why I can't still retrieve data?
If you want get field author, you can more loop for dataSnapshot like this
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
String category = dataSnapshot.child("Category").getValue(String.class));
for(DataSnapshot data : dataSnapshot.getChildren()) {
String author = data.child("author").getValue(String.class));
}
}
hope this can solve your problem :)
I think that the problem is your reference points to Category and you want the author. Between category and authors there are 2 children ("Sleep" and "1").
So, I think the best to do is change this line:
databaseReference = FirebaseDatabase.getInstance().getReference().child("Category");
in this:
databaseReference = FirebaseDatabase.getInstance().getReference().child("Category").child("Sleep").child("1");
To solve this issue you have to iterate through the children twice, as seen in the following lines of code:
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference categoryRef = db.child("Category");
categoryRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
DataSnapshot snapshot = task.getResult();
for (DataSnapshot categorySnapshot : snapshot.getChildren()) {
String categoryName = categorySnapshot.getKey();
Log.d("TAG", categoryName);
for (DataSnapshot ds : categorySnapshot.getChildren()) {
String author = ds.child("author").getValue(String.class);
Log.d("TAG", author);
}
}
} else {
Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
}
}
});
But be aware that a child as Category: "Sleep" should not exist on the same level as 1, 2, and so on. Since the name of the category already exists as the key of a node, please remove those records:
In this way, you'll avoid a ClassCastException, as at the same level you have an object with two properties and a String one. So once you remove those children, the above code will work perfectly fine. If you however need a node to contain that information, I recommend you create a top-level node that will contain only the name of the categories.

Reading data from Firebase Realtime Database for a specific user

What is the proper way to read data from Firebase Realtime Database? I have created a database "Mybill"s with child bills. In child Bills, I am saving UserId from FirebaseAuth so it should be easy to find bills for a specific user and in userID child, I have a child that I have created using the .push() method and in that, I have data about the bill.
It looks like this:
How should I change my Java code so I can get all the bills saved for a specific user (the user that is currently logged in)
this is my code for now :
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference("bills");
Query checkUser = ref.orderByChild("UserId").equalTo(Autentication.GetUser());
// Attach a listener to read the data at our posts reference
checkUser.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String email = dataSnapshot.child("email").getValue(String.class);
String market = dataSnapshot.child("market").getValue(String.class);
String price = dataSnapshot.child("price").getValue(String.class);
String date = dataSnapshot.child("date").getValue(String.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});
How should I change my Java code so I can get all the bills saved for a specific user (the user that is currently logged in)
To do that, please use the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("bills").child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String email = ds .child("email").getValue(String.class);
String market = ds .child("market").getValue(String.class);
String price = ds .child("price").getValue(String.class);
Log.d("TAG", email + "/" + market + "/" + price);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore potential errors!
}
};
uidRef.addListenerForSingleValueEvent(valueEventListener);
The "date" cannot be read as a String, as it's an object. So the most appropriate way would be to read it as a Map<String, Object>. In this way, you are getting only the bills that correspond to a specific user (logged-in user).

DataSnapshot value of the current user is NULL

I'm trying to get the name and phone for the current user from the Non Member node.But for some reason I'm always getting the value for name and phone to be NULL. I debugged and traced it back to find that the Value of the DataSnapshot for the current user is NULL.
Code :
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("NonMember");
final FirebaseUser Key = firebaseAuth.getCurrentUser();
final String userKey = Key.getUid();
if(firebaseAuth.getCurrentUser() == null){
finish();
startActivity(new Intent(getApplicationContext(), MEMBERMAINActivity.class));
}
myRef.child(userKey).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot){
for (DataSnapshot ds: dataSnapshot.getChildren()){
String name = dataSnapshot.child("name").getValue().toString();
Log.d("TAG", "Name"+ name);
// profile_name.setText(name);
}}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(MyProfile.this, databaseError.getCode(), Toast.LENGTH_SHORT).show();
}
});
The keys you have in the database under "NonMember" are not Firebase Auth user IDs. They look like Realtime Database push IDs, which means you've likely added the user data with something like myRef.push().setValue(...). However, your code is attempting to use a user ID to locate user data. The ID you're getting from Firebase Auth is just not matching the data in the database. If your query doesn't match any data, then it will get a null value in the snapshot.
If you want to store per-user data, don't use a Realtime Database push operation - use the ID of the user, with something like myRef.child(userKey).setValue(...).
for (DataSnapshot ds: dataSnapshot.getChildren()){
String name = ds.child("name").getValue().toString();
Log.d("TAG", "Name"+ name);
// profile_name.setText(name);
}
try this

Android Firebase Fetch Data Of Every User

For example, there are 2 main nodes in my database (there can be more). The parent node is the user's authentication id and inside it
there is some detail as you can see.
I am trying to do that if any user login all other user's data populated on his activity
but I really don't know how to start because every user has its own authentication id and there are sub-nodes also like map location and image
How can I fetch every user's detail to the activity?
What you can do is that get the data from the fbuserinfo node using an event listener like this and iterate through the data. Here User.class is the class for the User model that you have created
DatabaseReference userDataReference = FirebaseDatabase.getInstance().getReference()
.child("fbuserinfo");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
User user = ds.getValue(User.class);
Log.d("User", user);
}
}
}
#Override
public void onCancelled (DatabaseError databaseError){
Log.d(TAG, "Error fetching user data - " + databaseError.getMessage());
}
}
userDataReference.addListenerForSingleValueEvent(eventListener);
And then if you want to display the data, you can do it in the for loop and have an if condition to check if the user is not equal to the current one
Using the following example you'll be able to log the name of all users from your database.
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference fbRef = rootRef.child("Users").child("fbusersinfo");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String name = ds.child("name").getValue(String.class);
Log.d("TAG", name);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
fbRef.addListenerForSingleValueEvent(eventListener);
The output will be:
Ahmend Abbas
mahanoor 4
If you need also the other properties, you can get them in the same manner.

firebase how to get child of child?

so i am stuck. i want to retrieve child of child from my firebase database.
my database struture looks like this
users{
user1{
name:
regno:
carmodel:
caryear}
user2{
name:
regno:
carmodel:
caryear}
user3{
name:
regno:
carmodel:
caryear}}
Regno = car registration number.
when i type in a "carreg no" and press ok. i want the code to search every carreg. if a match is found execute next set of codes.
so far i have tried to store it in a array. but the code seems to fail when i put reg or any variable name that exist.
public void input(){
FirebaseDatabase firebase = FirebaseDatabase.getInstance();
final DatabaseReference table_user = firebase.getReference("User");
table_user.addListenerForSingleValueEvent(
new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Get map of users in datasnapshot
collectPhoneNumbers((Map<String,Object>) dataSnapshot.getValue());
}
#Override
public void onCancelled(DatabaseError databaseError) {
//handle databaseError
}
});
private void collectPhoneNumbers(Map<String,Object> users) {
ArrayList<Long> phoneNumbers = new ArrayList<>();
//iterate through each user, ignoring their UID
for (Map.Entry<String, Object> entry : users.entrySet()){
//Get user map
Map singleUser = (Map) entry.getValue();
//Get phone field and append to list
phoneNumbers.add((Long) singleUser.get("namesd"));
}
System.out.println(phoneNumbers.toString());
mVoiceInputTv.setText("" + phoneNumbers);
}
}
i got this from another stackflow. before this i tried creating a for look. it was successfull but result failed 80% of the time. (not always correct).
To solve this, you need to query your database using orderByChild() method like this:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("users");
Query regnoQuery = usersRef.orderByChild("regno").equalsTo(regno);
In which regno argument from equalsTo() is the the actual registration number that you are looking for. Then attach a listener to the regnoQuery and use getChildrenCount() method on the dataSnapshot object. If the number of childrens is noOfChildrens > 0 then execute the set of codes you need.
private FirebaseDatabase mdatabase;
private DatabaseReference mdatabaseRef;
mdatabase = FirebaseDatabase.getInstance();
mdatabaseRef = mdatabase.getReference();
mdatabaseRef.child("users").child("users1").orderByChild("regno").equalsTo(regno).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
}
}

Categories