Get data from firebase Realtime database - java

I want to get data from firebase in sorted manner, I tried below method but its not working propely and collects all the data.
Here is the image for my firebase database :
DatabaseReference databaseRef = FirebaseDatabase.getInstance().getReference();
String input = "G";
Date cd = Calendar.getInstance().getTime();
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy", Locale.getDefault());
String formattedDate = df.format(cd);
FirebaseUser currentUser = mAuth.getCurrentUser();
DatabaseReference data = databaseRef.child("Data").child(currentUser.getUid()).child(formattedDate.toString()).child(medname.toString());
databaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
List<String> data = new ArrayList<String>();
for (DataSnapshot postSnapshot : snapshot.getChildren()) {
data.add(postSnapshot.getValue().toString());
}
Log.d("datafriebase",""+data);
}
I want to get data in sorted manner, like value of 1, value of 2 but i am getting whole database

You're getting the whole database, because you're reading from databaseRef, which you initialized as:
DatabaseReference databaseRef = FirebaseDatabase.getInstance().getReference();
To get only the nested data, read from data, which you set to reference that path:
DatabaseReference data = databaseRef.child("Data").child(currentUser.getUid()).child(formattedDate.toString()).child(medname.toString());
So:
data.addValueEventListener(new ValueEventListener() {
...

Related

How to get the key of a pushed value

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.

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

My database reference does not show up in the tree

I have a method that I cdreated called getAssignedCustomerLocation that creates a database reference with the variable name assignedCustomerRef but,that database reference does not actually show up in my firebase console. No node is created on the actual console for it. Code below
public void getAssignedCustomerLocation(){
String userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference assignedCustomerRef = FirebaseDatabase.getInstance().getReference().child("customerRequest").child(userId).child("l");
assignedCustomerRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
List<Object> map = (List<Object>) dataSnapshot.getValue();
double locationLat = 0;
double locationLong =0;
if (map.get(0)!=null) {
locationLat= Double.parseDouble(map.get(0).toString());
}
if (map.get(1)!=null){
locationLong = Double.parseDouble(map.get(1).toString());
}
LatLng driverLatLong = new LatLng(locationLat,locationLong);
mMap.addMarker(new MarkerOptions().position(driverLatLong).title("your driver"));
}
}
The code you have used is to read from firebase. If you want to write a new node to the db use below.
String userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference assignedCustomerRef = FirebaseDatabase.getInstance().getReference().child("customerRequest").child(userId).child("l");
assignedCustomerRef.setValue("YOUR_DATA");
To create a node in the database you need to use setValue(), so you can do the following:
DatabaseReference assignedCustomerRef = FirebaseDatabase.getInstance().getReference().child("customerRequest").child(userId);
assignedCustomerRef.child("l").setValue("your driver");

Search data in Firebase | android

I have app and I am using Firebase Realtime database. I need get all data from Search and using this code:
myRef = FirebaseDatabase.getInstance().getReference();
Query query = myRef.orderByChild("Search");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
GenericTypeIndicator<ArrayList<String>> t = new GenericTypeIndicator<ArrayList<String>>(){};
test2 = dataSnapshot.getValue(t);
I need to get it all in ArrayList, but now i am getting below exception
com.google.firebase.database.DatabaseException: Expected a List while
deserializing, but got a class java.util.HashMap
Database structure:
How can I fix this? I need to get all data from Search in ArrayList.
If you need I can post all code from activity and logs.
Json:
{
"Search" : [ "Eggs", "Milk", "Apples", "Carrot", "Sugar", "Potato" ]
}
Assuming that the object node is a direct child of your Firebase database root, to solve this, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference searchRef = rootRef.child("object").child("Search");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<String> list = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String value = ds.getValue(String.class);
list.add(value);
}
Log.d("TAG", list.toString());
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
searchRef.addListenerForSingleValueEvent(valueEventListener);
The output will be:
Eggs
Milk
Apples
Carrot
Sugar
Potato

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