Firebase: onComplete() in createUserWithEmailAndPassword is never run,, - android

good Day
I'm trying to sign up a new account using firebase,but onComplete method it's never run I tried to check if there is any error by break point but it's never reached to it..as well I tried to make sure the password not less than 6 char,and email/password verification is enabled in firebase console..
here is my code
public class CreateAccountActivity extends AppCompatActivity {
private EditText emailedittxt;
private EditText passwordedittext;
private Button signUp;
//private EditText nametext;
private static final String TAG = "EmailPassword";
//Authentication
private FirebaseAuth mAuth;
// public static Intent newIntent(Context packageContext){
// Intent intent = new Intent(packageContext,CreateAccountActivity.class);
// return intent;
// }
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_account);
mAuth = FirebaseAuth.getInstance();
// nametext = (EditText) findViewById(R.id.RnameText);
emailedittxt = (EditText) findViewById(R.id.RemailText);
passwordedittext = (EditText) findViewById(R.id.RpasswordText);
signUp = (Button) findViewById(R.id.RsignupButton);
signUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// signUp();
//create new Account
// String name = nametext.getText().toString();
String email = emailedittxt.getText().toString();
String password = passwordedittext.getText().toString();
//validate the felids
// if (TextUtils.isEmpty(name)) {
// Toast.makeText(CreateAccountActivity.this, "Enter your nmae", Toast.LENGTH_SHORT).show();
// return;
// }
if (TextUtils.isEmpty(email)) {
Toast.makeText(CreateAccountActivity.this, "Enter your email", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(CreateAccountActivity.this, "Enter your password", Toast.LENGTH_SHORT).show();
return;
}
/*Create
new account */
SignUp(email,password);
}
});
}
private void SignUp(String email,String password) {
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(CreateAccountActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(TAG, "createUserWithEmail:onComplete:" + task.isSuccessful());
// // Toast.makeText(CreateAccountActivity.this, "createUserWithEmail:onComplete:" + task.isSuccessful(), Toast.LENGTH_SHORT).show();
// 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()) {
Intent intent = new Intent (CreateAccountActivity.this,Main2Activity.class);
startActivity(intent);
// startActivity(new Intent(CreateAccountActivity.this, Main2Activity.class));
finish();
} else {
Log.d(TAG, "onComplete: Failed=" + task.getException().getMessage()); //ADD THIS
//
//// Toast.makeText(CreateAccountActivity.this, "Authentication failed." + task.getException(), Toast.LENGTH_SHORT).show();
}}
});
}
}
anyone have any idea why it's never run onComplete()

Try adding onFailureListener() :
private void SignUp(String email,String password) {
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(CreateAccountActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(TAG, "createUserWithEmail:onComplete:" + task.isSuccessful());
// // Toast.makeText(CreateAccountActivity.this, "createUserWithEmail:onComplete:" + task.isSuccessful(), Toast.LENGTH_SHORT).show();
// 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()) {
Intent intent = new Intent (CreateAccountActivity.this,Main2Activity.class);
startActivity(intent);
// startActivity(new Intent(CreateAccountActivity.this, Main2Activity.class));
finish();
} else {
Log.d(TAG, "onComplete: Failed=" + task.getException().getMessage()); //ADD THIS
//
//// Toast.makeText(CreateAccountActivity.this, "Authentication failed." + task.getException(), Toast.LENGTH_SHORT).show();
}}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.e("exception",e.getMessage());
}
});
}

Related

After logout from Firebase phoneAuth, how to re-login into previous account?

I've a project using firebase phoneAuth verification as login method. But after logout, I can't re-login to previous account. It requires new account. But email verification works with re-login. I've check the doc and answer from this page but it seem l haven't got solution to the problem. Is it possible to re-login to previous account firebase phoneAuth ?
verifyBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String phoneNumber = loginPhoneET.getText().toString();
String phone = "+" + picker.getSelectedCountryCode() + phoneNumber;
if(!Patterns.PHONE.matcher(phoneNumber).matches())
{
loginPhoneET.setError("Invalid phone number");
loginPhoneET.setFocusable(true);
Toast.makeText(LoginActivity.this, "Please enter a valid phone number", Toast.LENGTH_LONG).show();
}
else
{
loadingBar.setTitle("Sending verification code");
loadingBar.setMessage("Please wait...");
loadingBar.setCanceledOnTouchOutside(false);
loadingBar.show();
PhoneAuthProvider.getInstance().verifyPhoneNumber(
phone, // Phone number to verify
60, // Timeout duration
TimeUnit.SECONDS, // Unit of timeout
TaskExecutors.MAIN_THREAD,
//AdminLoginActivity.this, // Activity (for callback binding)
callbacks); // OnVerificationStateChangedCallbacks
}
}
});
loginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
loginPhoneET.setVisibility(View.INVISIBLE);
verifyBtn.setVisibility(View.INVISIBLE);
String verificationCode = verificationET.getText().toString();
if(TextUtils.isEmpty(verificationCode))
{
Toast.makeText(LoginActivity.this, "Please enter the verification code", Toast.LENGTH_SHORT).show();
}
else
{
loadingBar.setTitle("Verifying code");
loadingBar.setMessage("Please wait...");
loadingBar.setCanceledOnTouchOutside(false);
loadingBar.show();
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(mVerificationId, verificationCode);
signInWithPhoneAuthCredential(credential);
}
}
});
callbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(#NonNull PhoneAuthCredential phoneAuthCredential)
{
String code = phoneAuthCredential.getSmsCode();
if (code!=null)
{
verificationET.setText(code);
signInWithPhoneAuthCredential(phoneAuthCredential);
}
}
#Override
public void onVerificationFailed(#NonNull FirebaseException e)
{
loadingBar.dismiss();
Toast.makeText(LoginActivity.this, "Invalid phone number. Please enter a correct phone number", Toast.LENGTH_SHORT).show();
verificationET.setVisibility(View.GONE);
loginBtn.setVisibility(View.GONE);
loginPhoneET.setVisibility(View.VISIBLE);
verifyBtn.setVisibility(View.VISIBLE);
}
#Override
public void onCodeSent(#NonNull String verificationId,
#NonNull PhoneAuthProvider.ForceResendingToken token) {
// Save verification ID and resending token so we can use them later
mVerificationId = verificationId;
mResendToken = token;
loadingBar.dismiss();
Toast.makeText(LoginActivity.this, "Verification code has been sent to your phone.", Toast.LENGTH_SHORT).show();
verificationET.setVisibility(View.VISIBLE);
loginBtn.setVisibility(View.VISIBLE);
loginPhoneET.setVisibility(View.GONE);
verifyBtn.setVisibility(View.GONE);
}
};
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task)
{
if (task.isSuccessful()) {
final FirebaseUser user = mAuth.getCurrentUser();
final String uid = user.getUid();
final String phone = user.getPhoneNumber();
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("userId", uid);
hashMap.put("phone", phone);
UsersDataRef.child(uid).setValue(hashMap).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
loadingBar.dismiss();
Toast.makeText(LoginActivity.this, "Login success !", Toast.LENGTH_SHORT).show();
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
SendUserToPhotoActivity(phone, uid);
}
});
} else {
String message = task.getException().toString();
Toast.makeText(LoginActivity.this, "Error:" + message, Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});

Failed to send DDMS packet REAQ to debugger (-1 of 20): Broken pipe

User gets Registered Successfully and in LoginActivity after filling User details while Authenticating it gives
"Failed to send DDMS packet REAQ to debugger (-1 of 20): Broken pipe"
Error in LogCat.
signup.java -> signUP_btn ClickListener
public void signingup(View view) {
uid = findViewById(R.id.userbox);
repwd = findViewById(R.id.repwd);
mail = findViewById(R.id.mail);
pwd = findViewById(R.id.pwd);
mylayout = findViewById(R.id.signuplayout);
String username = uid.getText().toString();
String password = pwd.getText().toString();
String rePassword = repwd.getText().toString();
String email = mail.getText().toString();
if (username.equals("")) {
Toast.makeText(this, "Invalid Username!!", Toast.LENGTH_LONG).show();
} else if (password.equals("")) {
Toast.makeText(this, "Invalid Password!!", Toast.LENGTH_LONG).show();
} else if (!password.equals(rePassword)) {
Toast.makeText(this, "Password should Match!!", Toast.LENGTH_LONG).show();
} else if (email.equals("")) {
Toast.makeText(this, "Invalid Email Id!!", Toast.LENGTH_LONG).show();
} else {
firebaseAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
try {
//check if successful
if (task.isSuccessful()) {
//User is successfully registered and logged in
//start Profile Activity here
Toast.makeText(signup.this, "registration successful",
Toast.LENGTH_SHORT).show();
finish();
startActivity(new Intent(getApplicationContext(), LoginActiviity.class));
}else{
Log.d("Error", ": "+task.getException().toString());
Toast.makeText(signup.this, "Couldn't register, try again",
Toast.LENGTH_SHORT).show();
}
}catch (Exception e){
e.printStackTrace();
}
}
});
}
}
LoginActivity.java
public class LoginActiviity extends AppCompatActivity {
TextView welcome,signsub,signText,reset;
EditText user,pwd;
Button signing;
ImageView loginLogo;
Animation anim,headtext,body_text,body_text2,body_text3;
private FirebaseAuth firebaseAuth;
private FirebaseUser currentUser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_activiity);
Typeface MRegular = Typeface.createFromAsset(getAssets(),"fonts/MRegular.ttf");
Typeface MMedium = Typeface.createFromAsset(getAssets(),"fonts/MMedium.ttf");
Typeface MLight = Typeface.createFromAsset(getAssets(),"fonts/MLight.ttf");
welcome= findViewById(R.id.welcome);
signsub= findViewById(R.id.signsub);
signText= findViewById(R.id.signText);
reset= findViewById(R.id.reset);
user= findViewById(R.id.userbox);
pwd= findViewById(R.id.pwd);
signing= findViewById(R.id.signBtn);
loginLogo= findViewById(R.id.login_logo);
welcome.setTypeface(MRegular);
signsub.setTypeface(MLight);
signText.setTypeface(MMedium);
reset.setTypeface(MLight);
user.setTypeface(MLight);
pwd.setTypeface(MLight);
signing.setTypeface(MMedium);
anim= AnimationUtils.loadAnimation(this,R.anim.sm_tobig);
loginLogo.startAnimation(anim);
headtext= AnimationUtils.loadAnimation(this,R.anim.head_text);
welcome.startAnimation(headtext);
signsub.startAnimation(headtext);
body_text= AnimationUtils.loadAnimation(this,R.anim.body_text);
body_text2= AnimationUtils.loadAnimation(this,R.anim.body_text2);
body_text3= AnimationUtils.loadAnimation(this,R.anim.body_text3);
user.startAnimation(body_text);
pwd.startAnimation(body_text2);
signing.startAnimation(body_text3);
reset.startAnimation(body_text3);
firebaseAuth= FirebaseAuth.getInstance();
reset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(LoginActiviity.this,signup.class);
startActivity(intent);
}
});
}
public void signingin(View view) {
user = findViewById(R.id.userbox);
pwd = findViewById(R.id.pwd);
String Email = user.getText().toString().trim();
String Password = pwd.getText().toString().trim();
firebaseAuth.signInWithEmailAndPassword(Email, Password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
currentUser = firebaseAuth.getCurrentUser();
Log.d("Error", "onComplete: "+task.toString()+currentUser);
startActivity(new Intent(getApplicationContext(),
RecyclerView.class));
}else {
Toast.makeText(LoginActiviity.this, "couldn't login",
Toast.LENGTH_SHORT).show();
}
}
});
}
}
Here in LoginActivity userbox is used for email.

Firebase won't find user id when signing in with Google

I've integrated Google Signin in to my app using Firebase. But when I log in with Google it logs in fine then crashes on my main activity because I need the user id and it can't find it giving this error in my log:
java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
Also if I sign in with email then sign in with a Google account it deletes my password from email sign in and won't allow me to authenticate using my email again unless I delete my account.
My code for login is
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//hides keyboard on start;
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
setContentView(com.example.harrops.h20droidapp2.R.layout.activity_login);
Intent intent = new Intent(Login.this, UpdateService.class);
startService(intent);
mAuth = FirebaseAuth.getInstance();
cbrememberme = (CheckBox) findViewById(R.id.cbrememberme);
mgo = (Button) findViewById(R.id.btnsubmit);
mgo.setText("Login");
memail = (EditText) findViewById(R.id.etemail);
mpass = (EditText) findViewById(R.id.etpass);
mforgot = (TextView) findViewById(R.id.tvforgotpass);
mreset = (Button) findViewById(R.id.btnreset);
mmember = (CheckBox) findViewById(R.id.cbexisiting);
loginPreferences = getSharedPreferences("loginPrefs", MODE_PRIVATE);
loginPrefsEditor = loginPreferences.edit();
saveLogin = loginPreferences.getBoolean("saveLogin", false);
if (saveLogin == true) {
memail.setText(loginPreferences.getString("username", ""));
mpass.setText(loginPreferences.getString("password", ""));
cbrememberme.setChecked(true);
signinnorm();
}
mmember.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (mmember.isChecked() == false) {
mgo.setText("Sign in");
memail.setHint("Sign up with a a valid email address");
} else {
mgo.setText("Register");
mpass.setHint("Enter new password");
}
}
});
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
SignInButton signInButton = (SignInButton) findViewById(R.id.sign_in_button);
findViewById(R.id.sign_in_button).setOnClickListener(this);
signInButton.setSize(SignInButton.SIZE_STANDARD);
mreset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mreset.setVisibility(View.GONE);
mpass.setVisibility(View.VISIBLE);
ResetPassword();
}
});
mforgot.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mpass.setVisibility(View.GONE);
mreset.setVisibility(View.VISIBLE);
}
});
mgo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!mmember.isChecked()) {
signinnorm();
} else {
signup();
}
}
});
}
private void signup() {
String email;
String password;
email = memail.getText().toString().trim();
password = mpass.getText().toString().trim();
if (TextUtils.isEmpty(email) || TextUtils.isEmpty(password)) {
memail.setHint(getString(R.string.ENTERYOUREMAIL));
memail.setHintTextColor(RED);
mpass.setHint(getString(R.string.ENTERYOURPASSWORD));
mpass.setHintTextColor(RED);
} else {
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "createUserWithEmail:success");
FirebaseUser user = mAuth.getCurrentUser();
mmember.setChecked(false);
cbrememberme.setChecked(true);
Toast.makeText(Login.this, "Thanks for signing up. click login in to continue", Toast.LENGTH_SHORT);
;
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "createUserWithEmail:failure", task.getException());
Toast.makeText(Login.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
}
});
}
}
private void signinnorm() {
String email = memail.getText().toString().trim();
String password = mpass.getText().toString().trim();
if (cbrememberme.isChecked()) {
loginPrefsEditor.putBoolean("saveLogin", true);
loginPrefsEditor.putString("username", email);
loginPrefsEditor.putString("password", password);
loginPrefsEditor.commit();
} else {
loginPrefsEditor.clear();
loginPrefsEditor.commit();
}
if (TextUtils.isEmpty(email) || TextUtils.isEmpty(password)) {
memail.setHint(getString(R.string.ENTERYOUREMAIL));
memail.setHintTextColor(RED);
mpass.setHint(getString(R.string.ENTERYOURPASSWORD));
mpass.setHintTextColor(RED);
} else {
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithEmail:success");
FirebaseUser user = mAuth.getCurrentUser();
startActivity(new Intent(Login.this, MainActivity.class));
finish();
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithEmail:failure", task.getException());
Toast.makeText(Login.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
}
});
}
}
private void ResetPassword() {
FirebaseAuth auth = FirebaseAuth.getInstance();
String emailAddress;
emailAddress = memail.getText().toString().trim();
auth.sendPasswordResetEmail(emailAddress)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "Email sent.");
}
}
});
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.sign_in_button:
signIn();
break;
}
}
private void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
handleSignInResult(result);
}
}
private void handleSignInResult(GoogleSignInResult result) {
if (result.isSuccess()) {
GoogleSignInAccount account = result.getSignInAccount();
firebaseAuthWithGoogle(account);
startActivity(new Intent(Login.this, MainActivity.class));
} else {
// Signed out, show unauthenticated UI.
}
}
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()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success");
FirebaseUser user = mAuth.getCurrentUser();
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
Toast.makeText(Login.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
// ...
}
});
}
Then in my main activity I call for user id calling this method in oncreate:
private void GetUser_Firebase() {
user = FirebaseAuth.getInstance().getCurrentUser();
userid = user.getUid();
DatabaseReference ref1 = mrootRef.getReference();
mloggedinas = (TextView) findViewById(R.id.tvloggedin);
ref1.child("User").child(userid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String m = dataSnapshot.child("screenname").getValue(String.class);
if (m == null) {
Toast.makeText(MainActivity.this, "Please fill in the above fields", Toast.LENGTH_LONG).show();
startActivity(new Intent(MainActivity.this, Edit_profile.class));
} else {
mloggedinas.setText(m);
}
}
Edit
Could I use this method on my main activity instead of login activity? This is from the Firebase website.
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()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success");
FirebaseUser user = mAuth.getCurrentUser();
updateUI(user);
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
Toast.makeText(GoogleSignInActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
updateUI(null);
}
// ...
}
});
}
I fixed the issue of having no it by calling the get user id method on sign up rather than my main activity.
I put it inside the Google auth method onSuccess.

How to separate two users in the firebase in android

In my application, I have two users--Event Member and Client--they have separate user login and registration. If a client log in he will go to the the client activity; if an event member will log in he will go to the event member activity. How will I make sure that the email is a client or an event member?
Below image shows my firebase structure:
Here is my code:
SignupClient.java
signupClient.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String cemail = clie_email.getText().toString().trim();
final String cpassword = clie_password.getText().toString().trim();
String ccpassword = clie_cpassword.getText().toString().trim();
final String cfname = clie_firstname.getText().toString().trim();
final String clname = clie_lastname.getText().toString().trim();
final String cbday = clie_birthday.getText().toString().trim();
final String ccountry = clie_country.getSelectedItem().toString();
final String cmobile = clie_mobile.getText().toString().trim();
auth.createUserWithEmailAndPassword(cemail, cpassword)
.addOnCompleteListener(_5_SignupClient.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Toast.makeText(_5_SignupClient.this, "createUserWithEmail: onComplete" + task.isSuccessful(), Toast.LENGTH_LONG).show();
if (!task.isSuccessful()){
Toast.makeText(_5_SignupClient.this, "Authentication Failed" + task.getException(),
Toast.LENGTH_LONG).show();
}
else {
AccountInfo accountInfo = new AccountInfo(cfname, clname, cemail, cpassword, cbday, ccountry, cmobile);
mDatabaseReference.child("client").push().setValue(accountInfo);
startActivity(new Intent(_5_SignupClient.this, _7_ViewClient.class));
finish();
}
}
});
}
});
LoginClient.java
loginClient.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String clie_unameemail = clie_emailuname.getText().toString();
final String clie_pass = clie_password.getText().toString();
if(TextUtils.isEmpty(clie_unameemail)){
Toast.makeText(getApplicationContext(), "Field cannot be empty", Toast.LENGTH_LONG).show();
return;
}
if(TextUtils.isEmpty(clie_pass)){
Toast.makeText(getApplicationContext(), "Field cannot be empty", Toast.LENGTH_LONG).show();
return;
}
auth.signInWithEmailAndPassword(clie_unameemail, clie_pass)
.addOnCompleteListener(_3_LoginClient.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
ref = FirebaseDatabase.getInstance().getReference().child("client");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
if(FirebaseAuth.getInstance().getCurrentUser().getUid().equals(snapshot.getKey())){
startActivity(new Intent(_3_LoginClient.this, _7_ViewClient.class));
}
}
// startActivity(new Intent(_3_LoginClient.this, Normal_memberActivity.class));
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
} else {
// User is signed out
}
// ...
}
};
if (!task.isSuccessful()) {
// there was an error
if (clie_pass.length() < 8) {
clie_password.setError(getString(R.string.minimum_password));
} else {
Toast.makeText(_3_LoginClient.this, getString(R.string.auth_failed), Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(_3_LoginClient.this, "Successfully Registered", Toast.LENGTH_LONG).show();
Intent intent = new Intent(_3_LoginClient.this, _7_ViewClient.class);
startActivity(intent);
finish();
}
}
});
}
});
I hope you could help me. Thank you!
On your db there should be one more field like we say it USER_TYPE. While registering the user send its USER_TYPE. suppose if you are registering a user as a CLIENT then inser db value USER_TYPE="CLIENT" and if its as an Event member registration then inser db value USER_TYPE="EVENT" and now once you logged in check its USER_TYPE and redirect him based upon his USER_TYPE

Facebook Login via Firebase - Access_Token_Denied Error

Facebook logs in correctly. In the Firebase console, I can see the user has logged. However, I cannot access any of the user's info.
I am getting below error log in LogCat:
signInWithFacebook:{AccessToken token:ACCESS_TOKEN_REMOVED
permissions:[public_profile, contact_email, user_friends, email]}
Afterwards, I also receive a FirebaseError: Permission denied in the LogCat and as a toast inside the app.
Following this tutorial, I have made a project that integrates Facebook and Firebase. I've tried copy and pasting the source code, and replacing the necessary lines (such as Facebook ID and Firebase URL) but it isn't working for me.
here is the specific void
private void signInWithFacebook(AccessToken token) {
Log.d(TAG, "signInWithFacebook:" + token.getToken());
showProgressDialog();
AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(TAG, "signInWithCredential: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()) {
Log.w(TAG, "signInWithCredential", task.getException());
Toast.makeText(LoginActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}else{
String uid=task.getResult().getUser().getUid();
String name=task.getResult().getUser().getDisplayName();
String email=task.getResult().getUser().getEmail();
String image=task.getResult().getUser().getPhotoUrl().toString();
//Create a new User and Save it in Firebase database
User user = new User(uid,name,null,email,name);
mRef.child(uid).setValue(user);
Log.d(TAG, uid);
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra("user_id",uid);
intent.putExtra("profile_picture",image);
startActivity(intent);
finish();
}
hideProgressDialog();
}
});
}
here is the full code
public class LoginActivity extends AppCompatActivity {
private static final String TAG = "AndroidBash";
public User user;
private EditText email;
private EditText password;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private ProgressDialog mProgressDialog;
private DatabaseReference mDatabase;
//Add YOUR Firebase Reference URL instead of the following URL
private Firebase mRef=new Firebase("https://firebase.firebaseio.com");
//FaceBook callbackManager
private CallbackManager callbackManager;
//
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mDatabase = FirebaseDatabase.getInstance().getReference();
mAuth = FirebaseAuth.getInstance();
FirebaseUser mUser = mAuth.getCurrentUser();
if (mUser != null) {
// User is signed in
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
String uid = mAuth.getCurrentUser().getUid();
String image=mAuth.getCurrentUser().getPhotoUrl().toString();
intent.putExtra("user_id", uid);
if(image!=null || image!=""){
intent.putExtra("profile_picture",image);
}
startActivity(intent);
finish();
Log.d(TAG, "onAuthStateChanged:signed_in:" + mUser.getUid());
}
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser mUser = firebaseAuth.getCurrentUser();
if (mUser != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + mUser.getUid());
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
}
}
};
//FaceBook
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
LoginButton loginButton = (LoginButton) findViewById(R.id.button_facebook_login);
loginButton.setReadPermissions("email", "public_profile");
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.d(TAG, "facebook:onSuccess:" + loginResult);
signInWithFacebook(loginResult.getAccessToken());
}
#Override
public void onCancel() {
Log.d(TAG, "facebook:onCancel");
}
#Override
public void onError(FacebookException error) {
Log.d(TAG, "facebook:onError", error);
}
});
//
}
#Override
protected void onStart() {
super.onStart();
email = (EditText) findViewById(R.id.edit_text_email_id);
password = (EditText) findViewById(R.id.edit_text_password);
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
//FaceBook
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
//
protected void setUpUser() {
user = new User();
user.setEmail(email.getText().toString());
user.setPassword(password.getText().toString());
}
public void onSignUpClicked(View view) {
Intent intent = new Intent(this, SignUpActivity.class);
startActivity(intent);
}
public void onLoginClicked(View view) {
setUpUser();
signIn(email.getText().toString(), password.getText().toString());
}
private void signIn(String email, String password) {
Log.d(TAG, "signIn:" + email);
if (!validateForm()) {
return;
}
showProgressDialog();
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(TAG, "signInWithEmail: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()) {
Log.w(TAG, "signInWithEmail", task.getException());
Toast.makeText(LoginActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
} else {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
String uid = mAuth.getCurrentUser().getUid();
intent.putExtra("user_id", uid);
startActivity(intent);
finish();
}
hideProgressDialog();
}
});
//
}
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);
}
return valid;
}
private void signInWithFacebook(AccessToken token) {
Log.d(TAG, "signInWithFacebook:" + token.getToken());
showProgressDialog();
AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(TAG, "signInWithCredential: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()) {
Log.w(TAG, "signInWithCredential", task.getException());
Toast.makeText(LoginActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}else{
String uid=task.getResult().getUser().getUid();
String name=task.getResult().getUser().getDisplayName();
String email=task.getResult().getUser().getEmail();
String image=task.getResult().getUser().getPhotoUrl().toString();
//Create a new User and Save it in Firebase database
User user = new User(uid,name,null,email,name);
mRef.child(uid).setValue(user);
Log.d(TAG, uid);
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra("user_id",uid);
intent.putExtra("profile_picture",image);
startActivity(intent);
finish();
}
hideProgressDialog();
}
});
}
public void showProgressDialog() {
if (mProgressDialog == null) {
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage(getString(R.string.loading));
mProgressDialog.setIndeterminate(true);
}
mProgressDialog.show();
}
public void hideProgressDialog() {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
}
}

Categories

Resources