I have a user model with some fields which I try to update. However, when I edit a user's password or email, my user model in firebase storage remains the same, whereas the firebase auth updates correctly.
here is my update user method
private void updateUser() {
String mFullName = editFullName.getText().toString().trim();
String mEmail = editEmail.getText().toString().trim();
String mPhone = editPhone.getText().toString().trim();
String mPassword = editPassword.getText().toString().trim();
if(isFullNameChanged(mFullName)){
user.setFullName(mFullName);
}
if(isPhoneChanged(mPhone)){
user.setPhone(mPhone);
}
if(isEmailChanged(mEmail)){
currentUser.updateEmail(mEmail)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
System.out.println("Email successful " + mEmail);
user.setEmail(mEmail);
System.out.println("Email successful " + mEmail + " " + user.getEmail());
}
else{
Toast.makeText(editProfile.this, "Email update error, re-authentication required", Toast.LENGTH_SHORT).show();
}
}
});
}
if(isPasswordChanged(mPassword)){
currentUser.updatePassword(mPassword)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
System.out.println("Password successful");
user.setPassword(mPassword);
}
else{
Toast.makeText(editProfile.this, "Password update error, re-authentication required", Toast.LENGTH_SHORT).show();
}
}
});
}
userReference.child(currentUser.getUid()).setValue(user);
System.out.println("My current email: " + currentUser.getEmail() + " " + user.getEmail());
Toast.makeText(editProfile.this, "Profile update successful", Toast.LENGTH_SHORT).show();
}
user model
public class User {
String fullName, password, email, date, phone, imageUri;
public User(){
}
public User(String mFullName, String mEmail, String mPassword, String mPhone, String mDate, String mImageUri){
this.fullName = mFullName;
this.email = mEmail;
this.password = mPassword;
this.phone = mPhone;
this.date = mDate;
this.imageUri = mImageUri;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getImageUri() {
return imageUri;
}
public void setImageUri(String imageUri) {
this.imageUri = imageUri;
}
}
I don't know why, but in completeListener functions, my user changes the field, but when I get out of it the user has no changes at all. I tried to figure it out but didn't find anything
This is because you are not updating the email and password in the model when updating in Auth. Try this code:
private void updateUser() {
String mFullName = editFullName.getText().toString().trim();
String mEmail = editEmail.getText().toString().trim();
String mPhone = editPhone.getText().toString().trim();
String mPassword = editPassword.getText().toString().trim();
if(isFullNameChanged(mFullName)){
user.setFullName(mFullName);
}
if(isPhoneChanged(mPhone)){
user.setPhone(mPhone);
}
if(isEmailChanged(mEmail)){
user.setEmail(mEmail);
currentUser.updateEmail(mEmail)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
System.out.println("Email successful " + mEmail);
user.setEmail(mEmail);
System.out.println("Email successful " + mEmail + " " + user.getEmail());
}
else{
Toast.makeText(editProfile.this, "Email update error, re-authentication required", Toast.LENGTH_SHORT).show();
}
}
});
}
if(isPasswordChanged(mPassword)){
user.setPassword(mPassword);
currentUser.updatePassword(mPassword)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
System.out.println("Password successful");
user.setEmail(mPassword);
}
else{
Toast.makeText(editProfile.this, "Password update error, re-authentication required", Toast.LENGTH_SHORT).show();
}
}
});
}
userReference.child(currentUser.getUid()).setValue(user);
System.out.println("My current email: " + currentUser.getEmail() + " " + user.getEmail());
Toast.makeText(editProfile.this, "Profile update successful", Toast.LENGTH_SHORT).show();
}
Related
how to find if the user's mail id, name, password already exists in signin functionality. I checked that it shows 400 bad request if the user giving same name, mail, password. so now how to display it in toast that user is already registered. I don't know whether response code and status code is equal or not
check my code.
public class RegisterActivity extends AppCompatActivity {
private static final String TAG = "Register Activity";
private EditText registerFullName, registerEmailAddress, registerPhoneNumber, registerPassword, registerRePassword;
private CheckBox signUpCheckBox;
private static final Pattern PASSWORD_PATTERN =
Pattern.compile("^" +
"(?=.*[0-9])" + //at least 1 digit
// "(?=.*[a-z])" + //at least 1 lower case letter
// "(?=.*[A-Z])" + //at least 1 upper case letter
"(?=.*[a-zA-Z])" + //any letter
"(?=.*[##$%^&+=])" + //at least 1 special character
"(?=\\S+$)" + //no white spaces
".{8,}" + //at least 8 characters
"$");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_register);
// final String email;
registerFullName = (EditText) findViewById(R.id.registerFullName);
registerEmailAddress = (EditText) findViewById(R.id.registerEmailAddress);
registerPhoneNumber = findViewById(R.id.registerPhoneNumber);
registerPassword = (EditText) findViewById(R.id.registerPassword);
registerRePassword = findViewById(R.id.registerRePassword);
signUpCheckBox = findViewById(R.id.signUpCheckBox);
TextView back2Login = (TextView) findViewById(R.id.registerBack2Login);
ImageView registerBackBtn = (ImageView) findViewById(R.id.registerBackBtn);
RelativeLayout relativeLayout = findViewById(R.id.signUplayout);
relativeLayout.scheduleLayoutAnimation();
registerPassword.setTransformationMethod(new PasswordTransformationMethod());
registerRePassword.setTransformationMethod(new PasswordTransformationMethod());
// registerPassword.setTransformationMethod(new HideReturnsTransformationMethod());
// registerRePassword.setTransformationMethod(new HideReturnsTransformationMethod());
registerBackBtn.setOnClickListener(v -> {
Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
startActivity(intent);
finish();
});
back2Login.setOnClickListener(v -> {
Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
startActivity(intent);
finish();
});
}
private void Usersignup() {
String email = registerEmailAddress.getText().toString().trim();
String name = registerFullName.getText().toString().trim();
String password = registerPassword.getText().toString().trim();
if (registerFullName.getText().toString().trim().isEmpty()) {
registerFullName.setError("Username is required");
registerFullName.requestFocus();
return;
}else {
registerFullName.setError(null);
}
if (registerPhoneNumber.getText().toString().trim().isEmpty()) {
registerPhoneNumber.setError("Field Can't be Empty");
registerFullName.requestFocus();
return;
}else{
registerPhoneNumber.setError(null);
}
if (email.isEmpty()) {
registerEmailAddress.setError("Email is required");
registerEmailAddress.requestFocus();
return;
}else {
registerEmailAddress.setError(null);
}
if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
registerEmailAddress.setError("Invalid emailaddress");
registerEmailAddress.requestFocus();
return;
}
if (name.isEmpty()) {
registerFullName.setError("Name is required");
registerFullName.requestFocus();
return;
}else {
registerFullName.setError(null);
}
if (password.isEmpty()) {
registerPassword.setError("Enter the password");
registerPassword.requestFocus();
return;
}else if(!PASSWORD_PATTERN.matcher(password).matches()){
registerPassword.setError("Password should contain atleast 1 alphabet, 1 special character, 1 numeric value, and a total of 8 characters");
return;
} else {
registerPassword.setError(null);
}
if (registerRePassword.getText().toString().trim().isEmpty()) {
registerRePassword.setError("Field Can't be Empty");
registerRePassword.requestFocus();
return;
}
if (!registerRePassword.getText().toString().trim().equals(registerPassword.getText().toString().trim())) {
registerRePassword.setError("Password Don't match. Please Match Again");
registerRePassword.requestFocus();
return;
}else {
registerRePassword.setError(null);
}
FoodVybeAPI foodVybeAPI = ApiClient.getRetrofit().create(FoodVybeAPI.class);
foodVybeAPI.register(name, email, password).enqueue(new Callback<Userinfo>() {
#Override
public void onResponse(Call<Userinfo> call, Response<Userinfo> response) {
if (response.code()==404) {
Toast.makeText(RegisterActivity.this, "An error occurred try again later", Toast.LENGTH_LONG).show();
Log.e(TAG, "onResponse: Not Successfull" + response.errorBody() + response.code());
return;
// } else if (response.code()==400){
// Toast.makeText(RegisterActivity.this, "Already Registered", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(RegisterActivity.this, "Woo! You are registered now Just Verify Email and login here", Toast.LENGTH_LONG).show();
Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
startActivity(intent);
finish();}
}
#Override
public void onFailure(Call<Userinfo> call, Throwable t) {
Toast.makeText(RegisterActivity.this,t.getLocalizedMessage(),Toast.LENGTH_SHORT);
Log.e(TAG, "onFailure: Failure" + t.getMessage());
}
});
}
public void registerSignUp(View view) {
if (!signUpCheckBox.isChecked()) {
Toast.makeText(this, "Please Accept Terms and Conditions", Toast.LENGTH_SHORT).show();
} else {
Usersignup();
}
}
}
Userinfo class:
public class Userinfo {
#SerializedName("userName")
#Expose
String userName;
#SerializedName("email")
#Expose
String email;
#SerializedName("password")
#Expose
String password;
public Userinfo(String name, String email, String password) {
name = userName;
this.email = email;
this.password = password;
}
public String getName() {
return userName;
}
public void setName(String name) {
this.userName = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Interface:
#FormUrlEncoded
#POST("user/login")
Call<User> login(#Field("email") String email, #Field("password") String password);
#FormUrlEncoded
#POST("user/register")
Call<Userinfo> register(
#Field("userName") String userName,
#Field("email") String email,
#Field("password") String password);
if you want to show that user already exist.
just ask to your back end developer to add status and message in response .
if user register successfully then status will be success and message will be "registration successful "
if user already exist then status will be failed and message will be "user already exist".
just user your UserInfo class like this:
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class UserInfo {
#SerializedName("userName")
#Expose
private String userName;
#SerializedName("email")
#Expose
private String email;
#SerializedName("password")
#Expose
private String password;
#SerializedName("error")
#Expose
private String error;
#SerializedName("message")
#Expose
private String message;
#SerializedName("status")
#Expose
private String status;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
Now if you get 400 status code show him the error and status message from UserInfo class cz now your UserInfo class holds status, error, message informations else if you get 201 or 200 status code just proceed to success
if (response.code()==404) {
Toast.makeText(RegisterActivity.this, response.status.toString(), Toast.LENGTH_LONG).show();
Log.e(TAG, "onResponse: Not Successfull" + response.errorBody() + response.code());
return;
} else if (response.code()==400){
UserInfo userInfo = response.body();
Toast.makeText(RegisterActivity.this, userInfo.status.toString(), Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(RegisterActivity.this, "Woo! You are registered now Just Verify Email and login here", Toast.LENGTH_LONG).show();
Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
startActivity(intent);
finish();}
This are the rules on my Firebase Realtime Database:
{
"rules": {
".read": true,
".write": true
}
}
RegisterActivity.java
public class RegisterActivity extends AppCompatActivity {
private EditText mUserName, mEmail, mPassword;
private Button registerBtn;
private TextView toLogin;
private ProgressBar progressBar;
private ImageView mImage;
// Firebase stuff
private FirebaseAuth mAuth;
private DatabaseReference databaseReference;
private FirebaseDatabase mDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
setupUI();
mAuth = FirebaseAuth.getInstance();
registerBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String userName = mUserName.getText().toString();
String email = mEmail.getText().toString();
String password = mPassword.getText().toString();
if(TextUtils.isEmpty(userName)) {
Toast.makeText(getApplicationContext(),"Username is required", Toast.LENGTH_SHORT).show();
}
if(TextUtils.isEmpty(email)) {
Toast.makeText(getApplicationContext(),"Email is required", Toast.LENGTH_SHORT).show();
}
if(TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(),"Password is required", Toast.LENGTH_SHORT).show();
}
if(userName.length() < 4) {
Toast.makeText(RegisterActivity.this, "Username too short", Toast.LENGTH_SHORT).show();
}
if (android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
Toast.makeText(getApplicationContext(),"Valid email address", Toast.LENGTH_SHORT).show();
}
if(password.length() < 8) {
Toast.makeText(getApplicationContext(),"Password must contain at least 8 characters", Toast.LENGTH_SHORT).show();
}
userRegister(email, password);
startActivity(new Intent(getApplicationContext(), MenuActivity.class));
finish();
}
});
toLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), LoginActivity.class));
}
});
}
private void userRegister(String email, String password) {
final ProgressDialog progressDialog = new ProgressDialog(RegisterActivity.this,
R.style.AppTheme_Dark_Dialog);
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Creating account...");
progressDialog.show();
//register user in firebase
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()) {
User user = new User(email, password);
FirebaseDatabase.getInstance().getReference("users")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()) {
Toast.makeText(RegisterActivity.this, "User successful created",
Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
else {
Toast.makeText(RegisterActivity.this, "Failed to register",
Toast.LENGTH_SHORT).show();
}
}
});
}
else {
Toast.makeText(RegisterActivity.this, "Error! " +
task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
private void setupUI() {
mImage = findViewById(R.id.image);
mUserName = findViewById(R.id.userName_register);
mEmail = findViewById(R.id.email_register);
mPassword = findViewById(R.id.password_register);
registerBtn = findViewById(R.id.register_button);
toLogin = findViewById(R.id.toLogin);
progressBar = findViewById(R.id.progress_bar_register);
}
}
User.java
public class User {
public String userName, email, password;
public User() { }
public User(String email, String password) {
this.email = email;
this.password = password;
}
public User(String userName, String email, String password) {
this.userName = userName;
this.email = email;
this.password = password;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
I have tried many things found on web but none have worked and nothing changes, it still remain void. I'm very desperate guys. Am I forgetting to add something? Unfortunately I'm new in Android and Firebase. Thanks in advance.
Did you setup the application by downloading the google-services.json from Firebase console and putting it in the Android Studio project?
Also, did you add your app's signature to the allowed apps in Firebase console?
Refer to this.
I did the registration through Firebase. The data is stored like this:
Each user can fill out a form and the data from it is displayed on a separate screen in RecyclerView. The problem is that now the users are not separated in any way. This is what user records look like:
How can I make only those entries created by a particular user be displayed? I need to check exactly by user id.
Now I output the data this way:
protected void onCreate(Bundle savedInstanceState) {
...
dRef = FirebaseDatabase.getInstance().getReference().child("User Data");
dRef.addListenerForSingleValueEvent(valueEventListener);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
userData = new ArrayList<UserData>();
}
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1: dataSnapshot.getChildren()) {
UserData uData = dataSnapshot1.getValue(UserData.class);
userData.add(uData);
}
userAdapter = new UserAdapter(MainActivity.this, userData);
recyclerView.setAdapter(userAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {}
};
How can I do that? The IDs are different everywhere.
UPD:
Create user:
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
User user = new User(fullName, age, email, phone);
FirebaseDatabase.getInstance().getReference("Users")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(RegisterUser.this, "Successful", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
} else {
Toast.makeText(RegisterUser.this, "Failed", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
}
});
} else {
Toast.makeText(RegisterUser.this, "Failed", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
}
});
User:
public class User {
public String fullName, age, email, phone;
public User() {
}
public User(String fullName, String age, String email, String phone) {
this.fullName = fullName;
this.age = age;
this.email = email;
this.phone = phone;
}
}
UserData:
public class UserData {
String id, userName, userLastName, userOtchestvo, userAppeal, userOrganisation, userPhone, userEmail, userVK, userFB;
public UserData(String id, String userName, String userLastName, String userOtchestvo, String userAppeal, String userOrganisation, String userPhone, String userEmail, String userVK, String userFB) {
this.id = id;
this.userName = userName;
this.userLastName = userLastName;
this.userOtchestvo = userOtchestvo;
this.userAppeal = userAppeal;
this.userOrganisation = userOrganisation;
this.userPhone = userPhone;
this.userEmail = userEmail;
this.userVK = userVK;
this.userFB = userFB;
}
public UserData() {}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUserName() {
return userName;
}
...
I add data to Firebase at the click of a button:
add_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String userId, userName, userLastName, userOtchestvo, userAppeal, userOrganisation, userPhone, userEmail, userVK, userFB;
userId = database.push().getKey();
userName = title_input.getText().toString();
userLastName = author_input.getText().toString();
userOtchestvo = pages_input.getText().toString();
userAppeal = appeal_input.getText().toString();
userOrganisation = organisation_input.getText().toString();
userPhone = phone_input.getText().toString();
userEmail = email_input.getText().toString();
userVK = vk_input.getText().toString();
userFB = fb_input.getText().toString();
UserData userData = new UserData(userId, userName, userLastName, userOtchestvo, userAppeal, userOrganisation, userPhone, userEmail, userVK, userFB);
database.child(userId).setValue(userData);
}
});
database.push().getKey()
This doesn't give you the userid, this only gives you a random unique key which is not equals to userid.
So do this instead.
userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
This will give you the userId of the current logged in user.
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
String currentUserID = mAuth.getCurrentUser().getUid();
DataRef.child("Users").child(currentUserID).child("Name").setValue(name);
DataRef.child("Users").child(currentUserID).child("Email").setValue(email);
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success");
FirebaseUser user = mAuth.getCurrentUser();
updateUI();
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
// Toast.makeText(MainActivity.this, task.getException().getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
// ...
}
});
UserInformation Classs:
public class UserInformation {
private String email;
private String name;
public UserInformation(){
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
First Assign Firebase User.
FirebaseUser firebaseUser = mAuth.getCurrentUser();
Which will hold the data of user.
There are different methods to retrieve current user data
String userEmail = firebaseUser.getEmail();
String uid = firebaseUser.getDisplayName();
String photouri = String.ValueOf(firebaseUser.getPhotoUrl());
In the task.isSuccessful(){ you need to add:
user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
String uid = user.getUid();
token = user.getUid();
email = user.getEmail();
displayName = user.getDisplayName();
}
this is how i have registered the users..but it is not sending anything to database though the registration completes just fine
private void registerUser(){
//getting email and password from edit texts
String email = editTextEmail.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();
//checking if email and passwords are empty
if(TextUtils.isEmpty(email)){
Toast.makeText(this,"Please enter email",Toast.LENGTH_LONG).show();
return;
}
if(TextUtils.isEmpty(password)){
Toast.makeText(this,"Please enter password",Toast.LENGTH_LONG).show();
return;
}
//if the email and password are not empty
//displaying a progress dialog
progressDialog.setMessage("Registering Please Wait...");
progressDialog.show();
//creating a new user
firebaseAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
//checking if success
if(task.isSuccessful()){
finish();
startActivity(new Intent(getApplicationContext(), ProfileActivity.class));
}else{
//display some message here
Toast.makeText(MainActivity.this,"Registration Error",Toast.LENGTH_LONG).show();
}
progressDialog.dismiss();
}
});
}
then here is my login.activity. i can log in just fine but i wonder what cretiria is this code using to log in users??
private void userLogin(){
String email = editTextEmail.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();
//checking if email and passwords are empty
if(TextUtils.isEmpty(email)){
Toast.makeText(this,"Please enter email",Toast.LENGTH_LONG).show();
return;
}
if(TextUtils.isEmpty(password)){
Toast.makeText(this,"Please enter password",Toast.LENGTH_LONG).show();
return;
}
//if the email and password are not empty
//displaying a progress dialog
progressDialog.setMessage("Registering Please Wait...");
progressDialog.show();
//logging in the user
firebaseAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressDialog.dismiss();
//if the task is successfull
if(task.isSuccessful()){
//start the profile activity
finish();
startActivity(new Intent(getApplicationContext(), ProfileActivity.class));
}
}
});
}
change your person class like this
public class Person {
private String Username;
private String Email;
public Person(String email,String userName) {
this.Username=userName;
this.Email=email;
/*Blank default constructor essential for Firebase*/
}
//Getters and setters
public String getUsername() {
return Username;
}
public void setUsername(String Username) {
this.Username = Username;
}
public String getEmail() {
return Email;
}
public void setEmail(String Email) {
this.Email = Email;
}
}
then use it like this
Person person=new Person();
person.setUsername(Username);
person.setEmail(Email);
Firebase newRef = ref.child("Users").push();
newRef.setValue(person);
then use this to get values
newRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Person person = dataSnapshot.getValue(Person.class);
String string = "Username: "+person.getName()+"\nEmail: "+person.getEmail()+"\n\n";
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
The problem is described here:
com.fasterxml.jackson.databind.JsonMappingException: Can not
instantiate value of type [simple type, class
com.example.moses.bstation.Person] from String value; no single-String
constructor/factory method
It seems that the mapping between the JSON response and the Person class is incorrect.
Double check your Person class implementation, also please share your Person class implementation and a sample from the JSON response.