After pressing verify button to send me the code the application opens browser and wait sometime. Nothing happens and no SMS sent to me and this toast appears to me. before you ask i made everything before, firebase and and SHA certificate fingerprints.
public class PhoneSingUp extends AppCompatActivity {
private FirebaseAuth auth;
TextView SignUpTXT , VerifyingTXT , ErrorTXT ;
GifImageView VerifySuccess ;
Button VerifyBTN , ContinueBTN ;
CountryCodePicker ccp;
EditText NumberEnt;
PinView VerifyPIN;
String VerifyCodeBySystem , Code , CountryCodeS ,UserEnteredNumber , PhoneNumber;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_phone_sing_up);
auth = FirebaseAuth.getInstance();
SignUpTXT = findViewById(R.id.SingUpTXT);
ccp = (CountryCodePicker) findViewById(R.id.ccp);
NumberEnt = (EditText) findViewById(R.id.editText_carrierNumber);
VerifyingTXT = findViewById(R.id.verifyingTXT);
ErrorTXT = findViewById(R.id.ErrorTXT);
VerifyPIN = findViewById(R.id.VerificationPIN);
VerifySuccess = findViewById(R.id.VerifySuccess);
VerifyBTN = findViewById(R.id.VerifyBTN);
VerifyBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CountryCodeS = ccp.getSelectedCountryCode();
UserEnteredNumber = NumberEnt.getText().toString();
PhoneNumber = "+" + CountryCodeS + UserEnteredNumber;
if (PhoneNumber.length() < 13){
ErrorTXT.setVisibility(View.VISIBLE);
VerifyingTXT.setVisibility(View.INVISIBLE);
}else {
if (PhoneNumber.length() == 13) {
ErrorTXT.setVisibility(View.GONE);
VerifyingTXT.setVisibility(View.VISIBLE);
sendVerificationCode(PhoneNumber);
}
}
}
});
ContinueBTN = findViewById(R.id.ContinueBTN);
ContinueBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(PhoneSingUp.this, MainActivity.class));
finish();
}
});
}
private void sendVerificationCode(String phoneNumber) {
PhoneAuthOptions options =
PhoneAuthOptions.newBuilder(auth)
.setPhoneNumber(phoneNumber) // Phone number to verify
.setTimeout(60L, TimeUnit.SECONDS) // Timeout and unit
.setActivity(PhoneSingUp.this) // Activity (for callback binding)
.setCallbacks(mCallbacks) // OnVerificationStateChangedCallbacks
.build();
PhoneAuthProvider.verifyPhoneNumber(options);
}
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onCodeSent(#NonNull String s, #NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
VerifyCodeBySystem = s;
}
#Override
public void onVerificationCompleted(#NonNull PhoneAuthCredential phoneAuthCredential) {
Code = phoneAuthCredential.getSmsCode();
if (Code != null){
VerifyPIN.setText(Code);
VerifyCode(Code);
VerifySuccess.setVisibility(View.VISIBLE);
}
}
#Override
public void onVerificationFailed(#NonNull FirebaseException e) {
Toast.makeText(PhoneSingUp.this,e.getMessage(), Toast.LENGTH_LONG).show();
}
};
private void VerifyCode(String code) {
PhoneAuthCredential phoneAuthCredential = PhoneAuthProvider.getCredential(VerifyCodeBySystem,code);
signInWithPhoneAuthCredential(phoneAuthCredential);
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential phoneAuthCredential) {
auth.signInWithCredential(phoneAuthCredential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
} else {
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
}
}
}
});
}
}
Related
Made registration using Firebase. I need that when clicking on the same CardView different DialogFragment opens and the condition is whether the user is logged in or not, i.e. by clicking on the CardView, DialogFragment1 opens in which the user logs in, if everything is successful DialogFragment1 is closed and when the CardView is pressed again, DialogFragment2 is opened, how to do this?
My dialog through which the user logs in
public class FragmentDialogLogin extends Fragment {
public static CardView close_dl, login_LG;
public static boolean isRememberUserLogin;
CardView registration;
public static EditText User_Name_LG;
public static EditText User_Password_LG;
public static String name;
public static String surname;
public static String email;
FirebaseAuth firebaseAuth;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
#SuppressLint("StaticFieldLeak")
public static LinearLayout Ll_LG;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_dialog_login, container, false);
}
#SuppressLint("SetJavaScriptEnabled")
#Override
public void onViewCreated(#NonNull final View view, #Nullable Bundle savedInstanceState) {
firebaseAuth = FirebaseAuth.getInstance();
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference("Users");
close_dl = view.findViewById(R.id.close_dl);
close_dl.setOnClickListener(v -> {
closeDialog();
});
registration = view.findViewById(R.id.registration);
registration.setOnClickListener(v -> {
int current = DialogAuthorization.VP_dialog_authorization.getCurrentItem();
int totalItems = DialogAuthorization.VP_dialog_authorization.getAdapter().getCount();
if (current < totalItems - 1) {
DialogAuthorization.VP_dialog_authorization.setCurrentItem(current + 1, true);
}
});
User_Name_LG = view.findViewById(R.id.User_Name_LG);
User_Password_LG = view.findViewById(R.id.User_Password_LG);
login_LG = view.findViewById(R.id.login_LG);
login_LG.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = User_Name_LG.getText().toString().trim();
String password = User_Password_LG.getText().toString().trim();
if (TextUtils.isEmpty(email)) {
User_Name_LG.setError("Email is Required.");
return;
}
if (TextUtils.isEmpty(password)) {
User_Password_LG.setError(getText(R.string.Rink));
return;
}
if (password.length() < 6) {
User_Password_LG.setError("Password Must be >= 6 Characters");
return;
}
firebaseAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(getContext(), "Logged in Successfully", Toast.LENGTH_SHORT).show();
DialogProfile dialog = new DialogProfile();
dialog.show(requireFragmentManager(), "DialogProfile");
} else {
Toast.makeText(getContext(), "Error ! " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
private void closeDialog() {
Fragment prev = requireActivity().getSupportFragmentManager().findFragmentByTag("DialogAuthorization");
if (prev != null) {
DialogAuthorization df = (DialogAuthorization) prev;
df.dismiss();
}
}
}
The simplest way to check whether user logged in or not is to call getCurrentUser();
private DatabaseReference rootReference;
private DatabaseReference usersRef;
#SuppressLint("SetJavaScriptEnabled")
#Override
public void onViewCreated(#NonNull final View view, #Nullable Bundle savedInstanceState) {
...
rootReference = FirebaseDatabase.getInstance().getReference();
usersRef = rootReference.child("Users");
...
login_LG.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
...
// User already logged in
if (firebaseAuth.getCurrentUser() != null) {
// Todo: close dialog fragment 1 and open dialog fragment 2
return;
}
// user did not log in
firebaseAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Store that user logged in with email
String currentUserId = firebaseAuth.getCurrentUser().getUid();
rootReference.child("Users").child(currentUserId).setValue("email");
Toast.makeText(getContext(), "Logged in Successfully", Toast.LENGTH_SHORT).show();
DialogProfile dialog = new DialogProfile();
dialog.show(requireFragmentManager(), "DialogProfile");
} else {
Toast.makeText(getContext(), "Error ! " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
You can add the int at the class as increment. You can do something like this.
At the class.
public static String surname;
public static String email;
private int counter = 1; //Add this one.
And then at the method onComplete()
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(getContext(), "Logged in Successfully", Toast.LENGTH_SHORT).show();
if (counter >1){
//DialogFragment2
}else{
DialogProfile dialog = new DialogProfile();
dialog.show(requireFragmentManager(), "DialogProfile");
counter++; //increment
}
} else {
Toast.makeText(getContext(), "Error ! " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
I'm trying to authenticate user with phone number using the firebase Authentication method. But it is showing me error after some time by running the code. And I think the sendVerificationCodeToUser() function is not working properly.
package com.example.foodapp;
import ...
public class PhoneVerification<phoneAuthProvider> extends AppCompatActivity {
String verificationCodeBySystem;
Button btn_verify;
EditText phoneenteredbyuser;
ProgressBar progressbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_phone_verification);
btn_verify = findViewById(R.id.btn_verify);
phoneenteredbyuser = findViewById(R.id.txt_otp);
progressbar = findViewById(R.id.progressbar);
progressbar.setVisibility(View.GONE);
String phoneNo = getIntent().getStringExtra("phone");
sendVerificationCodeToUser(phoneNo);
btn_verify.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String code= phoneenteredbyuser.toString();
if(code.isEmpty() || code.length()< 6){
phoneenteredbyuser.setError("Wrong OTP...");
phoneenteredbyuser.requestFocus();
return;
}
progressbar.setVisibility(View.VISIBLE);
verifyCode(code);
}
});
}
private void sendVerificationCodeToUser(String phoneNo) {
FirebaseAuth mAuth= FirebaseAuth.getInstance();
PhoneAuthOptions options =
PhoneAuthOptions.newBuilder(mAuth)
.setPhoneNumber("+92" + phoneNo) // Phone number to verify
.setTimeout(60L, TimeUnit.SECONDS) // Timeout and unit
.setActivity(this) // Activity (for callback binding)
.setCallbacks(mCallbacks) // OnVerificationStateChangedCallbacks
.build();
PhoneAuthProvider.verifyPhoneNumber(options);
}
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override //Entering OTP by manual way
public void onCodeSent(#NonNull String s, #NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
verificationCodeBySystem = s;
}
#Override // Automatically Verifying the OTP by system.
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
String code = phoneAuthCredential.getSmsCode();
if (code != null) {
progressbar.setVisibility(View.VISIBLE);
verifyCode(code);
}
}
#Override //In case of error this code will run.
public void onVerificationFailed(FirebaseException e) {
Toast.makeText(PhoneVerification.this, "Error Occured", Toast.LENGTH_SHORT).show();
}
};
private void verifyCode(String codeByUser) {
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationCodeBySystem, codeByUser);
signInUserByCredentials(credential);
}
private void signInUserByCredentials(PhoneAuthCredential credential) {
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
firebaseAuth.signInWithCredential(credential)
.addOnCompleteListener(PhoneVerification.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(PhoneVerification.this, "Your Account has been created successfully!", Toast.LENGTH_SHORT).show();
//Perform Your required action here to either let the user sign In or do something required
Intent intent = new Intent(getApplicationContext(), User_Home.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
} else {
Toast.makeText(PhoneVerification.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
}
I want to create Phone Auth Credential like Uber, I mean when user use the app for the first time he has to complete his registration information after phone authentication then he will be able to move to DriverHome Activity, but next time he uses the authentication he will redirect to the DriverHome Activity automatically.
I've used Phone Auth Credential code and it works fine but I need to add the part is responsible for checking if the user registered before or not.
public class VerifyPhoneActivity extends AppCompatActivity {
private String verificationId;
private FirebaseAuth mAuth;
FirebaseAuth.AuthStateListener mAuthListener;
DatabaseReference users;
ProgressBar progressBar;
TextInputEditText editText;
AppCompatButton buttonSignIn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_verification_code);
mAuth = FirebaseAuth.getInstance();
progressBar = findViewById(R.id.progressbar);
editText = findViewById(R.id.editTextCode);
buttonSignIn = findViewById(R.id.buttonSignIn);
String phoneNumber = getIntent().getStringExtra("phoneNumber");
sendVerificationCode(phoneNumber);
// save phone number
SharedPreferences prefs = getApplicationContext().getSharedPreferences("USER_PREF",
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("phoneNumber", phoneNumber);
editor.apply();
buttonSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String code = editText.getText().toString().trim();
if (code.isEmpty() || code.length() < 6) {
editText.setError("Enter code...");
editText.requestFocus();
return;
}
verifyCode(code);
}
});
}
private void verifyCode(String code) {
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code);
signInWithCredential(credential);
}
private void signInWithCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Intent intent = new Intent(VerifyPhoneActivity.this, DriverHomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}else {
Toast.makeText(VerifyPhoneActivity.this, task.getException().getMessage(), Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
}
}
});
}
private void sendVerificationCode(String number) {
progressBar.setVisibility(View.VISIBLE);
PhoneAuthProvider.getInstance().verifyPhoneNumber(
number,
60,
TimeUnit.SECONDS,
TaskExecutors.MAIN_THREAD,
mCallBack
);
progressBar.setVisibility(View.GONE);
}
private PhoneAuthProvider.OnVerificationStateChangedCallbacks
mCallBack = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
verificationId = s;
}
#Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
String code = phoneAuthCredential.getSmsCode();
if (code != null) {
editText.setText(code);
verifyCode(code);
}
}
#Override
public void onVerificationFailed(FirebaseException e) {
Toast.makeText(VerifyPhoneActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
}
};
}
before onCreateView
check if sharepreference has phone number if it has then using startActivity(new Intent(this, DriverHomeActivity.class); to go directly to driverhome activity
if sharepreference has no phone number then
Save phone number in sharepreference if onComplete function of signInWithCredential return successful using isSucessful
public class VerifyPhoneActivity extends AppCompatActivity {
private String verificationId;
private FirebaseAuth mAuth;
FirebaseAuth.AuthStateListener mAuthListener;
DatabaseReference users;
ProgressBar progressBar;
TextInputEditText editText;
AppCompatButton buttonSignIn;
SharedPreferences prefs ;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
prefs = getApplicationContext().getSharedPreferences("USER_PREF",
Context.MODE_PRIVATE);
editor = prefs.edit();
//add this line
if(prefs.getString("phoneNumber", null) != null)
startActivity(new Intent(this, DriverHomeActivity.class));
setContentView(R.layout.activity_verification_code);
mAuth = FirebaseAuth.getInstance();
progressBar = findViewById(R.id.progressbar);
editText = findViewById(R.id.editTextCode);
buttonSignIn = findViewById(R.id.buttonSignIn);
String phoneNumber = getIntent().getStringExtra("phoneNumber");
sendVerificationCode(phoneNumber);
buttonSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String code = editText.getText().toString().trim();
if (code.isEmpty() || code.length() < 6) {
editText.setError("Enter code...");
editText.requestFocus();
return;
}
verifyCode(code);
}
});
}
private void verifyCode(String code) {
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code);
signInWithCredential(credential);
}
private void signInWithCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
//insert data if task is successful
editor.putString("phoneNumber", phoneNumber);
editor.apply();
Intent intent = new Intent(VerifyPhoneActivity.this, DriverHomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}else {
Toast.makeText(VerifyPhoneActivity.this, task.getException().getMessage(), Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
}
}
});
}
private void sendVerificationCode(String number) {
progressBar.setVisibility(View.VISIBLE);
PhoneAuthProvider.getInstance().verifyPhoneNumber(
number,
60,
TimeUnit.SECONDS,
TaskExecutors.MAIN_THREAD,
mCallBack
);
progressBar.setVisibility(View.GONE);
}
private PhoneAuthProvider.OnVerificationStateChangedCallbacks
mCallBack = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
verificationId = s;
}
#Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
String code = phoneAuthCredential.getSmsCode();
if (code != null) {
editText.setText(code);
verifyCode(code);
}
}
#Override
public void onVerificationFailed(FirebaseException e) {
Toast.makeText(VerifyPhoneActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
}
};
I am trying to set up OTP verification
I have already tried many possibilities with the if and else, however, it didn't help out.
public class userLogin extends Activity {
EditText phnNum=null, veri = null;
FirebaseAuth au;
Button forgotpass, login;
PhoneAuthProvider.OnVerificationStateChangedCallbacks otp;
String verifyCode;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.userlogin);
login = findViewById(R.id.loginButton);
phnNum = findViewById(R.id.enter_phone);
forgotpass = findViewById(R.id.forgot_pass);
au = FirebaseAuth.getInstance();
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if ((phnNum.getText().toString()).equals("")) {
(Toast.makeText(getApplicationContext(), "Please enter the phone number and proceed to receive an OTP", Toast.LENGTH_SHORT)).show();
}
else{
otp = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(#NonNull PhoneAuthCredential phoneAuthCredential) {
}
#Override
public void onVerificationFailed(#NonNull FirebaseException e) {
}
#Override
public void onCodeSent(#NonNull String s, #NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
verifyCode = s;
(Toast.makeText(getApplicationContext(), "The OTP Code has been send, please verify the code", Toast.LENGTH_SHORT)).show();
}
};
}
}
});
}
public void send_sms (View v){
String i = (phnNum.getText()).toString();
PhoneAuthProvider.getInstance().verifyPhoneNumber(i, 60, TimeUnit.SECONDS, this, otp);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent u = new Intent(view.getContext(), otp_verify.class);
startActivity(u);
}
});
}
//SignIn Method
// We will pass value in the method with "PhoneAuthCredential" data-type.
public void SignIn(PhoneAuthCredential credential) {
//" au " is the firebase variable and call the method
au.signInWithCredential(credential).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
(Toast.makeText(getApplicationContext(), "You have Sign-In Successfully", Toast.LENGTH_SHORT)).show();
}
else{
(Toast.makeText(getApplicationContext(), "Please try again", Toast.LENGTH_SHORT)).show();
}
}
});
}
}
When I log-in with blank EditText, the if part executes but when I enter the phone number it doesn't execute the else part. I expect the when the user enters their phone number the else part should execute.
final String i = (phnNum.getText()).toString();
if ("".equals(i)) {
(Toast.makeText(getApplicationContext(), "Please enter the phone number and proceed to receive an OTP", Toast.LENGTH_SHORT)).show();
} else {
// 1. prepare callback for async call
otp = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(#NonNull PhoneAuthCredential phoneAuthCredential) {
}
#Override
public void onVerificationFailed(#NonNull FirebaseException e) {
}
#Override
public void onCodeSent(#NonNull String s, #NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
verifyCode = s;
(Toast.makeText(getApplicationContext(), "The OTP Code has been send, please verify the code", Toast.LENGTH_SHORT)).show();
Intent u = new Intent(userLogin.this, otp_verify.class);
startActivity(u);
}
};
// 2. execute actual call
PhoneAuthProvider.getInstance().verifyPhoneNumber(i, 60, TimeUnit.SECONDS, userLogin.this, otp);
}
The code snippet prepares callback and uses it on Firebase auth call. When the verification code is actually sent, the onCodeSent called and new activity launched.
I am new to Android and just published my app, the app is called random chat and its basically a chat application. So in order to record all of the user's names I used firebase real-time database. I have stored all of the User's data in a child in firebase called Usernames, in which the child of each User is stored with the user's UID (Obtained from Firebase Auth) as the main name and it has two children: name (which stores the name of the user) and phone (which stores the phone number of the user).
The problem is that in my app, every time a new user signs up, the app automatically switched from its current activity to a profile activity. I really don't understand why its happening, I thought it might be because the event listener in the other activity is still running but i remove the event listener at the onPause and onStop of every activity and I am using singleEventListeners.
My code is :
Profile Activity
public class ProfileActivity extends AppCompatActivity {
private FirebaseAuth mAuth;
private FirebaseUser mUser;
private FirebaseDatabase mDatabase;
private DatabaseReference mRef;
TextView UsernameP;
AdView mAdView;
private ValueEventListener eventListener;
private ValueEventListener eventListener1;
ArrayList<String> listOfUsernames = new ArrayList<>();
ArrayList<String> listOfGroups = new ArrayList<>();
ProgressDialog pDialog;
String usernameToBePassed;
String useruuid;
String randomGroupName;
int timer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
Log.d("TDS","3");
timer = 0;
MobileAds.initialize(this, "my-admob-id");
mAdView = (AdView) findViewById(R.id.adView2);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
showProgress();
UsernameP = (TextView)findViewById(R.id.UsernameP);
mAuth = FirebaseAuth.getInstance();
mUser = mAuth.getCurrentUser();
mDatabase = FirebaseDatabase.getInstance();
mRef = mDatabase.getReference();
checkAndSetUserNameAndGetUsernameList();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.log_out:
logOut();
return true;
case R.id.help:
startActivity(new Intent(ProfileActivity.this,HelpActivity.class));
default:
return super.onOptionsItemSelected(item);
}
}
public void logOut(){
mAuth.signOut();
FirebaseUser user = mAuth.getCurrentUser();
if (user == null){
Intent intent = new Intent(ProfileActivity.this,MainActivity.class);
startActivity(intent);
}
}
public void checkAndSetUserNameAndGetUsernameList() {
useruuid = mUser.getUid();
eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (timer==0) {
usernameToBePassed = "" + dataSnapshot.getValue(String.class);
UsernameP.setText(usernameToBePassed);
cancleProgress();
timer = 1;
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
mRef.child("Usernames").child(useruuid).child("name").addListenerForSingleValueEvent(eventListener);
/* mRef.child("Usernames").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Dummies.clear();
listOfUsernames.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
User user = snapshot.getValue(User.class);
String username = "" + user.name;
makeElementsUniqueUsingSet(Dummies,listOfUsernames,username);
if (mUser.getPhoneNumber().equals(user.phone)){
UsernameP.setText(user.name);
usernameToBePassed = user.name;
useruuid = snapshot.getKey();
}
}
cancleProgress();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
}); */
}
public void makeElementsUniqueUsingSet(Set<String> sEntries,ArrayList<String> Entries,String entry){
sEntries.add(entry);
Entries.add(entry);
if (sEntries.size() != Entries.size()){
Entries.clear();
List<String> checkers = new ArrayList<String>(sEntries);
for (int i=0; i<sEntries.size();i++){
Entries.add(checkers.get(i));
}
checkers.clear();
}
Entries.removeAll(Collections.singleton(null));
}
public void getRandomChildname(){
showProgress();
final Set<String> sEntries = new HashSet<>();
eventListener1 = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
String s = snapshot.child("name").getValue(String.class);
if (!snapshot.child("Users").hasChild(usernameToBePassed) && !s.equals(null)){
makeElementsUniqueUsingSet(sEntries,listOfGroups,s);
}
}
if (listOfGroups.size()>0) {
Random random = new Random();
int r = random.nextInt(listOfGroups.size());
randomGroupName = listOfGroups.get(r);
String randomGroupname = randomGroupName;
String uniqueUUID = UUID.randomUUID().toString();
mRef.child("GrouplistA").child(randomGroupname).child("Users").child(usernameToBePassed).child("name").setValue(usernameToBePassed);
mRef.child("GrouplistA").child(randomGroupname).child("Users").child(usernameToBePassed).child("status").setValue("normal");
mRef.child("GrouplistA").child(randomGroupname).child("status").setValue("hold");
mRef.child("GrouplistA").child(randomGroupname).child("ChatBox").child("CC-Randomizer-" + uniqueUUID).child("message").setValue("How's it going, people? Randomizer here letting you know there is a new user so all your names have been switched again.So Enjoy. Mizer out!");
mRef.child("GrouplistA").child(randomGroupname).child("ChatBox").child("CC-Randomizer-" + uniqueUUID).child("date").setValue(getCurrentDateAndTime());
cancleProgress();
Intent intent = new Intent(ProfileActivity.this, ChatActivity.class);
intent.putExtra("un", usernameToBePassed);
intent.putExtra("gr", randomGroupname);
intent.putExtra("gs", "A");
startActivity(intent);
finish();
} else {
Toast.makeText(getApplicationContext(),"Sorry but there are no public sessions for you to barge in on",Toast.LENGTH_SHORT).show();
cancleProgress();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
mRef.child("GrouplistA").addListenerForSingleValueEvent(eventListener1);
}
public void showProgress()
{
pDialog = new ProgressDialog(ProfileActivity.this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
pDialog.show();
}
public void cancleProgress()
{
if(pDialog!=null)
pDialog.dismiss();
}
public void CreateGroup(View v){
Intent intent = new Intent(ProfileActivity.this,CreateGroupActivity.class);
intent.putExtra("un",usernameToBePassed);
intent.putExtra("uk",useruuid);
startActivity(intent);
finish();
}
public void GroupList(View v){
Intent intent = new Intent(ProfileActivity.this,GroupListActvity.class);
intent.putExtra("un",usernameToBePassed);
startActivity(intent);
finish();
}
public void FriendsList(View v){
Intent intent = new Intent(ProfileActivity.this,FriendsListActivity.class);
intent.putExtra("un",usernameToBePassed);
intent.putExtra("uk",useruuid);
startActivity(intent);
finish();
}
public void JoinGroup(View v){
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("This will take you to a random public group. You ready?");
alert.setPositiveButton("Join", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
getRandomChildname();
}
});
alert.setNegativeButton("Nevermind",null);
alert.show();
}
public String getCurrentDateAndTime(){
return DateFormat.getDateTimeInstance().format(new Date());
}
#Override
protected void onPause() {
super.onPause();
mRef.removeEventListener(eventListener);
if (eventListener1!=null) {
mRef.removeEventListener(eventListener1);
}
}
#Override
protected void onStop() {
super.onStop();
mRef.removeEventListener(eventListener);
if (eventListener1!=null) {
mRef.removeEventListener(eventListener1);
}
}
}
Sorry about the bad indenting. The profile activity is the activity that the app keeps jumping back to by the way
SignUpActivity : Im using Phone Auth
EditText MobileNumber;
CountryCodePicker ccp;
public ProgressDialog pDialog;
private DatabaseReference mRef;
private FirebaseAuth mAuth;
private PhoneAuthProvider mPhoneAuth;
private PhoneAuthProvider.ForceResendingToken mResendToken;
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks;
String mVerificationId;
ValueEventListener eventListener;
private static final String TAG = "TDS";
ArrayList<String> MNumbers = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("TDS","1");
new SimpleEula(this).show();
MobileNumber = (EditText) findViewById(R.id.MobileNumber);
ccp = (CountryCodePicker) findViewById(R.id.ccp);
mRef = FirebaseDatabase.getInstance().getReference();
mAuth = FirebaseAuth.getInstance();
mPhoneAuth = PhoneAuthProvider.getInstance();
mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential credential) {
signInWithPhoneAuthCredential(credential);
}
#Override
public void onVerificationFailed(FirebaseException e) {
if (e instanceof FirebaseAuthInvalidCredentialsException) {
MobileNumber.setError("Invalid phone number.");
} else if (e instanceof FirebaseTooManyRequestsException) {
Toast.makeText(getApplicationContext(),"Quota exceeded.",Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCodeSent(String verificationId,
PhoneAuthProvider.ForceResendingToken token) {
mVerificationId = verificationId;
mResendToken = token;
}
};
}
public void Submit(View v){
if (!TextUtils.isEmpty(MobileNumber.getText().toString())) {
showProgress();
startPhoneVerification(ccp.getDefaultCountryCodeWithPlus() + MobileNumber.getText().toString());
} else {
MobileNumber.setError("Please enter your mobile number");
}
}
public void startPhoneVerification(String phoneNumber) {
mPhoneAuth.verifyPhoneNumber(
phoneNumber, // Phone number to verify
60, // Timeout duration
TimeUnit.SECONDS, // Unit of timeout
this, // Activity (for callback binding)
mCallbacks); // OnVerificationStateChangedCallbacks
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
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
FirebaseUser user = task.getResult().getUser();
checkUserSignIn();
// ...
} else {
// Sign in failed, display a message and update the UI
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
// The verification code entered was invalid
Toast.makeText(getApplicationContext(),"Verfication Code Invalid",Toast.LENGTH_SHORT).show();
}
}
}
});
}
private void verifyPhoneNumberWithCode(String verificationId, String code) {
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code);
signInWithPhoneAuthCredential(credential);
}
private void resendVerificationCode(String phoneNumber,
PhoneAuthProvider.ForceResendingToken token) {
mPhoneAuth.verifyPhoneNumber(
phoneNumber, // Phone number to verify
60, // Timeout duration
TimeUnit.SECONDS, // Unit of timeout
this, // Activity (for callback binding)
mCallbacks, // OnVerificationStateChangedCallbacks
token); // ForceResendingToken from callbacks
}
#Override
public void onStart() {
super.onStart();
checkUserSignIn();
}
public void checkUserSignIn() {
FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser != null) {
showProgress();
getandcheckAccount(currentUser);
}
}
public void showProgress()
{
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
pDialog.show();
}
public void cancleProgress()
{
if(pDialog!=null)
pDialog.dismiss();
}
public void getandcheckAccount(final FirebaseUser mUser){
eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
User user = snapshot.getValue(User.class);
MNumbers.add("" + user.phone);
}
String UserNumber = mUser.getPhoneNumber();
if (MNumbers.contains(UserNumber)){
cancleProgress();
startActivity(new Intent(MainActivity.this,ProfileActivity.class));
} else {
startActivity(new Intent(MainActivity.this,UsernameActivity.class));
cancleProgress();
}
cancleProgress();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
mRef.child("Usernames").addValueEventListener(eventListener);
}
#Override
protected void onPause() {
super.onPause();
if (eventListener!=null) {
mRef.removeEventListener(eventListener);
}
}
#Override
protected void onStop() {
super.onStop();
if (eventListener!=null) {
mRef.removeEventListener(eventListener);
}
}</i>
Im adding the username to the realtime database in a different activity
EditText Username;
TextView TitleTextU;
public ProgressDialog pDialog;
private FirebaseDatabase mDatabase;
private DatabaseReference mRef;
private FirebaseAuth mAuth;
private FirebaseUser mUser;
ValueEventListener eventListener;
ArrayList<String> Usernames = new ArrayList<>();
ArrayList<String> MNumbers = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_username);
showProgress();
Log.d("TDS","2");
mDatabase = FirebaseDatabase.getInstance();
mRef = mDatabase.getReference();
mAuth = FirebaseAuth.getInstance();
mUser = mAuth.getCurrentUser();
getListOfUsernames();
Username = (EditText)findViewById(R.id.Username);
TitleTextU = (TextView)findViewById(R.id.TitleTextU);
TitleTextU.setText("Enter a Username to Continue");
Username.addTextChangedListener(new TextWatcher(){
public void afterTextChanged(Editable s) {}
public void beforeTextChanged(CharSequence s, int start, int count, int after){}
public void onTextChanged(CharSequence s, int start, int before, int count){
//s is the current character in the eddittext after it is changed
if (Usernames.contains(Username.getText().toString())){
Username.setError("This username is taken");
}
}
});
}
public void Select(View v){
FirebaseAuth mAuth = FirebaseAuth.getInstance();
FirebaseUser mUser = mAuth.getCurrentUser();
String UID = mUser.getUid();
String MobileNumber = mUser.getPhoneNumber();
User user = new User(Username.getText().toString(),MobileNumber);
if (!TextUtils.isEmpty(Username.getText().toString())){
mRef.child("Usernames").child(UID).setValue(user);
startActivity(new Intent(UsernameActivity.this,ProfileActivity.class));
} else {
Username.setError("Please enter a username");
}
}
public void getListOfUsernames(){
eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
User user = snapshot.getValue(User.class);
Usernames.add("" + user.name);
MNumbers.add("" + user.phone);
}
String UserNumber = mUser.getPhoneNumber();
if (MNumbers.contains(UserNumber)){
cancleProgress();
startActivity(new Intent(UsernameActivity.this,ProfileActivity.class));
}
cancleProgress();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
mRef.child("Usernames").addValueEventListener(eventListener);
}
public void showProgress()
{
pDialog = new ProgressDialog(UsernameActivity.this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
pDialog.show();
}
public void cancleProgress()
{
if(pDialog!=null)
pDialog.dismiss();
}
#Override
protected void onPause() {
super.onPause();
if (eventListener!=null) {
mRef.removeEventListener(eventListener);
}
}
#Override
protected void onStop() {
super.onStop();
if (eventListener!=null) {
mRef.removeEventListener(eventListener);
}
}
Here is the problematic code:
public void getListOfUsernames(){
eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
User user = snapshot.getValue(User.class);
Usernames.add("" + user.name);
MNumbers.add("" + user.phone);
}
String UserNumber = mUser.getPhoneNumber();
if (MNumbers.contains(UserNumber)){
cancleProgress();
startActivity(new Intent(UsernameActivity.this,ProfileActivity.class));
}
cancleProgress();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
mRef.child("Usernames").addValueEventListener(eventListener);
}
Every user that signs in makes all the users go to profile screen.