I am using Firebase Auth (registering a new user) , it worked perfectly on the Main Thread but when i moved it to the background , Authentication always failed .
Here is the the method for creating a new user :
public void createAccount(String email, String password) {
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(TAG, "createUserWithEmail:onComplete:" + task.isSuccessful());
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
Toast.makeText(registerActivity.this, "bad",
Toast.LENGTH_SHORT).show();
sr = false;
} else {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
EditText etname = (EditText) findViewById(R.id.etName);
EditText etlname = (EditText) findViewById(R.id.etLName);
String namez = etname.getText().toString();
String lnamez = etlname.getText().toString();
DatabaseReference mDatabase;
mDatabase = FirebaseDatabase.getInstance().getReference();
Toast.makeText(registerActivity.this, "good", Toast.LENGTH_SHORT).show();
String UID = user.getUid();
mDatabase.child("users").child(UID + "_lname").setValue(lnamez);
mDatabase.child("users").child(UID + "_name").setValue(namez);
sr = true;
}
}
// ...
}
});
}
and here is the AsyncTask :
private class createInBack extends AsyncTask<Void, Void, Void> {
//Executes the 'createAccount' method in background .
EditText etemail = (EditText) findViewById(R.id.etEmail);
EditText etpassword = (EditText) findViewById(R.id.etPassword);
String email = etemail.getText().toString();
String password = etpassword.getText().toString();
#Override
protected void onPreExecute() {
super.onPreExecute();
spinner.setVisibility(View.VISIBLE);
}
#Override
protected Void doInBackground(Void... voids) {
createAccount(email, password);
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if(sr){
Toast.makeText(registerActivity.this, "we good here", Toast.LENGTH_SHORT).show();
startActivity(new Intent(registerActivity.this, MainActivity.class));
}
spinner.setVisibility(View.GONE);
}
}
so what is the problem ?
Problem Solved ,
I found in the XML layout that i forgot to remove the "android:onClick" from the button.
Linxy is right, it is not necessary to make an Asynctask for your goal.
Firebase solves that for you, look at a simple example.
private void loginAccount(String email, String password) {
final ProgressDialog progressDialog = new ProgressDialog(Login.this,
R.style.AppTheme_Dark_Dialog);
progressDialog.setIndeterminate(false);
progressDialog.setMessage("Autenticando...");
progressDialog.show();
mAuth.signInWithEmailAndPassword(email,password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
login.setEnabled(true);//button-ignore
login.setAlpha(1f);
if (task.isSuccessful()){
progressDialog.dismiss();
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
finish();
//Toast.makeText(Login.this,"Sesion iniciada",Toast.LENGTH_SHORT).show();
}else{
progressDialog.dismiss();
Toast.makeText(Login.this,"Email or password invalidate",Toast.LENGTH_SHORT).show();
Log.i("sesion","MaldatosH2");
}
}
});
}
To create a user is the same xd
Related
I am saving user information to a realtime database on a android studio app. When the user goes to register they select weather they are a PT or client by using radio buttons. As shown in my database all the user information is being saved under the user child node on firebase. Is there a way I can create subheadings called PT and Clients underneath user in the realtime database by using the radio buttons. Sign up code is:
public class RegisterActivity extends AppCompatActivity {
EditText txt_fullname, txt_email, txt_mobilenumber, txt_repassword, txt_password;
Button btn_register;
RadioButton radioJobClient, radioJobPT;
DatabaseReference databaseReference;
FirebaseDatabase firebaseDatabase;
String job ="";
FirebaseAuth firebaseAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
txt_fullname = (EditText) findViewById(R.id.editText_fullname);
txt_email = (EditText) findViewById(R.id.editText_UserEmail);
txt_password = (EditText) findViewById(R.id.editText_Password);
txt_repassword = (EditText) findViewById(R.id.editText_rePassword);
txt_mobilenumber = (EditText) findViewById(R.id.mobilenumber);
btn_register = (Button) findViewById(R.id.button_reg);
radioJobClient = (RadioButton) findViewById(R.id.radio_Client);
radioJobPT = (RadioButton) findViewById(R.id.radio_PersonalTrainer);
databaseReference = FirebaseDatabase.getInstance().getReference("User");
// new code
firebaseAuth = FirebaseAuth.getInstance();
btn_register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String fullname = txt_fullname.getText().toString();
final String email = txt_email.getText().toString();
final String mobilenumber = txt_mobilenumber.getText().toString();
final String password = txt_password.getText().toString();
final String rePassword = txt_repassword.getText().toString();
if (radioJobClient.isChecked()){
job = "Client";
}
if (radioJobPT.isChecked()){
job = "PT";
}
if (TextUtils.isEmpty(email)){
Toast.makeText(RegisterActivity.this, "Please enter Email", Toast.LENGTH_LONG).show();
}
if (TextUtils.isEmpty(fullname)){
Toast.makeText(RegisterActivity.this, "Please enter fullname", Toast.LENGTH_LONG).show();
}
if (TextUtils.isEmpty(password)){
Toast.makeText(RegisterActivity.this, "Please enter password", Toast.LENGTH_LONG).show();
}
firebaseAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(RegisterActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
User user = new User(
fullname,
email,
mobilenumber,
password,
job
);
FirebaseDatabase.getInstance().getReference("User")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(RegisterActivity.this, "Registration Complete", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(),MainActivity.class));
}
});
} else {
Toast.makeText(RegisterActivity.this, "Registration Unsuccessful", Toast.LENGTH_LONG).show();
}
// ...
}
});
}
});
}
if (radioJobClient.isChecked()){
job = "Client";
FirebaseDatabase.getInstance().getReference("User").child(job).child(FirebaseAuth.getInstance().getCurrentUser().getUid()).setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(RegisterActivity.this, "Registration Complete", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(),MainActivity.class));
}
});
}
if (radioJobPT.isChecked()){
job = "PT";
FirebaseDatabase.getInstance().getReference("User").child(job).child(FirebaseAuth.getInstance().getCurrentUser().getUid()).setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(RegisterActivity.this, "Registration Complete", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(),MainActivity.class));
I have a problem, I can't register in my chat app. It shows me that "You can't register". I don't know where is the problem. I set read and write to true in my database but it still not working. I use the last versions of Firebase. I haven't problems with the internet and connected firebase to my project successfully.
This is my register activity
MaterialEditText username, email, password;
Button btn_register;
FirebaseAuth auth;
DatabaseReference reference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Регистрация");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
username = findViewById(R.id.username);
email = findViewById(R.id.email);
password = findViewById(R.id.password);
btn_register = findViewById(R.id.btn_register);
auth = FirebaseAuth.getInstance();
btn_register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String txt_username = username.getText().toString();
String txt_email = email.getText().toString();
String txt_password = password.getText().toString();
if (TextUtils.isEmpty(txt_username) || TextUtils.isEmpty(txt_email) || TextUtils.isEmpty(txt_password)) {
Toast.makeText(RegisterActivity.this, "Write more", Toast.LENGTH_SHORT).show();
} else if (txt_password.length() < 6 ){
Toast.makeText(RegisterActivity.this, "Password too short ", Toast.LENGTH_SHORT).show();
} else {
register(txt_username, txt_email, txt_password);
}
}
});
}
private void register(final String username, String email, String password){
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
FirebaseUser firebaseUser= auth.getCurrentUser();
assert firebaseUser !=null;
String userid = firebaseUser.getUid();
reference = FirebaseDatabase.getInstance().getReference("Users").child(userid);
HashMap<String, String> HashMap = new HashMap<>();
HashMap.put("id", userid);
HashMap.put("username", username);
HashMap.put("imageURL", "default");
reference.setValue(HashMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Intent intent = new Intent(RegisterActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
}
});
}else {
Toast.makeText(RegisterActivity.this, "You cant register", Toast.LENGTH_SHORT).show();
}
}
});
}
}
When initializing your FirebaseDatabase reference, the item node with the provided user id does not exist yet in your database thus the reference is null
String userid = firebaseUser.getUid();
reference = FirebaseDatabase.getInstance().getReference("Users").child(userid);
Instead, initialize the reference to the Users node
String userid = firebaseUser.getUid();
reference = FirebaseDatabase.getInstance().getReference("Users");
Then when saving the user's data you can save to their userId:
reference.child(userid).setValue(HashMap).addOnCompleteListener(new OnCompleteListener<Void>() {
...
});
in manifest file allow internet permission. if you continue this err create failure listener and print failure code
Log.w(TAG, "createUserWithEmail:failure", task.getException());
Toast.makeText(EmailPasswordActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
I am new in android, I am trying to develop a simple system in android and using the cloud firestore beta as the database. I have already done the registration part which is writing the data(email & password) in the database. but I do not know the process for the login as i want the system to read the data from the database and match with the emails and passwords from the database. Can anyone help me? Thanks in advance.
The registration activity is given below:
public class RegisterActivity extends AppCompatActivity {
private Button btnRegister;
private EditText edtxtEmail;
private EditText edtxtTpnumber;
private EditText edtxtDepartment;
private EditText edtxtPassword;
private EditText edtxtConfirmpassword;
private FirebaseFirestore rFireStore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
rFireStore = FirebaseFirestore.getInstance();
btnRegister = (Button) findViewById(R.id.btnregister);
edtxtEmail = (EditText) findViewById(R.id.edtxtemail);
edtxtTpnumber = (EditText) findViewById(R.id.edtxttpnumber);
edtxtDepartment = (EditText) findViewById(R.id.edtxtdepartment);
edtxtPassword = (EditText) findViewById(R.id.edtxtpassword);
edtxtConfirmpassword = (EditText) findViewById(R.id.edtxtconfirmPassword);
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String Email = edtxtEmail.getText().toString();
String TPnumber = edtxtTpnumber.getText().toString();
String Department = edtxtDepartment.getText().toString();
String Password = edtxtPassword.getText().toString();
String ConfirmPassword = edtxtConfirmpassword.getText().toString();
Map<String, String> userMap = new HashMap<>();
userMap.put("Email Address", Email);
userMap.put("TP Number", TPnumber);
userMap.put("Department", Department);
userMap.put("Password", Password);
userMap.put("Confirm Pass", ConfirmPassword);
rFireStore.collection("Users").document("Students").set(userMap).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(RegisterActivity.this, "Data Saved!!", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(RegisterActivity.this, "Data Failed!!", Toast.LENGTH_SHORT).show();
}
});
/*rFireStore.collection("Users").add(userMap).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
Toast.makeText(RegisterActivity.this, "Data Saved!!", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(RegisterActivity.this, "Data Failed!!", Toast.LENGTH_SHORT).show();
}
});*/
}
});
}
}
For login you can use this:
for (QueryDocumentSnapshot documentSnapshot : task.getResult()) {
if (task.isSuccessful()) {
//task result = 1
}
}
if (task.getResult().size() == 0) {
//task result = 0
}
User register as student or tutor during registration which saved in firebase database but when login cannot identify the user position which saved in the firebase database so what should I do? Please anyone can give suggestion or advice me how to do this.
The database is save the uid from email authentication as the node under the root then rest details is the children of the uid.
The code like this
private FirebaseAuth auth;
private EditText un, pw;
private String getun, getpw, uid;
private Button bl;
private FirebaseDatabase db;
private DatabaseReference ref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
auth = FirebaseAuth.getInstance();
db = FirebaseDatabase.getInstance();
ref = db.getReference();
uid = auth.getCurrentUser().getUid();
ref = db.getReference("users").child(uid);
un = (EditText) findViewById(R.id.Lun);
pw = (EditText) findViewById(R.id.Lpw);
bl = (Button) findViewById(R.id.Lbt);
final TextView rl = (TextView) findViewById(R.id.Lreg);
//login
bl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getun = un.getText().toString().trim();
getpw = pw.getText().toString().trim();
loginaction(getun, getpw);
}
});
//open register page
rl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent ri = new Intent(Login.this,Register.class);
Login.this.startActivity(ri);
}
});
}
private void loginaction(String a, String b){
auth.signInWithEmailAndPassword(a, b).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d("Login", "Login Success" + task.isSuccessful());
if (!task.isSuccessful()) {
Log.w("Login", "Login Failed", task.getException());
Toast.makeText(Login.this, "Login Failed. Please try again", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(Login.this, "Login Success", Toast.LENGTH_SHORT).show();
ref.orderByChild("position").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String ps = dataSnapshot.getValue().toString();
if(ps.equalsIgnoreCase("student")){
Intent i = new Intent(Login.this, StudentHomePage.class);
startActivity(i);
}else if (ps.equalsIgnoreCase("tutor")){
Intent i = new Intent(Login.this, TutorHomePage.class);
startActivity(i);
}else{
Toast.makeText(Login.this,
"Wrong input. Please check again the email and password.", Toast.LENGTH_SHORT).show();
return;
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
// ...
}
});
}
Create two child nodes from users. One for students and one for tutors.(Give both child values a value of true, otherwise firebase doesn't save the children.)
Have two registration buttons ..one for students and one for tutors. Registration for Tutor code.....
mRegistration.setOnClickListener(new
View.OnClickListener() {
#Override
public void onClick(View v) {
final String email = mEmail.getText().toString();
final String password = mPassword.getText().toString();
mAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(DriverLoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()){
Toast.makeText(TutorsLoginActivity.this, "Sign in error", Toast.LENGTH_SHORT).show();
}else{
String user_id= mAuth.getCurrentUser().getUid();
DatabaseReference current_user_db= FirebaseDatabase.getInstance().getReference().child("Users").child("Tutors").child(user_id);
current_user_db.setValue(true);
}
}
});
}
});
Do the same for the students. Just change the .child("Tutors") to .child("Students") This will give you UIDs for the two different groups. And you can do the same when logging in. I think this is a better way to proceed.
I created a register activity with Firebase Authentication, but when I ran the application and clicked on the sign up button, nothing happened. Only the progress dialog, just rotating and it didn't even signup.
Here is my code:
public class RegisterActivity extends AppCompatActivity {
private EditText mNameField;
private EditText mEmailField;
private EditText mPasswordField;
private Button mRegisterBtn;
private FirebaseAuth mAuth;
private DatabaseReference mDatabase;
private ProgressDialog mProgress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
mAuth = FirebaseAuth.getInstance();
mDatabase = FirebaseDatabase.getInstance().getReference().child("users");
mProgress = new ProgressDialog(this);
mNameField = (EditText) findViewById(R.id.nameFied);
mEmailField = (EditText) findViewById(R.id.emailField);
mPasswordField = (EditText) findViewById(R.id.passwordField);
mRegisterBtn = (Button) findViewById(R.id.registerBtn);
mRegisterBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startRegister();
}
});
}
private void startRegister() {
final String name = mNameField.getText().toString().trim();
String email = mEmailField.getText().toString().trim();
String password = mPasswordField.getText().toString().trim();
if(!TextUtils.isEmpty(name) && !TextUtils.isEmpty(email) && !TextUtils.isEmpty(password)){
mProgress.setMessage("Signing up...please wait");
mProgress.show();
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
String user_id = mAuth.getCurrentUser().getUid();
DatabaseReference current_user_db = mDatabase.child(user_id);
current_user_db.child("name").setValue(name);
current_user_db.child("image").setValue("default");
mProgress.dismiss();
Intent mainIntent = new Intent(RegisterActivity.this, MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(mainIntent);
}
}
});
}
if (TextUtils.isEmpty(name) && TextUtils.isEmpty(email) && TextUtils.isEmpty(password)){
Toast.makeText(RegisterActivity.this, "do not leave any field empty", Toast.LENGTH_LONG).show();
}
}
}
I don't know what I did wrong.
Here are my gradle dependencies:
compile 'com.google.firebase:firebase-database:9.2.0'
compile 'com.google.firebase:firebase-auth:9.2.0'
try to add a OnFailureListener to see what exception or error you are getting.
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
String user_id = mAuth.getCurrentUser().getUid();
DatabaseReference current_user_db = mDatabase.child(user_id);
current_user_db.child("name").setValue(name);
current_user_db.child("image").setValue("default");
mProgress.dismiss();
Intent mainIntent = new Intent(RegisterActivity.this, MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(mainIntent);
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.i("Firebase Exception -> ",e.getMessage());
}});
You are creating user with
createUserWithEmailAndPassword(email, password)
but you never sign-in. You also need to sign in after creating user with
signInWithEmailAndPassword(email, password)
and in that add data to your database.
And I would suggest to update your repository and decencies also.