how can I list users who logged in on the day? I have a field in the firebase where the date and time is saved. but I'm interested in filtering a search based on the current day based on the device's date using data saved in firebaserealtime? could someone tell me how can i filter using these requirements?
thanks in advance.
code to save datatime in database.
//DataDia
usuarioAtual = UsuarioFirebase.getUsuarioAtual();
final DatabaseReference firebaseRef = ConfiguracaoFirebase.getFirebaseDatabase();
DatabaseReference usuario = firebaseRef.child("usuarios").child(getIdentificadorUsuario() );
final String userId = user.getUid();
firebaseRef.child("usuarios").child(userId).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
}
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
String strDate = dateFormat.format(date).toString();
firebaseRef.child("usuarios").child(getIdentificadorUsuario()).child("DataDia").setValue(strDate);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
code for search users
usuariosRef = ConfiguracaoFirebase.getFirebaseDatabase().child("usuarios");
database structure
To get all users for a specific date, you'll need to:
Construct a string with that date in the format that you have it stored in the database.
Then run a query with that string against the property.
So something like:
firebaseRef.child("usuarios") // Note that there's no .child(userId) here anymore
.orderByChild("DataDia").equalTo("2020/10/15")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
Log.i("DB", ds.getKey());
Log.i("DB", ds.child("DataDia").getValue(String.class));
}
}
...
I think you can use equalTo from documentation
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
Date date = YOUR_INPUT_DATE;
String strDate = dateFormat.format(date).toString();
usuariosRef = ConfiguracaoFirebase.getFirebaseDatabase().child("usuarios");
Query q = usuariosRef.equalTo(strDate)
Related
The user is creating the data based on the date he chose. So I use the date to separate it so the user can store the data based on the date. The problem is I want to retrieve all the data and put it all in the listview and show when the app is starting. But I cannot reach the child file which is the date file. So is that anyway I can retrieve all the data inside the user but did not point to the child file?
DatabaseReference reference= FirebaseDatabase.getInstance().getReference("user");
Query checkUser = reference.orderByChild("userid").equalTo(uid);
checkUser.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
String dateFromDB= dataSnapshot.child(uid).child("date").getValue(String.class);
String weightFromDB= dataSnapshot.child(uid).child("weight").getValue(String.class);
Intent intent = new Intent(getApplication(), Menu.class);
intent.putExtra("date", dateFromDB);
intent.putExtra("weight", weightFromDB);
startActivity(intent);
}
}
I try to use this code to retrieve but it returns a null value.
This is how you retrieve the data:
You will have to loop through all the dates IDs and extract the data
DatabaseReference reference= FirebaseDatabase.getInstance().getReference("user");
ValueEventListener listener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//loop through all the dates
for(DataSnapshot ds: dataSnapshot.getChildren()){
//get the data of all the dates
String date= ds.child("date").getValue(String.class);
String weight= ds.child("weight").getValue(String.class);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
}
};
reference.child(uid).addValueEventListener(listener);
I have this firebase structure:
I am trying to retrieve data under the key FA16-BCS-B16-B-MONDAY. What I am getting is:
where line 4,5,6 doesn't include in the FA16-BCS-B16-B-MONDAY, but in other category.
the code i have tried till now is:
final DatabaseReference childRef = FirebaseDatabase.getInstance().getReference().child("TimeTable");//.child("FA16-BCS-B16-B-MONDAY");
//adding listener
childRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Iterable<DataSnapshot> snapshotIterator = dataSnapshot.getChildren();
Iterator<DataSnapshot> iterator = snapshotIterator.iterator();
adapter.clear();
teacher.clear();
while (iterator.hasNext() ) {
DataSnapshot next = iterator.next();
String course= next.child("course").getValue().toString();
String teacher= next.child("teacher").getValue().toString();
String time= next.child("time").getValue().toString();
String key = next.getKey();
//teacher.add(key);
adapter.add(course+"\t"+teacher+"\t"+time);}
listview.setAdapter(adapter);
}
I don't know why the data of other children is being retrieved. If I use
final DatabaseReference childRef = FirebaseDatabase.getInstance().getReference().child("TimeTable").child("FA16-BCS-B16-B-MONDAY");
it retrieves only one result. Please help me figure this out. Thanks
If you want to retrieve only a single child node from the time table, you need to remove the loop from your onDataChange. So something like:
final DatabaseReference childRef = FirebaseDatabase.getInstance().getReference()
.child("TimeTable").child("FA16-BCS-B16-B-MONDAY");
//adding listener
childRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
adapter.clear();
teacher.clear();
String course = dataSnapshot.child("course").getValue().toString();
String teacher = dataSnapshot.child("teacher").getValue().toString();
String time= dataSnapshot.child("time").getValue().toString();
String key = dataSnapshot.getKey();
System.out.println(key+": "+course+", "+teacher+", "+time);
adapter.add(course+"\t"+teacher+"\t"+time);}
listview.setAdapter(adapter);
}
Update
To read all timetables, you can listen one level higher in the tree and then loop over the child nodes you get back:
final DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("TimeTable");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
adapter.clear();
teacher.clear();
for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
String course = childSnapshot.child("course").getValue().toString();
String teacher = childSnapshot.child("teacher").getValue().toString();
String time= childSnapshot.child("time").getValue().toString();
String key = childSnapshot.getKey();
System.out.println(key+": "+course+", "+teacher+", "+time);
adapter.add(course+"\t"+teacher+"\t"+time);}
});
listview.setAdapter(adapter);
}
I am trying to store all children of my firebase database into an array list.
Here is my database structure:
I am currently trying to loop through children in order to get the values I need as follows:
private void initializeData(int Destination) {
listItems = new ArrayList<>();
DatabaseReference MyRef = FirebaseDatabase.getInstance().getReference("rideShare");
switch (Destination) {
case 0:
Toast.makeText(getActivity(), "LA BUNDLE", Toast.LENGTH_SHORT).show();
MyRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
for(DataSnapshot snapshot : dataSnapshot.getChildren()) {
String NameValue = snapshot.child("Name").getValue(String.class);
String Price = snapshot.child("Price").getValue(String.class);
String Type = snapshot.child("Trip Type").getValue(String.class);
String Date = snapshot.child("Date").getValue(String.class);
String Destination = "LA";
String Phone = snapshot.child("Phone Number").getValue(String.class);
listingItem newItem = new listingItem(NameValue, Type, Price, Date, Destination, Phone);
listItems.add(newItem);
}
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
//Log.w(TAG , "Failed to read value.",error.toException());
}
});
break;
}
}
Add all the string variables into a POJO class and name the variables same as the child nodes keys. Use snapshot.get(listingItem.class) directly instead.
Refer to this https://stackoverflow.com/a/39861649/3860386
To get those values, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference rideShareRef = rootRef.child("rideShare");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<ListingItem> listItems = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String nameValue = ds.child("Name").getValue(String.class);
String type = ds.child("Trip Type").getValue(String.class);
String price = ds.child("Price").getValue(String.class);
String date = ds.child("Date").getValue(String.class);
String destination = "LA";
String phone = ds.child("Phone Number").getValue(String.class);
ListingItem newItem = new ListingItem(nameValue, type, price, date, destination, phone);
listItems.add(newItem);
}
Log.d("TAG", listItems);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
rideShareRef.addListenerForSingleValueEvent(eventListener);
When you are writting Java code, it's better to use Java Naming conventions. I added this code accordingly.
Also as you probaly see, i have added the declaration of listItems inside onDataChange() method, otherwise it will alwasy be null due the asynchronous behaviour of this method.
I have a problem several days ago and I don't find a solution.
I´m trying search in my firebase database by name but the result is always null.
The database is the next;
The code that I use is the next;
final String nombre = edtNombreJugador.getText().toString().trim().toUpperCase();
mDatabase.child("user").child("personalData").orderByChild("name").equalTo(nombre);
mDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
String title = (String) singleSnapshot.child("name").getValue(String.class);
System.out.println("TITLE: "+title);
}
Title always return null in my case.
Can somebody help me please? I don't know what I'm doing bad...
Right now you're querying the database path /user/personalData. And then for each child node under there, you're comparing the name property to the value the user entered. So /user/personalData/***/name.
That doesn't match the path in the database, which is /user/***/personalData/name. To query that you do:
Query query = mDatabase.child("user").orderByChild("personalData/name").equalTo(nombre);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {...
Im trying too with this code (more clear for me) for return all names in database but the result is null too:
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference("/users/");
mDatabase.child("personalData");
final UsersData[] user = {null};
ValueEventListener postListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
String title = (String)
postSnapshot.child("name").getValue(String.class);
System.out.println("TITLE: "+title);
}
}
#Override
public void onCancelled(DatabaseError firebaseError) {
Log.e("The read failed: " ,firebaseError.getMessage());
}
};
mDatabase.addValueEventListener(postListener);
The retrieve time should be display below the Time textview
I want to fetch the stored time and display it user.
How to do it?
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("user_time_table");
myRef.child("Y71VckCvTPVyqLCtrSQNHRiThsc2").child("Mondey").child("time").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String time = dataSnapshot.getValue(String.class);
myEditText.setText(time);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
This is hardcoded solution. If you want to make it more flexible, you can change "Y71VckCvTPVyqLCtrSQNHRiThsc2" to current user's id, for example:
FirebaseUser user = firebaseAuth.getCurrentUser();
String id = user.getUid();
and then use this id instead of hardcoded String.
String x = String.valueOf(drposts.getTime());
long milliSeconds= Long.parseLong(x);
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
String dateAsString = sdf.format (milliSeconds);
myEditText.setText(dateAsString );
//first convert the time value in string and store into it long after that
//define the simple date format and store it again in string and pass it text view
//drposts is my object class u an use
//String x = dataSnapshot.getValue(String.class);