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);
Related
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)
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 a Firebase database which I can read from and write to from my Android App. However, I am having problems with one aspect of the read.
Users can set up an account in the App (Firebase email and password) and are taken to a data input screen and save that information to Firebase using this structure:
myAndroidApp
users
21XKq2RXQYZ36l363msI26XOKdn2
description:
emailAddress:
name:
ownerName:
..... etc.
I have a PropertyData Java Class.
The code for saving the data is:
PropertyData propertyData = new PropertyData(ownerName, headline, description....... etc.);
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
databasePropertyData.child(uid).setValue(propertyData);
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot childSnapShot : dataSnapshot.getChildren()) {
String propNameTxt = (String) childSnapShot.child("name").getValue();
String ownerNameTxt = (String) childSnapShot.child("ownerName").getValue();
So that all seems to work fine and I can log in to different test users and write to the Firebase database.
But what I want is for any existing information in the database to be downloaded and populate the data entry form when the user next signs in. The code I have written does this, but when I sign out of the test account and sign into a different one the data entry form is populated by the previous account!! I thought I was using the Uid correctly but obviously not!
When signed into an account if I change the info in the data entry form it does save it to the correct node. So the problem is with the downloading of existing data on startup.
This is the code for downloading existing data to the data entry form:
databasePropertyData = FirebaseDatabase.getInstance().getReference("users");
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
//FirebaseDatabase.getInstance().getReference().child(uid).addValueEventListener(new ValueEventListener() {
//FirebaseDatabase.getInstance().getReference().child("users").child(uid).addValueEventListener(new ValueEventListener() {
FirebaseDatabase.getInstance().getReference().child("users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot childSnapShot : dataSnapshot.getChildren()) {
String propNameTxt = (String) childSnapShot.child("name").getValue();
String ownerNameTxt = (String) childSnapShot.child("ownerName").getValue();
String headlineTxt = (String) childSnapShot.child("headline").getValue();
String descriptionTxt = (String) childSnapShot.child("description").getValue();
....... etc.
I have tried different variations on the listener without success. Any help/suggestions appreciated.
You cannot use child("users" + uid). To solve this, you have two options:
.child("users").child(uid)
or
child("users/" + uid)
Remember, every node in a Firebase database has it's url.
In order to get the from a single authenticated user, you don't need use getChildren() method. You also don't need to use addValueEventListener, you only need to use addListenerForSingleValueEvent. Please see the following code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("users").child(uid);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String propNameTxt = dataSnapshot.child("name").getValue(String.class);
String ownerNameTxt = dataSnapshot.child("ownerName").getValue(String.class);
String headlineTxt = dataSnapshot.child("headline").getValue(String.class);
String descriptionTxt = dataSnapshot.child("description").getValue(String.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
uidRef.addListenerForSingleValueEvent(eventListener);
You set the database accurate address till where you want to get all the elements on databaseReference as you want. Then get the specific element you want to be store by its unique key Ex :- dataSnapshot.child("name").getValue().toString(); i hope it will help you else reply what you have confusion about firebase connectivity.
private String CurrentUserID;
private DatabaseReference databaseReference
//Outside of Oncreate for user Detection
#Override
protected void onStart(){
super.onStart();
mAuth.addAuthStateListener(mauthListener);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
mAuth = FirebaseAuth.getInstance();
mauthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser() != null){
CurrentUserID = firebaseAuth.getCurrentUser().getUid();
}
databaseReference = FirebaseDatabase.getInstance().getReference().getRoot().child("myAndroidApp").child("users").child(CurrentUserID);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String propNameTxt = dataSnapshot.child("name").getValue().toString();
String ownerNameTxt = dataSnapshot.child("ownerName").getValue().toString();
String headlineTxt = dataSnapshot.child("headline").getValue().toString();
String descriptionTxt = dataSnapshot.child("description").getValue().toString();
}
}
}
First of all use ...child("users/" + uid)... instead of ...child("users" + uid).... Because you will get the child "users21XKq2RXQYZ36l363msI26XOKdn2".
Second:
for(DataSnapshot childSnapShot : dataSnapshot.getChildren()) in your listener already gets child one by one in "users/21XKq2RXQYZ36l363msI26XOKdn2". So right now you are trying to get the value of "users/21XKq2RXQYZ36l363msI26XOKdn2/name/name", "users/21XKq2RXQYZ36l363msI26XOKdn2/description/name" and others. I offer you than do it without for cycle.
Like this:
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String propNameTxt = (String) dataSnapshot.child("name").getValue();
String ownerNameTxt = (String) dataSnapshot.child("ownerName").getValue();
String headlineTxt = (String) dataSnapshot.child("headline").getValue();
String descriptionTxt = (String) dataSnapshot.child("description").getValue();
}
Also you can create data class with setters and getters for these parameters (name, ownerName, headline, description) and use it to get all data.
Like this:
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
MyData data = (MyData) dataSnapshot.getValue(MyData.class);
}
Then you can get your field value using getter: data.getName(). I am offering setters and getters because you can insert there some validation.
If you are using data class for Firebase make sure it has an empty constructor.
More about it in my other answer: https://stackoverflow.com/a/48868970/5272951
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've written an android app using Firebase as the backend. My problem is only one item can be stored in Firebase and when I try to write more data it replaces the existing data. I want to write multiple bits and data and retrieve them in a list view or something.
My Code is below:
public class Capture_Meetings extends AppCompatActivity {
private EditText editTextName;
private EditText editTextAddress;
private EditText editDateTime;
private TextView textViewPersons;
private Button buttonSave;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_capture__meetings);
Firebase.setAndroidContext(this);
buttonSave = (Button) findViewById(R.id.buttonSave);
editTextName = (EditText) findViewById(R.id.editTextName);
editTextAddress = (EditText) findViewById(R.id.editTextAddress);
editDateTime = (EditText) findViewById(R.id.editDateTime);
textViewPersons = (TextView) findViewById(R.id.textViewPersons);
buttonSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Creating firebase object
Firebase ref = new Firebase(Config.FIREBASE_URL);
//Getting values to store
String name = editTextName.getText().toString().trim();
String address = editTextAddress.getText().toString().trim();
String DateTime = editDateTime.getText().toString().trim();
//Creating Person object
final MeetingUser person = new MeetingUser();
//Adding values
person.setName(name);
person.setAddress(address);
person.setDateTime(DateTime);
//Storing values to firebase
ref.child("Person").setValue(person);
//Value event listener for realtime data update
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot)
{
for (DataSnapshot postSnapshot : snapshot.getChildren()) {
//Getting the data from snapshot
MeetingUser person = postSnapshot.getValue(MeetingUser.class);
//Adding it to a string
String string = "\n Name of School: "+person.getName()+"\n Date:"+ person.getDateTime()+"\nMeeting Notes: "+person.getAddress()+"\n\n";
//Displaying it on textview
textViewPersons.setText(string);
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
System.out.println("The read failed: " + firebaseError.getMessage());
}
});
}
});
}
Have a look at the Firebase documentation. You can use the push method to append data to a node, which will have a unique id.
in Firebase you can not store many items/values under one child. But, you can make as many childs (children) with a single value as you want. Just make childs with tags s.a. "address" and "name" with their respective values.
To avoid overwriting of data we can use push() method in following way-
from your code -
ref.child("Person").setValue(person);
just put push() before setValue() method, that is -
ref.child("Person").push().setValue(person);
It will avoid overwriting and it will create a unique id for each data you store under the Person.