Android - Firebase - Save new Data without overwriting old Data - java

This Question was created as my previous question contained 2 question instead of narrowing it down to 1
Aim
Users will be able to store new data without overwriting their previously submitted data
Description
Currently, the User's Incident Report data within the Incident Report node will be overwritten when the User enters a new Report.
The Data from the old Incident Report sent by the user should be kept along with the new data.
This way the authorities will be able to view the previous reports and also the new report data.
Problem
Everytime a the currently signed in user saves a "Report", the New report data will overwrite the Old report data
Codes for Saving Data
private void submitReport(final String userReportDate,final String userReportTime,
final String userReportLocation,final String userReportDescription) {
jReportCurrentUserID = FirebaseAuth.getInstance().getCurrentUser();
final String reportUserID = jReportCurrentUserID.getUid();
jReportByUserDatabase = FirebaseDatabase.getInstance().getReference().child("Incident Reports").child(reportUserID);
HashMap<String, String> incidentReportUser = new HashMap<>();
incidentReportUser.put("date", userReportDate);
incidentReportUser.put("time", userReportTime);
incidentReportUser.put("location", userReportLocation);
incidentReportUser.put("description", userReportDescription);
jReportByUserDatabase.setValue(incidentReportUser).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
jReportLoad.dismiss();
Toast.makeText(getActivity(), "Report was Sent", Toast.LENGTH_SHORT).show();
jReportDatePick.setText("");
jReportTimeEnt.setText("");
jReportLocationEnt.setText("");
jReportDescriptionEnt.setText("");
}else{
jReportLoad.dismiss();
Toast.makeText(getActivity(), "Report failed to be sent", Toast.LENGTH_SHORT).show();
}
}
});
}

jReportByUserDatabase.push().setValue(incidentReportUser)
Write it this way (push() adds values instead of overriding).

See push documentation
Note that your all your reports will now be stored one level down under a unique key created by .push()
private void submitReport(final String userReportDate,final String userReportTime,
final String userReportLocation,final String userReportDescription) {
jReportCurrentUserID = FirebaseAuth.getInstance().getCurrentUser();
final String reportUserID = jReportCurrentUserID.getUid();
jReportByUserDatabase = FirebaseDatabase.getInstance().getReference().child("Incident Reports").child(reportUserID).push();
DatabaseReference newReport = jReportByUserDatabase.push();
HashMap<String, String> incidentReportUser = new HashMap<>();
incidentReportUser.put("date", userReportDate);
incidentReportUser.put("time", userReportTime);
incidentReportUser.put("location", userReportLocation);
incidentReportUser.put("description", userReportDescription);
newReport.setValue(incidentReportUser).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
jReportLoad.dismiss();
Toast.makeText(getActivity(), "Report was Sent", Toast.LENGTH_SHORT).show();
jReportDatePick.setText("");
jReportTimeEnt.setText("");
jReportLocationEnt.setText("");
jReportDescriptionEnt.setText("");
}else{
jReportLoad.dismiss();
Toast.makeText(getActivity(), "Report failed to be sent", Toast.LENGTH_SHORT).show();
}
}
});
}

Related

How do I push my data (in key:value pair) into my Firebase realtime database in android?

I want to push my data (in key:value pair) into my Realtime Database. This is my code:
DatabaseReference pay_details = database.getReference("pay/0/0/");
pay_details.push(
{
"Actual amount":arr.get(i).get(9),
"Current reading":arr.get(i).get(5),
"Employee":arr.get(i).get(1),
"Expected amount":arr.get(i).get(9),
"Installment":arr.get(i).get(10),
"Meter current date":arr.get(i).get(3),
"Meter previous date":arr.get(i).get(2),
"Previous reading":arr.get(i).get(4),
"Start from":arr.get(i).get(8),
"Total charge":arr.get(i).get(7),
"Type":arr.get(i).get(0),
"Unit consumed":arr.get(i).get(6)
}
);
This is my table structure:
I keep getting multiple syntax errors in the push section. Where am I going wrong?
The best way to send/store data in real-time database is to create an object of
Hashmap. Below is the code to achieve this objective
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
HashMap<String, Object> data = new HashMap<>();
data.put("Actual amount", Your actual amount);
data.put("Current reading", Your current reading);
data.put("Employee", Employee name);
databaseReference.child("The child name")
.updateChildren(data)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
Log.d("TAG", "Data added successfully");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d("TAG", "Failed " + e.getMessage());
}
});
The add data to the Realtime Database you need to use setValue() method. In code
DatabaseReference pay_details = database.getReference("pay/0/0/");
HashMap<String, Object> map = new HashMap<>();
map.put("fieldName", "fieldValue");
pay_details.setValue(map).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "Data added successfully.");
} else {
Log.d(TAG, task.getException().getMessage()); //Never ignore potential errors!
}
}
});
If you want to add multiple children, then you can also use push().

How to set users name in firebase realtime-database

When i am creating new account its name equals users UID is there anyway to change it to custom name?
My code
mAuth.createUserWithEmailAndPassword(Email, Password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
User user = new User(Name, LastName, Email);
curentUser = Name + " " + LastName;
FirebaseDatabase.getInstance().getReference("No server")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(MainActivity.this, "User has been registered successfully!", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(MainActivity.this,"Failed to register! try again!", Toast.LENGTH_LONG).show();
}
}
});
}else{
Toast.makeText(MainActivity.this,"Failed to register! try again!", Toast.LENGTH_LONG).show();
}
}
});
How it looks like
You can't change the key of an existing value in Firebase Realtime Database without reading the value, write it under a new key, and delete the old one.
That being said, you chose the key of the user object yourself:
FirebaseDatabase
.getInstance().getReference()
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.setValue(user)
The child method contains the key for the value you set in setValue. And you use the current user's UID for this.
You can change this to whatever value you like. For example, you could the user's email as a key (see reference for current user object):
.child(FirebaseAuth.getInstance().getCurrentUser().getEmail())
Note: See the comment from #puf below, you might want to encode an email address when using as a key.

How to check if email was already used in firebase? [duplicate]

I want to check when a user attempts to signup with createUserWithEmailAndPassword() in Firebase user Authentication method, this user is already registered with my app.
To detect whether a user with that email address already exists, you can detect when the call to createUserWithEmailAndPassword () fails with auth/email-already-in-use. I see that #Srinivasan just posted an answer for this.
Alternatively, you can detect that an email address is already used by calling fetchSignInMethodsForEmail().
The usual flow for this is that you first ask the user to enter their email address, then call fetchSignInMethodsForEmail, and then move them to a screen that either asks for the rest of their registration details (if they're new), or show them the provider(s) with which they're signed up already.
When the user trying to create an user with same email address, the task response will be "Response: The email address is already in use by another account."
mFirebaseAuth.createUserWithEmailAndPassword(email,password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
//User registered successfully
}else{
Log.i("Response","Failed to create user:"+task.getException().getMessage());
}
}
});
First of all, you need to make sure you have that restriction enabled in Firebase console (Account and email address settings). Take a look at #Srinivasan's answer.
Then, do this in your java code:
firebaseAuthenticator.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
if (task.getException() instanceof FirebaseAuthUserCollisionException) {
Toast.makeText(SignUpActivity.this, "User with this email already exist.", Toast.LENGTH_SHORT).show();
}
} else {
sendVerificationEmail();
startActivity(new Intent(SignUpActivity.this, DetailsCaptureActivity.class));
}
// ...
}
});
This is where the trick happens:
if (task.getException() instanceof FirebaseAuthUserCollisionException) {
Toast.makeText(SignUpActivity.this,
"User with this email already exist.", Toast.LENGTH_SHORT).show();
Several exceptions can be thrown when registering a user with email and password, but the one we are interested in is the FirebaseAuthUserCollisionException. As the name implies, this exception is thrown if the email already exists. If the exception thrown is an instance of this class, let the user know.
As a practice of #Frank's answer here is the code of using fetchProvidersForEmail()
private boolean checkAccountEmailExistInFirebase(String email) {
FirebaseAuth mAuth = FirebaseAuth.getInstance();
final boolean[] b = new boolean[1];
mAuth.fetchProvidersForEmail(email).addOnCompleteListener(new OnCompleteListener<ProviderQueryResult>() {
#Override
public void onComplete(#NonNull Task<ProviderQueryResult> task) {
b[0] = !task.getResult().getProviders().isEmpty();
}
});
return b[0];
}
I was looking into this kind of condition where we can detect if user exists or not and perform registration and login. fetchProvidersForEmail is best option right now. I have found this tutorial. Hope it helps you too!
See : Manage Users
UserRecord userRecord = FirebaseAuth.getInstance().getUserByEmail(email);
System.out.println("Successfully fetched user data: " + userRecord.getEmail());
This method returns a UserRecord object for the user corresponding to the email provided.
If the provided email does not belong to an existing user or the user cannot be fetched for any other reason, the Admin SDK throws an error. For a full list of error codes, including descriptions and resolution steps, see Admin Authentication API Errors.
private ProgressDialog progressDialog;
progressDialog.setMessage("Registering, please Wait...");
progressDialog.show();
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
//checking if success
if (task.isSuccessful()) {
//Registration was successfull:
Toast.makeText(RegistrationActivity.this, "Successfully registered!", Toast.LENGTH_LONG).show();
} else {
//Registration failed:
//task.getException().getMessage() makes the magic
Toast.makeText(RegistrationActivity.this, "Registration failed! " + "\n" + task.getException().getMessage(), Toast.LENGTH_LONG).show();
}
progressDialog.dismiss();
}
});
Add below code to MainActivity.java file.When user attempt to register with the same email address a message "The email address is already used by another account" will pop up as a Toast
mAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(!task.isSuccessful()){
Toast.makeText(MainActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
if(task.isSuccessful()){
Toast.makeText(MainActivity.this, "Sign up successfull", Toast.LENGTH_SHORT).show();
}
}
});
You do not have to do anything because the backend of Firebase will do the job.
Unless you are referring to reauthenticating of the app.
Take a scenario for an example, w

How to change document in Firestore without String error?

In my app a first time user creates a username which I save in Firestore as a document and set it as displayName (username = name of document = displayName). In the app the user has the option to change his username by typing a new one in an EditText. The result should be that the data which is stored under his current username moves to a new document which has the new username. So first I check if the new username is already in use by someone else, if not I create a new document which name is the new username. Now I get the current displayName (which is the current username) as a string and the input of the EditText as a string (new username). I Implemented a method to move documents from here: How to move a document in Cloud Firestore?
But when I call the method like this moveFirestoreDocument(usernameInput, oldUsername ); I get:
moveFirestoreDocument cannot be applied to (String, String)
How can I resolve this problem? Can I change the moveFirestoreDocument method so it can also takes Strings?
Here is the method:
public void moveFirestoreDocument(DocumentReference fromPath, final DocumentReference toPath) {
fromPath.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document != null) {
toPath.set(document.getData())
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "DocumentSnapshot successfully written!");
fromPath.delete()
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "DocumentSnapshot successfully deleted!");
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "Error deleting document", e);
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "Error writing document", e);
}
});
} else {
Log.d(TAG, "No such document");
}
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});
}
You get the following error:
I get "moveFirestoreDocument cannot be applied to (String, String)
Because you are trying to pass to the moveFirestoreDocument() method two arguments of type String and not of type DocumentReference. In order to be able to move a document, both fromPath and toPath must be of type DocumentReference so you can call set() on toPath and get() and delete() on fromPath.
Can I change the moveFirestoreDocument method so it can also takes Strings?
There is no need to change the method, you can simply pass the correct arguments when you call it. According to the details that you have provided in the question, I understand that you have a schema that is similar to this:
Firestore-root
|
--- users (collection)
|
--- John (document)
|
--- //User details
To rename the document call the method using:
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference usersRef = rootRef.collection("users");
DocumentReference oldUsernameRef = usersRef.document(oldUsername);
DocumentReference usernameInputRef = usersRef.document(usernameInput);
moveFirestoreDocument(oldUsernameRef, usernameInputRef);

How Should I fetch the document fields and use them in another map for another collection?

How should I fetch the document fields from one collection and combine them to add a new document to another collection? I have attached picture of the database how does it looks, I want to fetch the fields from the collection show and want to update it to the new collection along with some other data:
private void savePost(String mPostTitle, String mPostContent, String mlistSpinnerC) {
final DocumentReference docRef = FirebaseFirestore.getInstance().collection("users").document(mauth.getCurrentUser().getUid());
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document != null) {
String username = (String)
document.get("username");
String email= (String) document.get(email);
} else {
Log.d(TAG, "No such document");
}
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});
postMap.put(Constants.POSTTTITLE, mPostTitle);
postMap.put(Constants.POSTCATEGORY, mlistSpinnerC);
postMap.put(Constants.POSTCONTENT, mPostContent);
postMap.put(Constants.TIMESTAMP, (System.currentTimeMillis()/1000));
postMap.put(Constants.USER_ID,mauth.getCurrentUser().getUid());
postMap.put("username", username);
PostsRef.document().set(postMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Intent toHomeActivity = new Intent(AddPostActivity.this, MainActivity.class);
startActivity(toHomeActivity);
}
}
});
I am just not able to map the fields from one collection to another collection, please guide me the correct method to that.
By the time you are trying to add the username to your postMap using the following line of code:
postMap.put("username", username);
The data has not finished loading yet from the database and this is because the listener you have added to your get() call is being invoked some unknown amount of time later after your query finishes. You don't know how long it's going to take, it may take from a few hundred milliseconds to a few seconds before that data is available. The onComplete() method has an asynchronous behavior, that's why you cannot get that username in such a way.
A quick solve for this problem would be to move all that block of code related to adding data to the postMap, inside the onComplete() method. In this you are waiting for the callback and username your will be available. Otherwise I recommend you see the last part of my anwser from this post in which I have explained how it can be done using a custom callback. You can also take a look at this video for a better understanding.

Categories

Resources