I have using Firebase Phone Auth in my project. But the firebase only sending otp for testing phone numbers.
I have added SHA1 and SHA256 in firebase project and enable Android DeviceCheck API. But all time i didn't get otp from Firebase.
When I cheking with testing phone number the otp popup screen is showing up and i am entered otp which i was created verification code ie 123456, 111111, 222222 etc. But otherwise i dont getting otp from firebase.
This is my code
username = findViewById(R.id.username);
fullname = findViewById(R.id.fullname);
mTelephoneNumber = findViewById(R.id.telephonenumberregister);
continueregister = findViewById(R.id.continueregister);
back = findViewById(R.id.back);
txt_login = findViewById(R.id.btnSign);
countryCodePicker = findViewById(R.id.countrycodepicker);
pd = new ProgressDialog(RegisterActivity.this);
pd.setCancelable(false);
auth = FirebaseAuth.getInstance();
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(RegisterActivity.this, StartActivity.class));
}
});
txt_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
continueregister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pd.setMessage("Loading");
pd.show();
mFullTelephoneNumber = countryCodePicker.getSelectedCountryCodeWithPlus() + mTelephoneNumber.getText().toString();
FirebaseDatabase.getInstance().getReference().child("Users").orderByChild("telephoneno").equalTo(mFullTelephoneNumber)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()){
pd.dismiss();
Toast.makeText(RegisterActivity.this, "There is a user who has this phone number", Toast.LENGTH_SHORT).show();
}
else {
pd.dismiss();
phoneVerification();
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
});
}
private void phoneVerification(){
pd.setMessage("Sending");
pd.show();
AlertDialog dialog;
View verficationView = LayoutInflater.from(RegisterActivity.this).inflate(R.layout.verificationdialoglayout, null);
AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
builder.setView(verficationView);
builder.setCancelable(false);
dialog = builder.create();
final EditText input_verificationCode = verficationView.findViewById(R.id.mverificationcode);
Button submit = verficationView.findViewById(R.id.submit);
Button resend = verficationView.findViewById(R.id.resend);
TextView countDownView = verficationView.findViewById(R.id.countdown);
ImageButton closeVerification = verficationView.findViewById(R.id.closeverification);
Log.d("a", mFullTelephoneNumber);
CountDownTimer countDownTimer = countDownTimer(countDownView, dialog);
closeVerification.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
countDownTimer.onFinish();
}
});
callbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(#NonNull PhoneAuthCredential phoneAuthCredential) {
}
#Override
public void onVerificationFailed(#NonNull FirebaseException e) {
Log.d("error", e.getMessage());
}
#Override
public void onCodeSent(#NonNull String s, #NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
Log.d("verificationcode", s);
mVerificationId = s;
resendingToken = forceResendingToken;
pd.dismiss();
dialog.show();
countDownTimer.start();
}
};
PhoneAuthOptions options =
PhoneAuthOptions.newBuilder(firebaseAuth)
.setPhoneNumber(mFullTelephoneNumber)
.setCallbacks(callbacks)
.setTimeout(60L, TimeUnit.SECONDS)
.setActivity(RegisterActivity.this)
.build();
PhoneAuthProvider.verifyPhoneNumber(options);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pd.setMessage("Please Wait...");
pd.show();
String str_verificationCode = input_verificationCode.getText().toString();
if (!TextUtils.isEmpty(str_verificationCode) && str_verificationCode.length() == 6){
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(mVerificationId, input_verificationCode.getText().toString());
firebaseAuth.signInWithCredential(credential).addOnCompleteListener(RegisterActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
String userID = task.getResult().getUser().getUid();
String a = "0";
DatabaseReference pref = FirebaseDatabase.getInstance().getReference().child("wallet").child(userID);
HashMap<String, Object> point = new HashMap<>();
point.put("balance", a);
pref.setValue(point);
reference = FirebaseDatabase.getInstance().getReference().child("Users").child(userID);
HashMap<String, Object> map = new HashMap<>();
map.put("id", userID);
map.put("telephoneno", mFullTelephoneNumber);
map.put("username", username.getText().toString().toLowerCase());
map.put("fullname", fullname.getText().toString());
map.put("imageurl", "https://firebasestorage.googleapis.com/v0/b/instagramtest-fcbef.appspot.com/o/placeholder.png?alt=media&token=b09b809d-a5f8-499b-9563-5252262e9a49");
map.put("bio", "");
reference.setValue(map).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
Intent intent = new Intent(RegisterActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
pd.dismiss();
countDownTimer.onFinish();
}
else {
Toast.makeText(RegisterActivity.this, "error", Toast.LENGTH_SHORT).show();
}
}
});
}
else {
pd.dismiss();
dialog.dismiss();
Toast.makeText(RegisterActivity.this, "Wrong code is entered.", Toast.LENGTH_SHORT).show();
}
}
});
}
else {
Toast.makeText(RegisterActivity.this, "Please enter the code!", Toast.LENGTH_SHORT).show();
}
}
});
resend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
pd.setMessage("Resending");
pd.show();
countDownTimer.onFinish();
countDownTimer.start();
PhoneAuthOptions options =
PhoneAuthOptions.newBuilder(firebaseAuth)
.setPhoneNumber(mFullTelephoneNumber)
.setCallbacks(callbacks)
.setTimeout(60L, TimeUnit.SECONDS)
.setActivity(RegisterActivity.this)
.setForceResendingToken(resendingToken)
.build();
PhoneAuthProvider.verifyPhoneNumber(options);
}
});
}
private CountDownTimer countDownTimer(TextView countDownView, AlertDialog dialog){
return new CountDownTimer(61000, 1000){
#SuppressLint("SetTextI18n")
#Override
public void onTick(long l) {
countDownView.setVisibility(View.VISIBLE);
countDownView.setText("" + l / 1000);
}
#Override
public void onFinish() {
countDownView.setVisibility(View.GONE);
dialog.dismiss();
}
};
}
}
Please give me a solution.
If anyone is facing this problem, Try to Add SHA fingerprint to your firebase to receive SMS
Related
I'm new, I don't have any experience. I saw some code to disable the login button. I tried to add it to the code. But I did not succeed. The application stops when the login button is pressed when the fields are empty.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityLoginBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
auth = FirebaseAuth.getInstance();
dialog = new ProgressDialog(this);
dialog.setMessage("Logging in...");
if(auth.getCurrentUser() != null) {
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
}
binding.submitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email, pass;
email = binding.emailBox.getText().toString();
pass = binding.passwordBox.getText().toString();
dialog.show();
auth.signInWithEmailAndPassword(email, pass).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
dialog.dismiss();
if(task.isSuccessful()) {
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
} else {
Toast.makeText(LoginActivity.this, task.getException().getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
});
binding.createNewBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, SignupActivity.class));
}
});
}
}
Instead of just checking for the empty fields, you should check for email pattern and for password, you should check if length > 6 otherwise Firebase Auth will throw an exception. Use below code for your submitBtn listener:
binding.submitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = binding.emailBox.getText().toString();
String pass = binding.passwordBox.getText().toString();
if (email.isEmpty()) {
binding.emailBox.setError("Email is required");
binding.emailBox.requestFocus();
return;
}
if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
binding.emailBox.setError("Email is not valid");
binding.emailBox.requestFocus();
return;
}
if (pass.isEmpty()) {
binding.passwordBox.setError("Password is required");
binding.passwordBox.requestFocus();
return;
}
if (pass.length() < 6) {
binding.passwordBox.setError("Password is weak");
binding.passwordBox.requestFocus();
return;
}
dialog.show();
auth.signInWithEmailAndPassword(email, pass).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
dialog.dismiss();
if(task.isSuccessful()) {
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
} else {
Toast.makeText(LoginActivity.this, task.getException().getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
});
I'm making setup_profile activity. Users can change information.
When users do not change the image, it is good. But when the user change image errors come.
I add 'null checker' like
if (uri!=null) But I don know why it is.
Here are the errors.
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.toString()' on a null object reference
at com.razberrylovers.mbting.SetUpActivity.saveToFireStore(SetUpActivity.java:291)
at com.razberrylovers.mbting.SetUpActivity.access$700(SetUpActivity.java:40)
at com.razberrylovers.mbting.SetUpActivity$10.onComplete(SetUpActivity.java:217)
Here is my code.
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_set_up);
Toolbar setUpToolbar = findViewById(R.id.setup_toolbar);
setSupportActionBar(setUpToolbar);
getSupportActionBar().setTitle("Profile");
storageReference = FirebaseStorage.getInstance().getReference();
firestore = FirebaseFirestore.getInstance();
auth = FirebaseAuth.getInstance();
Uid = auth.getCurrentUser().getUid();
progressBar = findViewById(R.id.progressBar);
progressBar.setVisibility(View.INVISIBLE);
circleImageView = findViewById(R.id.circleImageView);
mProfileName = findViewById(R.id.profile_name);
mSaveBtn = findViewById(R.id.save_btn);
mProfileSchool = findViewById(R.id.profile_school);
mconcreteregion = findViewById(R.id.profile_concreteregion);
// setting dialog
textView_age=findViewById(R.id.age_dialog);
textView_age.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new FragmentDialogBox().show(getSupportFragmentManager(),"fragmentDialog");
}
});
textView_job=findViewById(R.id.job_dialog);
textView_job.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Fragment_job().show(getSupportFragmentManager(),"fragmentDialog");
}
});
textView_region = findViewById(R.id.region_dialog);
textView_region.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Fragment_region().show(getSupportFragmentManager(),"fragmentDialog");
}
});
textView_height = findViewById(R.id.height_dialog);
textView_height.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Fragment_height().show(getSupportFragmentManager(),"fragmentDialog");
}
});
textView_religion = findViewById(R.id.religion_dialog);
textView_religion.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Fragment_religion().show(getSupportFragmentManager(),"fragmentDialog");
}
});
textView_drink = findViewById(R.id.drink_dialog);
textView_drink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Fragment_drink().show(getSupportFragmentManager(),"fragmentDialog");
}
});
textView_smoke = findViewById(R.id.smoke_dialog);
textView_smoke.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Fragment_smoke().show(getSupportFragmentManager(),"fragmentDialog");
}
});
textView_mbti = findViewById(R.id.mbti_dialog);
textView_mbti.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Fragment_mbti().show(getSupportFragmentManager(),"fragmentDialog");
}
});
and load data from firestore + mSaveBtn click listener(including the case of not changing the picture)
firestore.collection("Users").document(Uid).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()){
if (task.getResult().exists()){
String name = task.getResult().getString("name");
String age = task.getResult().getString("age");
String job = task.getResult().getString("job");
String imageUrl = task.getResult().getString("image");
String school = task.getResult().getString("school");
String region = task.getResult().getString("region");
String concrete_region = task.getResult().getString("concrete_region");
String height = task.getResult().getString("height");
String religion = task.getResult().getString("religion");
String drink = task.getResult().getString("drink");
String smoke = task.getResult().getString("smoke");
String mbti = task.getResult().getString("mbti");
mProfileName.setText(name);
textView_age.setText(age);
textView_job.setText(job);
mProfileSchool.setText(school);
textView_region.setText(region);
mconcreteregion.setText(concrete_region);
textView_height.setText(height);
textView_religion.setText(religion);
mImageUri = Uri.parse(imageUrl);
textView_drink.setText(drink);
textView_smoke.setText(smoke);
textView_mbti.setText(mbti);
Glide.with(SetUpActivity.this).load(imageUrl).into(circleImageView);
}
}
}
});
//
mSaveBtn.setOnClickListener(v -> {
progressBar.setVisibility(View.VISIBLE);
String name = mProfileName.getText().toString();
String age = textView_age.getText().toString();
String job = textView_job.getText().toString();
String school = mProfileSchool.getText().toString();
String region = textView_region.getText().toString();
String concrete_region = mconcreteregion.getText().toString();
String height = textView_height.getText().toString();
String religion = textView_religion.getText().toString();
String drink = textView_drink.getText().toString();
String smoke = textView_smoke.getText().toString();
String mbti = textView_mbti.getText().toString();
StorageReference imageRef = storageReference.child("Profile_pics").child(Uid+".jpg");
//프로필 수정시 사진을 바꾸지 않았을 경우를 해결
if(isPhotoSelected)
{
if (!name.isEmpty() && mImageUri != null) {
imageRef.putFile(mImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
saveToFireStore(task, name, age, job, school, region,
concrete_region, height, religion, drink, smoke, mbti, imageRef);
} else {
progressBar.setVisibility(View.INVISIBLE);
Toast.makeText(SetUpActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
} else {
progressBar.setVisibility(View.INVISIBLE);
Toast.makeText(SetUpActivity.this, "등록을 하지 않은 것이 있습니다.", Toast.LENGTH_SHORT).show();
}
}
else{
saveToFireStore(null, name, age, job, school, region,
concrete_region, height, religion, drink, smoke, mbti, imageRef);
}
});
--> also code
Next code
There is a section that allows permission, and there is a saveToFireStore() method.-> when the task is null, the photo is not changed and when the task is not null photo will be changed.
circleImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
if(ContextCompat.checkSelfPermission(SetUpActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(SetUpActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
}
else{
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1,1)
.start(SetUpActivity.this);
}
}
}
});
}
private void saveToFireStore(Task<UploadTask.TaskSnapshot> task, String name,
String age, String job, String school, String region,
String concrete_region, String height, String religion,
String drink, String smoke, String mbti,
StorageReference imageRef) {
if(task != null){
imageRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
downloadUri = uri;
}
});
}
else{
downloadUri = mImageUri;
}
HashMap<String , Object> map = new HashMap<>();
map.put("name", name);
map.put("age", age);
map.put("job", job);
map.put("school", school);
map.put("region", region);
map.put("concrete_region", concrete_region);
map.put("height", height);
map.put("religion", religion);
map.put("drink", drink);
map.put("smoke", smoke);
map.put("mbti", mbti);
map.put("image",downloadUri.toString());
firestore.collection("Users").document(Uid).set(map).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
progressBar.setVisibility(View.INVISIBLE);
Toast.makeText(SetUpActivity.this, "프로필이 등록되었습니다.", Toast.LENGTH_SHORT).show();
startActivity(new Intent(SetUpActivity.this, MainActivity.class));
finish();
}
else{
progressBar.setVisibility(View.INVISIBLE);
Toast.makeText(SetUpActivity.this,task.getException().toString(),Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE){
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if(resultCode == RESULT_OK){
mImageUri = result.getUri();
circleImageView.setImageURI(mImageUri);
isPhotoSelected = true;
}
else if(resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE){
Toast.makeText(this,result.getError().getMessage(),Toast.LENGTH_SHORT).show();
}
}
}
The part of the error that logcat showed
imageRef.putFile(mImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
saveToFireStore(task, name, age, job, school, region,
concrete_region, height, religion, drink, smoke, mbti, imageRef);
} else {
progressBar.setVisibility(View.INVISIBLE);
Toast.makeText(SetUpActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
and
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
progressBar.setVisibility(View.INVISIBLE);
Toast.makeText(SetUpActivity.this, "프로필이 등록되었습니다.", Toast.LENGTH_SHORT).show();
startActivity(new Intent(SetUpActivity.this, MainActivity.class));
finish();
}
else{
progressBar.setVisibility(View.INVISIBLE);
Toast.makeText(SetUpActivity.this,task.getException().toString(),Toast.LENGTH_SHORT).show();
}
}
I keep on getting the error of sms code has been expiraed please resend it even though it just came in my phone. This for android studio firebase authentication by phone number by the way. Can we solve this error?
Below are the codes:
The Send OTP Code:
public void sendOTP(){
final String Mobile = getMobileNo();
//Looks if the mobile number is already signed
FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
if(currentUser!=null){
Toast.makeText(this,"User with mobile no"+Mobile+" already exists",Toast.LENGTH_LONG).show();
Intent in = new Intent(OTPActivity.this,LoginActivity.class);
in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(in);
}
//if not a current user then send otp.
else {
PhoneAuthOptions options = PhoneAuthOptions.newBuilder(mAuth)
.setPhoneNumber(Mobile)
.setTimeout(120L, TimeUnit.SECONDS)
.setActivity(this)
.setCallbacks(mCallBack)
.build();
PhoneAuthProvider.verifyPhoneNumber(options);
}
}
The mCallBacks Code:
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallBack = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onCodeSent(#NonNull String s, #NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
verificationId = s;
setVerificationId(verificationId);
setToken(forceResendingToken);
}
#Override
public void onVerificationCompleted(#NonNull PhoneAuthCredential phoneAuthCredential) {
final String code = phoneAuthCredential.getSmsCode();
if(code!=null){
OTP.setText(code);
verifyCode(getVerificationId(),code);
}
}
#Override
public void onVerificationFailed(#NonNull FirebaseException e) {
Toast.makeText(OTPActivity.this,e.getMessage(),Toast.LENGTH_LONG).show();
}
};
The Verify Code:
public void verifyCode(String verificationId,String code){
if(code!=null) {
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code);
FirebaseAuth.getInstance().signInWithCredential(credential)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
FirebaseUser user = task.getResult().getUser();
AlertDialog.Builder builder = new AlertDialog.Builder(OTPActivity.this);
builder.setMessage("Congratulations!!You are Registered. Do You Want To Login?");
builder.setCancelable(true);
builder.setPositiveButton(
"Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent in = new Intent(OTPActivity.this, LoginActivity.class);
in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(in);
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(OTPActivity.this, "Exiting the app.", Toast.LENGTH_SHORT).show();
System.exit(0);
}
});
}
else
{
if(task.getException() instanceof FirebaseAuthInvalidCredentialsException){
Toast.makeText(OTPActivity.this,task.getException().getMessage(),Toast.LENGTH_SHORT).show();
}
}
}
});
}
else
{
Toast.makeText(this,"Code Field is Empty.Please Enter OTP.",Toast.LENGTH_LONG).show();
}
}
Please Help. Been stuck on this for days.
The Exception I am getting is that:
The sms Code has expired(even though I have got the otp code like seconds ago.).Please resend the code.
In my app there's a signup option, there a user can input his data, after user put input they can get a token, then they can sign in with that token,every user get a unique token and sign in with this unique token.how can I do it with firebase?
Here is the firebase database:
https://i.pinimg.com/originals/40/47/18/404718948df116f257abe31fa8cc98e7.png
Here is the sample code:
public class MainActivity extends AppCompatActivity {
//for sign in
EditText edtUser,edtPwd;
//for sign up
EditText edtNewUser,edtnewPassword,edtnewPhnNum,edtnewEmail;
Button signIn,signUp;
FirebaseDatabase database;
DatabaseReference users;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edtUser = findViewById(R.id.signinUserEdit);
edtPwd = findViewById(R.id.signinUserPwd);
signIn = findViewById(R.id.signinBtn);
signUp = findViewById(R.id.signUpBtn);
database = FirebaseDatabase.getInstance();
users = database.getReference("Users");
signUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
signUpDilog();
}
});
signIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
signInMethod(edtUser.getText().toString(),edtPwd.getText().toString());
}
});
}
private void signInMethod(final String user, final String pwd) {
users.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.child(user).exists()){
if (!user.isEmpty()){
SignInUpModel login = dataSnapshot.child(user).getValue(SignInUpModel.class);
if (login.getPassword().equals(pwd)){
Toast.makeText(MainActivity.this,"Login ok!",Toast.LENGTH_LONG).show();
Intent home = new Intent(MainActivity.this,HomeActivity.class);
CommonModel.currentUser = login;
startActivity(home);
finish();
}
else
Toast.makeText(MainActivity.this,"Wrong Password",Toast.LENGTH_LONG).show();
}else{
Toast.makeText(MainActivity.this,"Please enter your user name",Toast.LENGTH_LONG).show();
}
}
else
Toast.makeText(MainActivity.this,"User is not exists",Toast.LENGTH_LONG).show();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void signUpDilog() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
alertDialog.setTitle("Sign Up");
alertDialog.setMessage("Please fill your information");
LayoutInflater inflater = this.getLayoutInflater();
View signUpLayout = inflater.inflate(R.layout.signuplayout,null);
edtNewUser = signUpLayout.findViewById(R.id.signUpEdit);
edtnewEmail = signUpLayout.findViewById(R.id.signoutemailEdit);
edtnewPhnNum = signUpLayout.findViewById(R.id.signupphnEdit);
edtnewPassword = signUpLayout.findViewById(R.id.signUpPwd);
alertDialog.setView(signUpLayout);
alertDialog.setIcon(R.drawable.ic_account_circle_black_24dp);
alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
final SignInUpModel user = new SignInUpModel(edtNewUser.getText().toString(),edtnewEmail.getText().toString(),
edtnewPhnNum.getText().toString(),edtnewPassword.getText().toString());
users.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.child(user.getUserName()).exists()){
Toast.makeText(MainActivity.this,"User already exists",Toast.LENGTH_LONG).show();
}else{
users.child(user.getUserName()).setValue(user);
Toast.makeText(MainActivity.this,"User registration success!",Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
dialogInterface.dismiss();
}
});
alertDialog.show();
}
}
I expect when the user put his/her details and complete signup then he/she gets a token and put this token and complete his signing and goes to the next activity. How can I do that using firebase? thank u
Try this for SignUp
TextView mailSignup = findViewById(R.id.mailSignup);
String Email = mailSignup.getText().toString();
TextView passwordSignup = findViewById(R.id.passwordSignup);
String Password = passwordSignup.getText().toString();
TextView nameSignup = findViewById(R.id.nameSignup);
String Name = nameSignup.getText().toString();
TextView ErrorText = findViewById(R.id.errortext);
TextView confirmPassSignup = findViewById(R.id.confirmpassSignup);
String Verification = confirmPassSignup.getText().toString();
if (!(Password.isEmpty()) && !(Email.isEmpty()) && !(Name.isEmpty()) && Password.equals(Verification) && Password.length() > 5) {
mAuth = FirebaseAuth.getInstance();
mAuth.createUserWithEmailAndPassword(Email, Password).addOnCompleteListener(SignUp.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
mDatabase = FirebaseDatabase.getInstance().getReference("users");
String UserUid = mAuth.getCurrentUser().getUid();
user User = new user(UserUid,Name,Email);
mDatabase.child(UserUid).setValue(User);
// Toast.makeText(SignUp.this, "Save Done", Toast.LENGTH_SHORT).show();
} else {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
progressDialog.dismiss();
}
}, 1000);
// If sign in fails, display a message to the user.
Toast.makeText(SignUp.this, "Authentication failed.", Toast.LENGTH_SHORT).show();
}
}
});
}
And this for Login
EditText mailLogin = findViewById(R.id.mailLogin);
String Email = mailLogin.getText().toString();
EditText passwordLogin = findViewById(R.id.passwordLogin);
String Password = passwordLogin.getText().toString();
if (!(Email.isEmpty()) && !(Password.isEmpty())){
mAuth.signInWithEmailAndPassword(Email,Password)
.addOnCompleteListener(MainActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
Intent goToHome = new Intent(LoginActivity.this, Home.class);
startActivity(goToHome);
}
else{
Toast.makeText(getApplicationContext(),"Wrong Credentials",Toast.LENGTH_LONG).show();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
}
}, 1000);
}
}
});
}
}
can't get to second activity after spots dialog "keep's on loading" on my main activity and can load for hours without error i use facebook acount kit i dont see the error out here is the main activity source code
main activity java :
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_CODE = 1000;
Button btnContinue;
RelativeLayout rootLayout;
FirebaseAuth auth;
FirebaseDatabase db;
DatabaseReference users;
#Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//bf4 set context view
CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
.setDefaultFontPath("fonts/Arkhip_font.ttf")
.setFontAttrId(R.attr.fontPath)
.build());
setContentView(R.layout.activity_main);
printKeyHash();
//Init Firebase
auth = FirebaseAuth.getInstance();
db = FirebaseDatabase.getInstance();
users = db.getReference(Common.user_driver_tbl);
//init view
btnContinue = (Button)findViewById(R.id.btnContinue);
rootLayout =(RelativeLayout)findViewById(R.id.rootLayout);
//Event
btnContinue.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
signInwithPhone();
}
});
//auto login to facebook act kit for second time
if (AccountKit.getCurrentAccessToken() != null)
{
//create dialog
final AlertDialog waitingDialog = new SpotsDialog(this);
waitingDialog.show();
waitingDialog.setMessage("Please waiting....");
waitingDialog.setCancelable(false);
AccountKit.getCurrentAccount(new AccountKitCallback<Account>() {
#Override
public void onSuccess(Account account) {
//copy from exiting user
users.child(account.getId())//fixed
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Common.currentUser = dataSnapshot.getValue(User.class);
Intent homeIntent = new Intent(MainActivity.this,DriverHome.class);
startActivity(homeIntent);
//Dismiss dialog
waitingDialog.dismiss();
finish();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onError(AccountKitError accountKitError) {
}
});
}
}
private void signInwithPhone() {
Intent intent = new Intent(MainActivity.this, AccountKitActivity.class);
AccountKitConfiguration.AccountKitConfigurationBuilder configurationBuilder =
new AccountKitConfiguration.AccountKitConfigurationBuilder(LoginType.PHONE,
AccountKitActivity.ResponseType.TOKEN);
intent.putExtra(AccountKitActivity.ACCOUNT_KIT_ACTIVITY_CONFIGURATION,configurationBuilder.build());
startActivityForResult(intent,REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE)
{
AccountKitLoginResult result = data.getParcelableExtra(AccountKitLoginResult.RESULT_KEY);
if (result.getError() !=null)
{
Toast.makeText(this, ""+result.getError().getErrorType().getMessage(), Toast.LENGTH_SHORT).show();
return;
}
else if (result.wasCancelled())
{
Toast.makeText(this, "Cancel login", Toast.LENGTH_SHORT).show();
return;
}
else{
if (result.getAccessToken() !=null)
{
//Show dialog
final AlertDialog waitingDialog = new SpotsDialog(this);
waitingDialog.show();
waitingDialog.setMessage("Please waiting....");
waitingDialog.setCancelable(false);
//get current phone
AccountKit.getCurrentAccount(new AccountKitCallback<Account>() {
#Override
public void onSuccess(final Account account) {
final String userId = account.getId();
//check if exist on firebase
users.orderByKey().equalTo(account.getId())
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (!dataSnapshot.child(account.getId()).exists())//if not exits
{
//will we create new user login
final User user = new User();
user.setPhone(account.getPhoneNumber().toString());
user.setName(account.getPhoneNumber().toString());
user.setAvatarUrl("");
user.setRates("0.0");
//Register to Firebase
users.child(account.getId())
.setValue(user)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
//Login
users.child(account.getId())
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Common.currentUser = dataSnapshot.getValue(User.class);
Intent homeIntent = new Intent(MainActivity.this,DriverHome.class);
startActivity(homeIntent);
//Dismiss dialog
waitingDialog.dismiss();
finish();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, ""+e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
else //if user existing ,login
{
users.child(account.getId())
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Common.currentUser = dataSnapshot.getValue(User.class);
Intent homeIntent = new Intent(MainActivity.this,DriverHome.class);
startActivity(homeIntent);
//Dismiss dialog
waitingDialog.dismiss();
finish();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onError(AccountKitError accountKitError) {
Toast.makeText(MainActivity.this, ""+accountKitError.getErrorType().getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
}
}
private void printKeyHash() {
try{
PackageInfo info = getPackageManager().getPackageInfo("com.example.rd.androidapp",
PackageManager.GET_SIGNATURES);
for (Signature signature:info.signatures)
{
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.d("KEYHASH", Base64.encodeToString(md.digest(),Base64.DEFAULT));
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
}
if more is needed !!! or is there something lacking also i am still new in android programing so ...
Try to uses dismiss the dialog in onCancel and onError method and print error for discretion.