The user signs up successfully and it show in Firebase. However, each time the user registers, the app crash although it can register successfully in Firebase. Is there any things I have configured wrongly?
reg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(TextUtils.isEmpty(email.getText().toString())||TextUtils.isEmpty(password.getText().toString()))
Toast.makeText(getApplicationContext(),"Please fill in all the detail",Toast.LENGTH_SHORT).show();
else if(password.getError()!=null||email.getError()!=null)
Toast.makeText(getApplicationContext(),"Please fill in the detail correctly",Toast.LENGTH_SHORT).show();
else{
signUp( );
}
}
});
}
//Sign Up method
private void signUp() {
String e=email.getText().toString().trim();
String p=password.getText().toString().trim();
mAuth.createUserWithEmailAndPassword(e,p).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d("SIGNIN", "Sign up Successfully" + task.isSuccessful());
if (!task.isSuccessful()) {
Toast.makeText(RegisterActivity.this, "Signed up Failed", Toast.LENGTH_SHORT).show();
}
else{
createNewAccount(task.getResult().getUser());
}
}
});
}
I think problem exists at here
private void createNewAccount(FirebaseUser user) {
String username = name.getText().toString().trim();
int point=0;
String date1="None";
// Write new user
writeNewUser(user.getUid(), username, user.getEmail(),point,date1);
// Go to MainActivity
startActivity(new Intent(RegisterActivity.this, RewardGainActivity.class));
}
private void writeNewUser(String userId, String Uname, String eMail, int pointss, String date11) {
User user=new User(Uname,eMail,pointss,date11);
mDatabase.child("users").child(userId).setValue(user);
}
public class User {
public String uName2;
public String eMail2;
public int point2;
public String Date2;
public User() {
// Default constructor required for calls to DataSnapshot.getValue(User.class)
}
public User(String uName2, String eMail2, int point2, String Date2) {
this.uName2=uName2;
this.eMail2=eMail2;
this.point2=point2;
this.Date2=Date2;
}
}
Related
I used firebase phone and google authentication in my app I am facing an issue that when a user logout and signing again though OTP or google it signup the user again by creating new user id and all the information that user update through profile update option erased and come back in original state as new user and all updates of profile lost.
My phone sign in code is here
PhoneAuthOptions options = PhoneAuthOptions.newBuilder(auth)
.setPhoneNumber(phoneNumber)
.setTimeout(120L, TimeUnit.SECONDS)
.setActivity(this)
.setCallbacks(new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(#NonNull PhoneAuthCredential phoneAuthCredential) {
}
#Override
public void onVerificationFailed(#NonNull FirebaseException e) {
}
#Override
public void onCodeSent(#NonNull String verifyId, #NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(verifyId, forceResendingToken);
verificationId = verifyId;
}
}).build();
PhoneAuthProvider.verifyPhoneNumber(options);
}
public void callNextScreen(View view) {
dialog.show();
String otp = binding.otpView.getText().toString();
if (otp!= null) {
verifyOTP(otp);
} else {
Toast.makeText(this, "Enter code", Toast.LENGTH_LONG).show();
}
}
private void verifyOTP(String otp) {
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, otp);
auth.signInWithCredential(credential).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
String uid = auth.getCurrentUser().getUid();
String phoneNumber = auth.getCurrentUser().getPhoneNumber();
User users = new User();
users.setPhone(phoneNumber);
database
.collection("users")
.document(uid)
.set(users).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
dialog.dismiss();
Intent intent = new Intent(OTP_Activity.this, MainActivity.class);
startActivity(intent);
finishAffinity();
} else {
dialog.dismiss();
Toast.makeText(OTP_Activity.this, task.getException().getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
}
});
} else {
dialog.dismiss();
Toast.makeText(OTP_Activity.this, task.getException().getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
and my user attributes and user class constructor looks like this
private String name, email, image, phone, gender;
private long coins = 500;
public User(String name, String email, String image, String phone, String gender) {
this.name = name;
this.email = email;
this.image = image;
this.phone = phone;
this.gender = gender;
}
public User() {
}
this is how creating user profile with google signing
private void firebaseAuthWithGoogle(String idToken){
AuthCredential firebaseCredential = GoogleAuthProvider.getCredential(idToken, null);
auth.signInWithCredential(firebaseCredential)
.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 = auth.getCurrentUser();
String uid = user.getUid();
User newUser = new User();
newUser.setName(user.getDisplayName());
newUser.setEmail(user.getEmail());
newUser.setImage(user.getPhotoUrl().toString());
database
.collection("users")
.document(uid)
.set(newUser).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
dialog.dismiss();
Intent intent = new Intent(SignupActivity.this, MainActivity.class);
startActivity(intent);
finishAffinity();
} else {
dialog.dismiss();
Log.w("TAG", "signInWithCredential:failure", task.getException());
Toast.makeText(SignupActivity.this, task.getException().getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
}
});
} else {
dialog.dismiss();
// If sign in fails, display a message to the user.
Toast.makeText(SignupActivity.this, "Signup Failed", Toast.LENGTH_SHORT).show();
// updateUI(null);
}
}
});
}
My App having the Phone authentication method for user register and login to firebase is working fine for some devices but in one device it had send the verification SMS only the first time i checked it. After that ,I even deleted that account from firebase console but it is not sending any verfication code on registering that number again.
public class phone_no_verification extends AppCompatActivity {
ProgressBar verify_progress;
TextInputEditText verify_edittext;
TextInputLayout verify_textInput;
String mverificationID;
FirebaseAuth auth;
static String TAG;
SharedPreferences sp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_phone_no_verification);
verify_progress = findViewById(R.id.verify_progress);
verify_edittext = findViewById(R.id.verify_edittext);
verify_textInput = findViewById(R.id.verify_textinputLayout);
auth = FirebaseAuth.getInstance();
//getting Intent mobile number
Intent intent = getIntent();
String mobile = intent.getStringExtra("mobile_no");
sendVerificationcode(mobile);
//Entering code manually
findViewById(R.id.verify_Button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String code = verify_edittext.getText().toString().trim();
if(code.isEmpty() || code.length() < 6){
verify_textInput.setError("Enter Valid code");
}
else{
verifyVerificationCode(code);}
}
});
}
private void sendVerificationcode(String mobile) {
PhoneAuthProvider.getInstance().verifyPhoneNumber
("+91" + mobile,60, TimeUnit.SECONDS,
TaskExecutors.MAIN_THREAD,mcallbacks);
}
//callback to detect verification status
PhoneAuthProvider.OnVerificationStateChangedCallbacks mcallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onCodeSent(#NonNull String s, #NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
mverificationID = s;
}
#Override
public void onVerificationCompleted(#NonNull PhoneAuthCredential phoneAuthCredential) {
Log.d(TAG, "onVerificationCompleted:" + phoneAuthCredential);
String code = phoneAuthCredential.getSmsCode();
if(code != null){
verify_edittext.setText(code);
verifyVerificationCode(code);
}
}
#Override
public void onVerificationFailed(#NonNull FirebaseException e) {
Toast.makeText(phone_no_verification.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
};
private void verifyVerificationCode(String code) {
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(mverificationID,code);
//signing user
signInWithPhoneAuthCredential(credential);
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
auth.signInWithCredential(credential).addOnCompleteListener(phone_no_verification.this
, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Intent intent = new Intent(phone_no_verification.this, Basic_activity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
sp = getSharedPreferences("login",MODE_PRIVATE);
sp.edit().putBoolean("isAutheticated",true).apply();
}
else{
String message = "Somthing is wrong, we will fix it soon...";
if(task.getException() instanceof FirebaseAuthInvalidCredentialsException){
message = "Invalid code Entered..";
}
else if(task.getException() instanceof FirebaseAuthUserCollisionException){
message = "User Already Exists";
}
Toast.makeText(phone_no_verification.this,message,Toast.LENGTH_LONG).show();
}
}
});
}
}
I am currently trying to add user details who have registered in my app using Firebase Phone authentication to Firebase Real time database. I am successfully able to verify a user, but I am not able to send to Details Activity class where I need the user to enter his details, instead I jump to MainActivity Directly.
I do get Toast "Phone Verified" whenever I add a new user.
Register.java
public class Register extends AppCompatActivity {
FirebaseAuth auth;
String phoneNumber;
String otpCode;
String verificationId;
EditText phone, optEnter;
Button next;
CountryCodePicker countryCodePicker;
PhoneAuthCredential credential;
Boolean verificationOnProgress = false;
ProgressBar progressBar;
TextView state, resend;
PhoneAuthProvider.ForceResendingToken token;
//FirebaseFirestore fStore;
DatabaseReference reference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
phone = findViewById(R.id.phone);
optEnter = findViewById(R.id.codeEnter);
countryCodePicker = findViewById(R.id.ccp);
next = findViewById(R.id.nextBtn);
auth = FirebaseAuth.getInstance();
progressBar = findViewById(R.id.progressBar);
state = findViewById(R.id.state);
resend = findViewById(R.id.resendOtpBtn);
resend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// todo:: resend OTP
}
});
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!phone.getText().toString().isEmpty() && phone.getText().toString().length() == 10) {
if (!verificationOnProgress) {
next.setEnabled(false);
progressBar.setVisibility(View.VISIBLE);
state.setVisibility(View.VISIBLE);
String phoneNum = "+" + countryCodePicker.getSelectedCountryCode() + phone.getText().toString();
Log.d("phone", "Phone No.: " + phoneNum);
requestPhoneAuth(phoneNum);
} else {
next.setEnabled(false);
optEnter.setVisibility(View.GONE);
progressBar.setVisibility(View.VISIBLE);
state.setText("Logging in");
state.setVisibility(View.VISIBLE);
otpCode = optEnter.getText().toString();
if (otpCode.isEmpty()) {
optEnter.setError("Required");
return;
}
credential = PhoneAuthProvider.getCredential(verificationId, otpCode);
verifyAuth(credential);
}
} else {
phone.setError("Valid Phone Required");
}
}
});
}
private void requestPhoneAuth(String phoneNumber) {
PhoneAuthProvider.getInstance().verifyPhoneNumber(phoneNumber, 60L, TimeUnit.SECONDS, this,
new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onCodeAutoRetrievalTimeOut(String s) {
super.onCodeAutoRetrievalTimeOut(s);
Toast.makeText(Register.this, "OTP Timeout, Please Re-generate the OTP Again.", Toast.LENGTH_SHORT).show();
resend.setVisibility(View.VISIBLE);
}
#Override
public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
verificationId = s;
token = forceResendingToken;
verificationOnProgress = true;
progressBar.setVisibility(View.GONE);
state.setVisibility(View.GONE);
next.setText("Verify");
next.setEnabled(true);
optEnter.setVisibility(View.VISIBLE);
}
#Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
verifyAuth(phoneAuthCredential);
}
#Override
public void onVerificationFailed(FirebaseException e) {
Toast.makeText(Register.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void verifyAuth(PhoneAuthCredential credential) {
auth.signInWithCredential(credential).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(Register.this, "Phone Verified", Toast.LENGTH_SHORT).show();
checkUserProfile();
} else {
progressBar.setVisibility(View.GONE);
state.setVisibility(View.GONE);
Toast.makeText(Register.this, "Can not Verify phone and Create Account.", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
protected void onStart() {
super.onStart();
if (auth.getCurrentUser() != null) {
progressBar.setVisibility(View.VISIBLE);
state.setText("Logging IN");
state.setVisibility(View.VISIBLE);
checkUserProfile();
}
}
private void checkUserProfile() {
FirebaseUser firebaseUser = auth.getCurrentUser();
assert firebaseUser != null;
String userid = firebaseUser.getUid();
reference = FirebaseDatabase.getInstance().getReference("Users").child(userid);
if (userid != null) {
Intent intent = new Intent(Register.this, MainActivity.class);
startActivity(intent);
} else {
Toast.makeText(Register.this, "Profile doesnt exist", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Register.this, Details.class);
startActivity(intent);
}
}
}
Details.java
public class Details extends AppCompatActivity {
public static final String TAG = "TAG";
EditText firstName,lastName,email;
Button saveBtn;
FirebaseAuth auth;
FirebaseFirestore fStore;
String userID;
DatabaseReference reference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
firstName = findViewById(R.id.firstName);
lastName = findViewById(R.id.lastName);
email = findViewById(R.id.emailAddress);
saveBtn = findViewById(R.id.saveBtn);
auth = FirebaseAuth.getInstance();
fStore = FirebaseFirestore.getInstance();
saveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String First_Name= firstName.getText().toString();
String Last_Name= lastName.getText().toString();
String EMail= email.getText().toString();
if(firstName.getText().toString().isEmpty()||lastName.getText().toString().isEmpty() || email.getText().toString().isEmpty()){
Toast.makeText(Details.this, "Fill the required Details", Toast.LENGTH_SHORT).show();
return;
}
register(First_Name,Last_Name,EMail);
}
});
}
private void register(String first_name, String last_name, String eMail) {
FirebaseUser firebaseUser = auth.getCurrentUser();
assert firebaseUser != null;
String userid = firebaseUser.getUid();
reference = FirebaseDatabase.getInstance().getReference("Users").child(userid);
Map<String,Object> hashmap=new HashMap<>();
hashmap.put("First Name",first_name);
hashmap.put("Last Name",last_name);
hashmap.put("Email-Id",eMail);
reference.setValue(hashmap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Intent intent=new Intent(Details.this,MainActivity.class);
startActivity(intent);
}
else{
Toast.makeText(Details.this,"Registration failed...",Toast.LENGTH_SHORT).show();
}
}
});
}
}
It seems that in your Register class in checkUserProfile() function you are checking if userId from firebaseUser.getUid() is not null. At the moment this will always be not null, because you are already asserting that the user must be authenticated at this point.
Judging from your code this is just a mistake on your part. I assume that what you are trying to do is actually see if the details already exist in the FirebaseDatabase. You have a reference to the database which you are not using.
private void checkUserProfile() {
FirebaseUser firebaseUser = auth.getCurrentUser();
assert firebaseUser != null;
String userid = firebaseUser.getUid();
//Unused reference
reference = FirebaseDatabase.getInstance().getReference("Users").child(userid);
if (userid != null) {
Intent intent = new Intent(Register.this, MainActivity.class);
startActivity(intent);
}
But also my question would be, are you sure you want to use Realtime Database for user details? You are saving details in Details function using FirebaseFirestore. Didn't you want to check if the details already exist in FirebaseFirestore?
How to fix:
First, let's create the user data class:
public class User {
public String uid;
public String firstName;
public String lastName;
public String email;
public User {
// Default constructor required for calls to DataSnapshot.getValue(User.class)
}
public User(String uid, String firstName, String lastName, String email) {
this.uid = uid;
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
}
Now, let's change the code in Details.java class to use User class:
private void register(String first_name, String last_name, String eMail) {
FirebaseUser firebaseUser = auth.getCurrentUser();
assert firebaseUser != null;
String userid = firebaseUser.getUid();
reference = FirebaseDatabase.getInstance().getReference("Users").child(userid);
User user = new User(userid, firstName, lastName, eMail)
reference.setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Intent intent=new Intent(Details.this,MainActivity.class);
startActivity(intent);
}
else{
Toast.makeText(Details.this,"Registration failed...",Toast.LENGTH_SHORT).show();
}
}
});
}
Let's check if the registration details exist in the database in checkUserProfile() method:
private void checkUserProfile() {
FirebaseUser firebaseUser = auth.getCurrentUser();
assert firebaseUser != null;
String userid = firebaseUser.getUid();
reference = FirebaseDatabase.getInstance().getReference("Users").child(userid);
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
Intent intent = new Intent(Register.this, MainActivity.class);
startActivity(intent);
}
else {
Toast.makeText(Register.this, "Profile doesnt exist", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Register.this, Details.class);
startActivity(intent);
}
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
}
});
}
Let me know if it works for you.
Firebase will generate a single unique key(UID) on registration of account whether using Email/Phone number. This key remains associated with that account until the account exists in the firebase authentication list.
So, once you register with some number/email at that time UID is created for the same. every time you fetch UID it will return that user UID, and you are also asserting Firebase User is NotNull So, every time you got UID from firebase and app move to the dashboard screen.
If you want to move users to a Detail screen then. You can also add a condition based on firebase User.
if(firebaseUser != null){
// Get UID and Move to Dashboard
}else{
// Move to Detail Screen
}
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
Hello I'm new to Android development. I am currently trying to build a basic android application with Google's Firebase as its backend system.
I have a "Login with Facebook" button, whenever this button is clicked it opens up a dialog where the user enters his facebook credentials in order to get access to the application. When that's done, I want to store his email, name and id in Firebase if it's his first time logging in, if it's not his first time logging in I want to update his information.
I made a class called User (POJO) that I will use to represent this data. My problem is that I don't seem to know where to put the code that stores this information.
Here's my MainActivity class:
public class MainActivity extends AppCompatActivity {
//Declare our view variables
private LoginButton mLoginButton;
private CallbackManager mCallbackManager;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private FirebaseDatabase mDatabase;
private DatabaseReference mDatabaseReference;
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_main);
//Initialize callback manager
mCallbackManager = CallbackManager.Factory.create();
//Assign the views to the corresponding variables
mLoginButton = (LoginButton) findViewById(R.id.login_button);
//Assign the button permissions
mLoginButton.setReadPermissions("email", "public_profile");
//Create instance of database
mDatabase = FirebaseDatabase.getInstance();
mDatabaseReference = mDatabase.getReference();
//Assign the button a task
mLoginButton.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.d(TAG, "facebook:onSuccess:" + loginResult);
handleFacebookAccessToken(loginResult.getAccessToken());
}
#Override
public void onCancel() {
Log.d(TAG, "facebook:onCancel");
}
#Override
public void onError(FacebookException error) {
Log.d(TAG, "facebook:onError", error);
}
});
// Initialize Firebase Auth
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
//Get currently logged in user
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
// Name, email address
String name = user.getDisplayName();
String email = user.getEmail();
// The user's ID, unique to the Firebase project. Do NOT use this value to
// authenticate with your backend server, if you have one. Use
// FirebaseUser.getToken() instead.
String uid = user.getUid();
//Create user
final User loggedIn = new User(uid, name, email);
mDatabaseReference.child("users").child(loggedIn.getId()).setValue(loggedIn);
mDatabaseReference.child("users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
}
});
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
}
}
};
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Pass the activity result back to the Facebook SDK
mCallbackManager.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
//If user successfully signs in the LoginButton's onSuccess callback method
// get an access token for the signed-in user, exchange it for a Firebase credential
// and authenticate with Firebase using the Firebase credential
private void handleFacebookAccessToken(AccessToken token) {
Log.d(TAG, "handleFacebookAccessToken:" + token);
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(MainActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show();
}
}
});
}
}
Here's my User class:
public class User {
private String id;
private String name;
private String email;
public User(){
}
public User(String id, String name, String email) {
this.id = id;
this.name = name;
this.email = email;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Thank you for your time
You've already done the most work, so i am going to create two methods for you to use.
protected void getUserInfo(final LoginResult login_result){
GraphRequest data_request = GraphRequest.newMeRequest(
login_result.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
try {
String facebook_id = object.getString("id");
String f_name = object.getString("name");
String email_id = object.getString("email");
String token = login_result.getAccessToken().getToken();
String picUrl = "https://graph.facebook.com/me/picture?type=normal&method=GET&access_token="+ token;
saveFacebookCredentialsInFirebase(login_result.getAccessToken());
} catch (JSONException e) {
// TODO Auto-generated catch block
}
}
});
Bundle permission_param = new Bundle();
permission_param.putString("fields", "id,name,email,picture.width(120).height(120)");
data_request.setParameters(permission_param);
data_request.executeAsync();
data_request.executeAsync();
}
This is where you save the data in firebase
private void saveFacebookCredentialsInFirebase(AccessToken accessToken){
AuthCredential credential = FacebookAuthProvider.getCredential(accessToken.getToken());
firebaseAuth.signInWithCredential(credential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(!task.isSuccessful()){
Toast.makeText(getApplicationContext(),"Error logging in", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(),"Login in Successful", Toast.LENGTH_LONG).show();
}
}
});
}
I downgraded firebase to 9.6.0 to avoid the Google Play Services errors and I saved the user after he signs in with his credentials in the handleFacebookAccessToken method.