'Save current date and user Input to Firebase Firestore
I am making a note-saving app using Firebase Firestore and a RecyclerView.
So far users are able to enter the title and content of the note, this saves and works fine.
What I would like to add is the current date (in a "dd/MM/yy" format) when the user saves the note to be displayed in the recycler view the notes are displayed in.
My code for adding the note is as follows
public class AddWellbeingActivity extends AppCompatActivity {
private static final String TAG = "AddWellbeingActivity";
EditText createtitleofnote, createcontentofnote;
FloatingActionButton savenote;
FirebaseAuth firebaseAuth;
FirebaseUser firebaseUser;
FirebaseFirestore firebaseFirestore;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_wellbeing);
savenote = findViewById(R.id.saveNote);
createcontentofnote = findViewById(R.id.createContentNote);
createtitleofnote = findViewById(R.id.createTitleNote);
firebaseAuth = FirebaseAuth.getInstance();
firebaseFirestore = FirebaseFirestore.getInstance();
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
savenote.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String title = createtitleofnote.getText().toString();
String content = createcontentofnote.getText().toString();
if(title.isEmpty() || content.isEmpty())
{
Toast.makeText(getApplicationContext(), "Both fields are Required", Toast.LENGTH_SHORT).show();
}
else
{
DocumentReference documentReference = firebaseFirestore.collection("notes").document(firebaseUser.getUid()).collection("myNotes").document();
Map<String, Object> note = new HashMap<>();
note.put("title",title);
note.put("content", content);
documentReference.set(note).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid)
{
Toast.makeText(getApplicationContext(), "Wellbeing entry saved", Toast.LENGTH_SHORT).show();
startActivity(new Intent(AddWellbeingActivity.this, WellbeingActivity.class));
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e)
{
Toast.makeText(getApplicationContext(), "Wellbeing entry failed to save", Toast.LENGTH_SHORT).show();
}
});
}
}
});
}
If anyone has a solution it would be greatly appreciated
Solution 1:[1]
To add a timestamp field when add a note into Firestore, then you should add an extra put() call:
note.put("title",title);
note.put("content", content);
note.put("date", FieldValue.serverTimestamp()); ?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Alex Mamo |
