i'm trying to show the created user/user info in my firestore database but i cant seem to get it. I have a Question model already created that will show up whenever a new question is submitted however when I try to create a user, the information doesnt show in the Database.
Ideally, of course, i'd like to have the info in the database. i'd also like to show that the question was created by an author.
Any and all help is appreciated. Ive been following a series of tutorials trying to blend them all to make my code work but im struggling on this part.
here is my relative code so far:
SignUpActivity.java
private void registerUser() {
final String email = editTextEmail.getText().toString().trim();
final String userName = editTextUserName.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();
final List<Question> questionsList = new ArrayList<>();
final String firstName = "default firstName";
final String lastName = "default lastName";
CollectionReference usersRef = FirebaseFirestore.getInstance().collection("Users");
User userInfo = new User(userName, firstName, lastName, email, questionsList);
// DocumentReference docPath = FirebaseFirestore.getInstance().document(mAuth.getCurrentUser()).
userInfo.setUserName(userName);
usersRef.add(userInfo);
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressBar.setVisibility(View.GONE);
if (task.isSuccessful()) {
CollectionReference usersRef = FirebaseFirestore.getInstance().collection("Users");
usersRef.add(new User(userName, firstName, lastName, email, questionsList));
FirebaseUser user = mAuth.getCurrentUser();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
UserProfileChangeRequest profileChangeRequest = new UserProfileChangeRequest.Builder()
.setDisplayName(userName).build();
user.updateProfile(profileChangeRequest);
}
}
};
mAuth.addAuthStateListener(mAuthListener); // need this to change info on Firebase Firestore
String usernameTest = user.getDisplayName();
Toast.makeText(SignUpActivity.this, "info saved hopefully", Toast.LENGTH_SHORT).show();
finish();
startActivity(new Intent(SignUpActivity.this, DashboardActivity.class));
} else {
if (task.getException() instanceof FirebaseAuthUserCollisionException) {
Toast.makeText(getApplicationContext(), "You are already registered", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), task.getException().getMessage(), Toast.LENGTH_LONG).show();
}
}
}
});
}
NewQuestionActivity.java
private void saveQuestion(){
String questionString = questionEditText.getText().toString();
String questionAnswerString = answerEditText.getText().toString();
String authorFirebase = FirebaseAuth.getInstance().getCurrentUser().toString(); //TODO: HOW TO SET THIS Author
authorTextView.setText(authorFirebase);
int priority = numberPickerPriority.getValue();
String tagInput = editTextTags.getText().toString();
String[] tagArray = tagInput.split("\\s*, \\s*");
List<String> tags = Arrays.asList(tagArray);
if (questionString.trim().isEmpty() || questionAnswerString.trim().isEmpty()) {
Toast.makeText(this, "Please insert a question and a proposed answer", Toast.LENGTH_SHORT).show();
return;
}
CollectionReference questionRef = FirebaseFirestore.getInstance().collection("Questions");
questionRef.add(new Question(questionString, questionAnswerString, priority, tags, authorFirebase));
Toast.makeText(this, "Question Added", Toast.LENGTH_SHORT).show();
finish();
}
usermodel
package com.example.stairmaster.models;
import java.util.List;
import androidx.databinding.BaseObservable;
import com.google.firebase.firestore.Exclude;
public class User extends BaseObservable {
#Exclude
private int id;
private String firstName;
private String lastName;
private String userName;
private String email;
private List<Question> questions;
public User() {
// no arg constructor needed
}
public User(String firstName, String lastName, String userName, String email, List<Question> questions) {
this.firstName = firstName;
this.lastName = lastName;
this.userName = userName;
this.email = email;
this.questions = questions;
}
public int getId() {
return id;
}
public String getUserName(String userName) { return userName;}
public void setUserName(String userName) { this.userName = userName; }
public String getFirstName(String firstName) {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName(String lastName) {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail(String email) {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public List<Question> getQuestions() {
return questions;
}
}
Issue is firstname, and lastname are not being created in the database as they should be. ID is incorrect (i'm still not too sure what to assign as an ID to users so that they unique), and the questions list is another thing i still need to figure out.
Finally got it working. although the only thing i cant seem to get working is storing the userId when its created so i have to do that later somewhere.
Code under registerUser looks like this now:
final CollectionReference usersColRef = FirebaseFirestore.getInstance().collection("Users");
final User userInfo = new User(firstName, lastName, userName, userEmail, mAuthUserId);
final DocumentReference userDocRef = usersColRef.document(userEmail);
userDocRef.set(userInfo).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
mAuthUserId = FirebaseAuth.getInstance().getCurrentUser().getUid();
userDocRef.update(
"firstname", firstName,
"lastname", lastName,
"userEmail", userEmail).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "onSuccess: userinfo was created");
}
});
Log.d(TAG, "onSuccess: user was created");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d(TAG, "onFailure: failed to create user in signup" + e);
}
});
Related
I'm trying to build a ticket booking app for an event and I managed to do the registration and log-in part. After the login, the user profile shows up which contains some TextViews about the name, age, email, etc. and I want to read the data from the real-time database and put it in TextView.I don't know what is the problem but the TextViews won't show the data.
User profile class
public class ProfilUser extends AppCompatActivity {
private FirebaseUser user;
private DatabaseReference referinta;
private String userID;
private Button delogare;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profil_user);
delogare = (Button) findViewById(R.id.delogare);
delogare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(ProfilUser.this,MainActivity.class));
}
});
user = FirebaseAuth.getInstance().getCurrentUser();;
userID = user.getUid();
referinta = FirebaseDatabase.getInstance("https://rezervarebileteveniment-default-rtdb.europe-west1.firebasedatabase.app").getReference("Users").child(userID);
TextView bunVenitTextView = (TextView) findViewById(R.id.bunVenit);
TextView numeTextView = (TextView) findViewById(R.id.getNume);
TextView prenumeTextView = (TextView) findViewById(R.id.getPrenume);
TextView varstaTextView = (TextView) findViewById(R.id.getVarsta);
TextView emailTextView = (TextView) findViewById(R.id.getAdresaEmail);
referinta.child(userID).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
User profilUser = snapshot.getValue(User.class);
if(profilUser != null){
String nume = profilUser.nume;
String prenume = profilUser.prenume;
String email = profilUser.email;
String varsta = profilUser.varsta;
bunVenitTextView.setText("Buna ziua, "+nume + " "+prenume +"!");
numeTextView.setText(nume);
prenumeTextView.setText(prenume);
emailTextView.setText(email);
varstaTextView.setText(varsta);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(ProfilUser.this,"Ceva nu a mers bine!", Toast.LENGTH_LONG).show();
}
});
}
}
User class
package oct.alx.rezervarebileteveniment;
public class User {
public String nume, prenume , varsta, email;
public User(){
}
public User(String nume, String prenume, String varsta, String email){
this.nume = nume;
this.prenume = prenume;
this.varsta = varsta;
this.email = email;
}
public String getNume(){
return nume;
}
public void setNume(String nume){
this.nume = nume;
}
public String getPrenume() {
return prenume;
}
public void setPrenume(String prenume) {
this.prenume = prenume;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getVarsta() {
return varsta;
}
public void setVarsta(String varsta) {
this.varsta = varsta;
}
}
The problem in your code lies in the fact that you're calling .child(userID) twice, once when you create the reference:
referinta = FirebaseDatabase.getInstance("https://rezervarebileteveniment-default-rtdb.europe-west1.firebasedatabase.app")
.getReference("Users")
.child(userID); //👈
And second time when you attach the listener:
referinta.child(userID).addListenerForSingleValueEvent(/*... /*);
// 👆
This means that you're trying to read the data from a location that doesn't exist. To solve this, you either remove that method call from the first line of code or from the second one.
P.S. To use encapsulation, try to make all fields in your class private:
private String nume, prenume , varsta, email;
i developed authentication with firebase it worked fine but i want to add an extra module to add user profie image. so I wrote 2 functions first for the user signup with email and password in firebase realtime database, and the second for uploading user profile image along with it...
i just add pimage variable in user model class, but i am getting errors here in previous parameters of user model object and (uri.toString());
here is the code for creating user with email and password
private void register_doctor () {
String dname = et_name.getText().toString().trim();
String demail = et_email.getText().toString().trim();
String dpass = et_pass.getText().toString().trim();
String dcpass = et_cnf_pass.getText().toString().trim();
String dcontact = et_contact.getText().toString().trim();
String dcity = et_city.getText().toString().trim();
String dage = et_age.getText().toString().trim();
if (dname.isEmpty()) {
et_name.setError("Full Name is Required");
et_name.requestFocus();
return;
}
if (demail.isEmpty()) {
et_email.setError("Email is Required");
et_email.requestFocus();
return;
}
if (dpass.isEmpty()) {
et_pass.setError("Password is Required");
et_pass.requestFocus();
return;
}
if (dpass.length() < 6) {
et_pass.setError("Password Length Should be greater than 6 characters");
et_pass.requestFocus();
return;
}
if (dcpass.isEmpty()) {
et_cnf_pass.setError("Password is Required");
et_cnf_pass.requestFocus();
return;
}
if (!dcpass.equals(dpass)) {
et_cnf_pass.setError("Password Does not Matched!");
et_cnf_pass.requestFocus();
return;
}
if (dcontact.isEmpty()) {
et_contact.setError("Contact is Required");
et_contact.requestFocus();
return;
}
if (dcity.isEmpty()) {
et_city.setError("City is Required");
et_city.requestFocus();
return;
}
if (dage.isEmpty()) {
et_age.setError("Age is Required");
et_age.requestFocus();
return;
}
progressBar.setVisibility(View.VISIBLE);
mAuth.createUserWithEmailAndPassword(demail, dpass)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
User user = new User(dname, demail, dcontact, dcity, dage);👈
FirebaseDatabase.getInstance().getReference("doctors")
.child("Doctors_Registration")
// .child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.child(demail.replace(".", ","))
.setValue(user)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(signup.this, "Doctor Registered", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
} else {
Toast.makeText(signup.this, "Failed to Registered, Try Again!" + task.getException(), Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
}
}
});
} else {
Toast.makeText(signup.this, "Failed to Registered, Try Again!", Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
}
}
});
}
here is the function to upload user profile image
private void upload_image() {
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference uploader = storage.getReference("Image1"+ new Random().nextInt(50));
uploader.putFile(filepath)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
uploader.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
FirebaseDatabase db = FirebaseDatabase.getInstance();
DatabaseReference root = db.getReference("Doctors_Registration");
User obj = new User(uri.toString()); 👈
root.child(et_email.getText().toString()).setValue(obj);
// iv.setImageResource(R.drawable.ic_launcher_background);
Toast.makeText(signup.this, "Profile Image Uploaded", Toast.LENGTH_SHORT).show();
}
});
}
});
}
here is the user model class code
public class User {
public String name, email, password, contact, city, age, pimage;
public User(){
}
public User(String name, String email, String contact, String city, String age, String pimage){
this.name = name;
this.email = email;
this.contact = contact;
this.city = city;
this.age = age;
this.pimage = pimage;
}
}
Your User class has two constructors:
One that takes no arguments.
And one that takes 6 string values as its arguments.
In the two screenshots you are trying to construct a User object:
First with a single string value,
And then with 5 string values.
Since neither of these calls matches the constructors you defined, the compiler is unable to compile your code.
To allow constructing a User, makes sure you either add constructor overloads for the parameters you want to pass, or pass the parameters that match with the constructors you defined.
so I'm making a chatting app, I'm facing the problem where I'm trying to add the user details to my Realtime database, and it's just not working so I can later on show them to the logged in user
this is my Register Activity
public class RegisterActivity extends AppCompatActivity {
EditText username;
EditText email;
EditText password;
Button registerButton;
TextView oldMember;
FirebaseAuth auth;
DatabaseReference myRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
username = findViewById(R.id.usernameEditText);
email = findViewById(R.id.emailEditText);
password = findViewById(R.id.passwordEditText);
registerButton = findViewById(R.id.RegisterButton);
oldMember = findViewById(R.id.LoginTextView);
auth = FirebaseAuth.getInstance();
myRef = FirebaseDatabase.getInstance().getReference("MyUsers");
registerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String usernameText = username.getText().toString();
String emailText = email.getText().toString();
String passwordText = password.getText().toString();
if(TextUtils.isEmpty(usernameText) || TextUtils.isEmpty(emailText) || TextUtils.isEmpty(passwordText)){
Toast.makeText(RegisterActivity.this, "Please Fill the Required Info", Toast.LENGTH_SHORT).show();
} else {
Register(usernameText, emailText, passwordText);
}
}
});
oldMember.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(intent);
finish();
}
});
}
private void Register(String username, String email, String password){
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull #org.jetbrains.annotations.NotNull Task<AuthResult> task) {
if(task.isSuccessful()){
FirebaseUser firebaseUser = auth.getCurrentUser();
String userid = firebaseUser.getUid();
myRef = FirebaseDatabase.getInstance()
.getReference("MyUsers")
.child(userid);
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("id", userid);
hashMap.put("username", username);
hashMap.put("imageURL", "default");
myRef.setValue(hashMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull #NotNull Task<Void> task) {
if(task.isSuccessful()){
Intent intent = new Intent(getApplicationContext(), MainHomeActivity.class);
//intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
}
});
} else {
Toast.makeText(RegisterActivity.this, "Invalid Email or Password", Toast.LENGTH_SHORT).show();
}
}
});
}
}
this is how my realtime database looks like
and these are my realtime database rules
"rules": {
".read": true,
".write": true
}
}
I would appreciate any help!
Instead of using HashMap for adding data to firebase realtime database
myRef = FirebaseDatabase.getInstance()
.getReference("MyUsers")
.child(userid);
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("id", userid);
hashMap.put("username", username);
hashMap.put("imageURL", "default");
Create a model class for the information
Example model class for the given information
public class userRegisteration(){
Sting id;
String username;
String imageURL;
//to add details it needs an empty constructor
userRegisteration(){}
userRegisteration(String id,String username,String imageURL){
this.id = id;
this.username = username;
this.imageURL = imageURL;
}
public void setID(String id){this.id = id}
public void setUsername(String username){this.username= username}
public void setImgeURL(String imageURL){this.imageURL = imageURL}
public String getID(){return id}
public String getUsername(){return username}
public String getImageURL(){return imageURL}
}
Trust me it'll work
I am new on Android Studio. I want to assign unique id (increment) from "1", but whenever I register account, I keep getting one only.
btn_register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String email = et_email.getText().toString().trim();
final String username = email.split("#")[0];
final String pwd = et_password.getText().toString().trim();
final long usr_id = 0; // not increment
if (email.isEmpty() || pwd.isEmpty()) {
et_email.setError("Entering Email Password Is required");
et_email.requestFocus();
return;
}
if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
et_email.setError("Entering Valid Email is required");
}
if (pwd.length() < 3) {
et_password.setError("Password Length Should More Than 3");
et_password.requestFocus();
} else {
m_auth.createUserWithEmailAndPassword(email, pwd).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("users");
DatabaseReference usr_uid = ref.child(m_auth.getCurrentUser().getUid());
if (task.isSuccessful()) {
Toast.makeText(MainActivity.this, "Registration Successed", Toast.LENGTH_SHORT).show();
//User usr = new User(email,username,usr_id+1);
usr_uid.child("email").setValue(email);
usr_uid.child("username").setValue(username);
usr_uid.child("password").setValue(pwd);
usr_uid.child("icon").setValue("default_icon");
usr_uid.child("id").setValue(String.valueOf(usr_id+1));
Intent refer_to_home = new Intent(MainActivity.this, Home_Activity.class);
startActivity(refer_to_home);
finish();
}
else
Log.e("user_reg_fail", "Field Empty!");
}
});
}
}
});
And this is my model:
public class User {
private String email;
private String username;
private long usr_id=0;
private String icon;
public User(String email, String username, long id) {
this.email = username;
this.username = username;
this.usr_id = id;
}
public void setIcon(String icon) {
this.icon = icon;
}
public User() {
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public long getId() {
return usr_id;
}
public void setId(long id) {
this.usr_id = id;
}
}
The database I get
dldnPGvVsHeQmVqHkuJS4no4g1r1
|-email: "effeff#gmail.com"
|-icon: "default_icon"
|-id: "1" //from one
|-password: "xxx"
|-username: "effeff"
gWEvZMOgi7hmuU5xOXhlG3vibgj1
|-email: "feefee#gmail.com"
|-icon: "default_icon"
|-id: "1" // id is still one
|-password: "xxx"
|-username: "feefee"
I have no idea why it does not increment the ID. How can I able to get increment "2" "3"? I can able to register my account successfully, but it keeps only assign ID "1"
So inside your onClick method you have those lines
final long usr_id = 0; // not increment
...
usr_uid.child("id").setValue(String.valueOf(usr_id+1));
every time that you click that button the usr_id will set its values to 0.
With firebase you have a unique document id (example in your question is dldnPGvVsHeQmVqHkuJS4no4g1r1,gWEvZMOgi7hmuU5xOXhlG3vibgj1) you don't need any extra id
So far I have successfully implemented Firebase within my Android application, where I can add users to the Authentication portal through a SignUpActivity, and also add maintenance issues to the real-time database through a MaintenanceActivity.
However, at present, none of the database data is linked to specific users, which is what I want to achieve. So essentially at the moment when I log in as an arbitrary user, the same data will always come up.
Presumably, and having read several other threads on this, the User UID will be required here and will need to be present for every maintenance record.
I'm not sure, however, how I can implement this. Possibly a layer of authentication needs implemented into the MainActivity?
Finding it hard to get my head around this, so any help on this would be much appreciated.
SignUpActivity
mDatabase = FirebaseDatabase.getInstance().getReference().child("users");
final DatabaseReference[] ref = new DatabaseReference[1];
final FirebaseUser[] mCurrentUser = new FirebaseUser[1];
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(SignUpActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Toasty.info(getApplicationContext(), "creation of account was: " + task.isSuccessful(), Toast.LENGTH_SHORT).show();
if (task.isSuccessful()) {
mCurrentUser[0] = task.getResult().getUser();
ref[0] =mDatabase.child(mCurrentUser[0].getUid());
ref[0].child("email").setValue(email);
Intent intent = new Intent(SignUpActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
}
});
You can implement it like this:
mDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
DatabaseReference ref;
FirebaseUser mCurrentUser;
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(SignUpActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Toasty.info(getApplicationContext(), "creation of account was: " + task.isSuccessful(), Toast.LENGTH_SHORT).show();
if (task.isSuccessful()) {
mCurrentUser= task.getResult().getUser();
ref=mDatabase.child(mCurrentUser.getUid());
ref.child("email").setValue(email);
ref.child("name").setValue(name);
}
});
You can implement it like the above, then in your db you will have:
Users
userid
name: userx
email: userx#gmail.com
After you authenticate the user using createUserWithEmailAndPassword(email, password), you can then retrieve the email and name, and whatever extra data was written and send it to the database.
This mCurrentUser.getUid() will give you the userid, that you can use in the database.
After adding your project to the firebase
U can also try this.
public class RegisterActivity extends AppCompatActivity implements
View.OnClickListener {
private static final String TAG = "MAGIC";
Firebase mref =null;
private User user;
private EditText email;
private EditText password;
private FirebaseAuth mAuth;
private ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
Firebase.setAndroidContext(this);
mAuth = FirebaseAuth.getInstance();
}
#Override
protected void onStart() {
super.onStart();
email = (EditText) findViewById(R.id.edit_text_new_email);
password = (EditText) findViewById(R.id.edit_text_new_password);
}
#Override
public void onStop() {
super.onStop();
}
//This method sets up a new User by fetching the user entered details.
protected void setUpUser() {
user = new User();
user.setEmail(email.getText().toString().trim());
user.setPassword(password.getText().toString().trim());
}
#Override
public void onClick(View v) {
//paste your firebase database link address here.
mref = new Firebase("https://citypride-97902.firebaseio.com/");
createNewAccount(email.getText().toString(),
password.getText().toString());
}
private void createNewAccount(String email, String password) {
Log.d(TAG, "createNewAccount:" + email);
if (!validateForm()) {
return;
}
showProgressDialog();
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(TAG, "Register Successfully " + task.isSuccessful());
hideProgressDialog();
if (!task.isSuccessful()) {
Toast.makeText(RegisterActivity.this, "Registration failed.",
Toast.LENGTH_SHORT).show();
hideProgressDialog();
} else {
onAuthenticationSuccess(task.getResult().getUser());
Toast.makeText(RegisterActivity.this, "Register Successful.",
Toast.LENGTH_SHORT).show();
} hideProgressDialog();
}
});
}
private void onAuthenticationSuccess(FirebaseUser mUser) {
// Write new user
saveNewUser(mUser.getUid(), user.getEmail(), user.getPassword());
signOut();
// Go to LoginActivity
Intent i =new Intent(LoginActivity.this, YourActivity.class);
startActivity(i);
}
private void saveNewUser(String userId,
String email, String password) {
User user = new User(userId,email,password);
mref.child("Users").child(name).setValue(user);
}
private void signOut() {
mAuth.signOut();
}
//This method, validates email address and password
private boolean validateForm() {
boolean valid = true;
String userEmail = email.getText().toString();
if (TextUtils.isEmpty(userEmail)) {
email.setError("Required.");
valid = false;
} else {
email.setError(null);
}
String userPassword = password.getText().toString();
if (TextUtils.isEmpty(userPassword)) {
password.setError("Required.");
valid = false;
} else {
password.setError(null);
}
if(!Patterns.EMAIL_ADDRESS.matcher(userEmail).matches()){
Toast.makeText(getApplicationContext(),"please enter valid
email",Toast.LENGTH_LONG).show();
}
if (userEmail.isEmpty() && userPassword.isEmpty()){
Toast.makeText(getApplicationContext(),"all fields are
mandatory",Toast.LENGTH_LONG).show();
}
return valid;
}
public void showProgressDialog() {
if (mProgressDialog == null) {
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Loading");
mProgressDialog.setIndeterminate(true);
}
mProgressDialog.show();
}
public void hideProgressDialog() {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
}
}
Below is User class
class User {
private String id;
private String email;
private String password;
public User() {
}
public User(String id,String email, String password) {
this.id = id;
this.email = email;
this.password = password;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public void setName(String 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;
}
}
this will show email and password field in your firebase database.