I am making a Whatsapp like app(By Following tutorial). It crashes when i click on send code button. i confirmed it by try/catch my phone number verification is not working or there's a problem with it
java.lang.IllegalArgumentException: Cannot create PhoneAuthCredential
without either verificationProof, sessionInfo, ortemprary proof.
What i confirmed/tried:
both activities are declared in manifest,
assigned id to layout,
initialized relative argument,
Nothing is there in libs folder of the project,
swapped initialization with layout ,
Tried this code to get value:
String.valueOf(phoneNumberEdt)
I did all what i could as per my level
public class MainActivity extends AppCompatActivity {
private EditText phoneNumberEdt, verificationcodeEdt;
Button sendCodeButton;
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallBacks;
String mVerificationId = "0";
//private PhoneAuthProvider.ForceResendingToken mResendToken;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
phoneNumberEdt = (EditText) findViewById(R.id.phonenumber_edt);
verificationcodeEdt = (EditText)
findViewById(R.id.verificationcode_edt);
sendCodeButton = (Button) findViewById(R.id.sendcode_btn);
FirebaseApp.initializeApp(this);
userIsLoggedIn();
phoneNumberEdt.setText("03026989523");
sendCodeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//try{
if(mVerificationId != null)
verifyPhoneNumberWithCode();
else
startPhoneNumberVerification();
/*}catch (Exception e){
Toast toast = Toast.makeText(getApplicationContext(),
"Verification Code is wrong, try again", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER,0,0);
toast.show();
}*/
mCallBacks = new
PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential
phoneAuthCredential) {
signInWithPhoneAuthCredential(phoneAuthCredential);
}
#Override
public void onVerificationFailed(FirebaseException e) {}
#Override
public void onCodeSent(String VerificationId,
PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(VerificationId, forceResendingToken);
mVerificationId = VerificationId;
sendCodeButton.setText("Verify Code");
}
};
}
});
}
Error points here
private void startPhoneNumberVerification() {
PhoneAuthProvider.getInstance().verifyPhoneNumber(
phoneNumberEdt.getText().toString(),//String.valueOf(phoneNumberEdt)
60,
TimeUnit.SECONDS,
this,
mCallBacks);
}
Rest of the functions
private void verifyPhoneNumberWithCode(){
PhoneAuthCredential credential =
PhoneAuthProvider.getCredential(mVerificationId,
verificationcodeEdt.getText().toString());
signInWithPhoneAuthCredential(credential);
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential
phoneAuthCredential) {
FirebaseAuth.getInstance().signInWithCredential(phoneAuthCredential).
addOnComp leteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful())
userIsLoggedIn();
}
});
}
private void userIsLoggedIn() {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if(user != null) {
startActivity(new
Intent(getApplicationContext(),MainPageActivity.class));
finish();
return;
}
}
Related
Just trying to make a phone authentication as per a tutorial i'm watching which I have written down the code as below, but i keep getting the error expression expected for 'User' - I am completely new to this so I imagine it's something simple I need help nonetheless! Thank you in advance!
mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(#NonNull PhoneAuthCredential phoneAuthCredential) {
signInWithPhoneAuthCredential(phoneAuthCredential);
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential phoneAuthCredential) {
FirebaseAuth.getInstance().signInWithCredential(phoneAuthCredential).addOnCompleteListener(this, new OnCompleteListener<Credential.UserCredential>() {
#Override
public void onComplete(#NonNull Task<Credential.UserCredential> task) {
if(task.isSuccessful())
userIsLoggedIn();
}
private void userIsLoggedIn() {
User = FirebaseAuth.getInstance().getCurrentUser();
if(User != null){
startActivity(new Intent(getApplicationContext(), MainPageActivity.class));
finish();
return;
You have a class named "User" and you didn't define its variable here which showing java expression error . Actually you are looking for User of Firebase , FirebaseAuth has class FirebaseUser . So it should be below code to check current user .
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if(user != null){.....
Update (cause of new error) - You are implementing PhoneAuthCredential , but passing Username-password based Credential.UserCredential and implemeting wrong method.
Your signInWithPhoneAuthCredential void would be -
private void signInWithPhoneAuthCredential(PhoneAuthCredential phoneAuthCredential) {
FirebaseAuth.getInstance().signInWithCredential(phoneAuthCredential).addOnCompleteListener(this , new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
userIsLoggedIn();
} else {
//
}
}
});
}
And your attached code would be -
mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(#NonNull PhoneAuthCredential phoneAuthCredential) {
signInWithPhoneAuthCredential(phoneAuthCredential);
}
#Override
public void onVerificationFailed(#NonNull FirebaseException e) {
//TODO
}
#Override
public void onCodeSent(#NonNull String s, #NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
//TODO
}
};
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential phoneAuthCredential) {
FirebaseAuth.getInstance().signInWithCredential(phoneAuthCredential).addOnCompleteListener(this , new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
userIsLoggedIn();
} else {
//
}
}
});
}
private void userIsLoggedIn() {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
startActivity(new Intent(getApplicationContext(), MainPageActivity.class));
finish();
// return;
}
}
Please check the documentation.
When I enter a phone number into my EditText field and press login, the java code has to validate if the editText field is empty or not. So after entering my phone no., the if(!phonenumber.isempty()) is always false and the else statement is executed, that is "Please enter number" Toast
Here is my compelete code:
public class User_login extends AppCompatActivity {
private EditText editTextphone;
private Button otp_login;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_login);
otp_login = (Button) findViewById(R.id.otp_login);
editTextphone = (EditText) findViewById(R.id.editTextphone);
String phoneNumber = editTextphone.getText().toString().trim();
mAuth = FirebaseAuth.getInstance();
ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);
otp_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(!phoneNumber.isEmpty()){
if(phoneNumber.length() == 10){
progressBar.setVisibility(View.VISIBLE);
otp_login.setVisibility(View.INVISIBLE);
PhoneAuthOptions options = PhoneAuthOptions.newBuilder(mAuth)
.setPhoneNumber("+91" + phoneNumber)
.setTimeout(60L, TimeUnit.SECONDS)
.setActivity(User_login.this)
.build();
PhoneAuthProvider.verifyPhoneNumber(options);
new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(#NonNull #org.jetbrains.annotations.NotNull PhoneAuthCredential phoneAuthCredential) {
progressBar.setVisibility(View.GONE);
otp_login.setVisibility(View.VISIBLE);
}
#Override
public void onVerificationFailed(#NonNull #org.jetbrains.annotations.NotNull FirebaseException e) {
progressBar.setVisibility(View.GONE);
otp_login.setVisibility(View.VISIBLE);
Toast.makeText(User_login.this,"Some error occured" + e.getMessage(), Toast.LENGTH_LONG).show();
}
#Override
public void onCodeSent(#NonNull #org.jetbrains.annotations.NotNull String s, #NonNull #org.jetbrains.annotations.NotNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
Intent intent = new Intent(getApplicationContext(),opt_verify.class);
intent.putExtra("phone", editTextphone.getText().toString());
intent.putExtra("mVerificationId", s);
startActivity(intent);
}
};
}else{
Toast.makeText(User_login.this,"Please enter complete number",Toast.LENGTH_LONG).show();
}
}else{
Toast.makeText(User_login.this,"Please enter mobile number",Toast.LENGTH_LONG).show();
}
}
});
}
#Override
protected void onStart() {
super.onStart();
if(mAuth.getCurrentUser() != null){
startActivity(new Intent(this, home_user.class));
}
}
}
You should get the EditText input in the onClick Listner, only then you could get the latest inputted value from the edittext.
ie,
String phoneNumber = editTextphone.getText().toString().trim();
should be called inside :
otp_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String phoneNumber = editTextphone.getText().toString().trim(); //like this
if(!phoneNumber.isEmpty()){
There is a problem in your logic. The reason is that you are getting text before clicking the button meanwhile when the onCreate method runs it gets the value form the EditText. But you need get the value when you click the button each time.
Try this code:
otp_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String phoneNumber = editTextphone.getText().toString().trim();
if (!phoneNumber.isEmpty()) {
if (phoneNumber.length() == 10) {
//you logic or code here
}
}
}
}
I'm creating an app that display notes list in a recyclerView. I connected the app with firebase authentication and realtime database.
The Realtime Database JSON tree looks like this:
The problem is that I want "Notes" to be part of "Users" which is not the case, because when I login to my app, I found the same Notes in every user account. I want the notes to be displayed for a specific user when they create them.
Here is my code:
SignupActivity.java
public class SignupActivity extends AppCompatActivity {
private static final String TAG = "";
private static final int RC_SIGN_IN = 9001;
EditText mName, mEmail,mPassword;
Button mSignupBtn;
FirebaseAuth mAuth;
ProgressBar progressBar;
View mViewHelper;
GoogleSignInButton button;
GoogleSignInClient mGoogleSignInClient;
FirebaseAuth.AuthStateListener mAuthListner;
FirebaseFirestore fStore;
String userID;
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListner);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
TextView textView = findViewById(R.id.textView);
textView.setText(Html.fromHtml(getString(R.string.agree_terms)));
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
mEmail = findViewById(R.id.et_email_address);
mPassword = findViewById(R.id.et_password);
mName = findViewById(R.id.et_name);
mSignupBtn = findViewById(R.id.create_btn);
progressBar = findViewById(R.id.loading_spinner);
mViewHelper = findViewById(R.id.view_helper);
button = findViewById(R.id.login_google_btn);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signIn();
}
});
mAuth = FirebaseAuth.getInstance();
fStore = FirebaseFirestore.getInstance();
mSignupBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String email = mEmail.getText().toString().trim();
String password = mPassword.getText().toString().trim();
final String name = mName.getText().toString();
if(TextUtils.isEmpty(email)) {
mEmail.setError("Email is required.");
return;
}
if(TextUtils.isEmpty(name)) {
mName.setError("Name is required.");
return;
}
if(TextUtils.isEmpty(password)) {
mPassword.setError("Password is required.");
return;
}
if(password.length() < 6) {
mPassword.setError("Password Must be >= 6 Characters");
return;
}
progressBar.setVisibility(View.VISIBLE);
mViewHelper.setVisibility(View.VISIBLE);
mSignupBtn.setVisibility(View.INVISIBLE);
// register the user in firebase
mAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()) {
Toast.makeText(SignupActivity.this, "User Created", Toast.LENGTH_SHORT).show();
userID = mAuth.getCurrentUser().getUid();
DocumentReference documentReference = fStore.collection("users").document(userID);
DatabaseReference current_user_db = FirebaseDatabase.getInstance().getReference().child("Users").child(userID);
Map<String, Object> user = new HashMap<>();
user.put("name", name);
user.put("email", email);
user.put("image", "default");
user.put("thumb_image", "default");
current_user_db.setValue(user);
documentReference.set(user).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "onSuccess: user Profile is created for "+ userID);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d(TAG, "onFailure: "+ e.toString());
}
});
Intent intent = new Intent(SignupActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
else{
Toast.makeText(SignupActivity.this, "Error !" + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
progressBar.setVisibility(View.GONE);
mViewHelper.setVisibility(View.INVISIBLE);
mSignupBtn.setVisibility(View.VISIBLE);
}
});
}
});
mAuthListner = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser() != null) {
startActivity(new Intent(SignupActivity.this, MainActivity.class));
}
}
};
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken("886475354465-j5suema9gt5mhi2fhli0un9vsn1olvaa.apps.googleusercontent.com")
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
}
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = task.getResult(ApiException.class);
firebaseAuthWithGoogle(account);
} catch (ApiException e) {
// Google Sign In failed, update UI appropriately
Log.w(TAG, "Google sign in failed", e);
// ...
}
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount account) {
AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success");
//updateUI(user);
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
Toast.makeText(SignupActivity.this, "Aut Fail", Toast.LENGTH_SHORT).show();
//updateUI(null);
}
// ...
}
});
}
}
NotesAdapter.java
public class NotesAdapter extends RecyclerView.Adapter<NotesAdapter.MyHolder>
{
List<Listdata> noteslist;
private Context context;
public NotesAdapter(List<Listdata> noteslist,Context context)
{
this.context=context;
this.noteslist=noteslist;
}
#NonNull
#Override
public MyHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view= LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item,viewGroup,false);
MyHolder myHolder=new MyHolder(view);
return myHolder;
}
#Override
public void onBindViewHolder(#NonNull MyHolder myHolder, int position) {
Listdata data=noteslist.get(position);
myHolder.title.setText(data.getTitle());
myHolder.desc.setText(data.getDesc());
}
#Override
public int getItemCount() {
return noteslist.size();
}
class MyHolder extends RecyclerView.ViewHolder {
TextView title,desc;
public MyHolder(#NonNull View itemView) {
super(itemView);
title=itemView.findViewById(R.id.title);
desc=itemView.findViewById(R.id.desc);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Listdata listdata=noteslist.get(getAdapterPosition());
Intent i=new Intent(context, StreamActivity.class);
i.putExtra("id",listdata.id);
i.putExtra("title",listdata.title);
i.putExtra("desc",listdata.desc);
context.startActivity(i);
}
});
}
}
}
AddNotesActivity.java
public class AddNotesActivity extends AppCompatActivity {
EditText title,desc;
String titlesend,descsend;
private DatabaseReference mDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_notes);
title=findViewById(R.id.title);
desc=findViewById(R.id.desc);
mDatabase = FirebaseDatabase.getInstance().getReference();
}
public void AddNotes(View view) {
titlesend=title.getText().toString();
descsend=desc.getText().toString();
if(TextUtils.isEmpty(titlesend) || TextUtils.isEmpty(descsend)){
return;
}
AddNotes(titlesend,descsend);
}
private void AddNotes(String titlesend, String descsend)
{
String id=mDatabase.push().getKey();
Listdata listdata = new Listdata(id,titlesend, descsend);
mDatabase.child("Notes").child(id).setValue(listdata).
addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(AddNotesActivity.this, "Notes Added", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(),NotesActivity.class));
}
});
}
}
NotesActivity.java
public class NotesActivity extends AppCompatActivity {
// Firebase instance variables
private FirebaseAuth mFirebaseAuth;
private FirebaseUser mFirebaseUser;
//HomeScreen variables
RecyclerView recyclerView;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
List<Listdata> list =new ArrayList<>();
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notes);
recyclerView=findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager=new LinearLayoutManager(NotesActivity.this);
recyclerView.setLayoutManager(layoutManager);
// Initialize Firebase Auth
mFirebaseAuth = FirebaseAuth.getInstance();
mFirebaseUser = mFirebaseAuth.getCurrentUser();
// Notes Screen
final NotesAdapter notesAdapter=new NotesAdapter(list,this);
recyclerView.setAdapter(notesAdapter);
FloatingActionButton fab = findViewById(R.id.fab);
firebaseDatabase=FirebaseDatabase.getInstance();
databaseReference=firebaseDatabase.getReference("Notes");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot dataSnapshot1: dataSnapshot.getChildren())
{
Listdata listdata=dataSnapshot1.getValue(Listdata.class);
list.add(listdata);
}
notesAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getApplicationContext(), AddNotesActivity.class));
}
});
// end NotesScreen
}
#Override
public void onStart() {
super.onStart();
FirebaseUser currentUser = mFirebaseAuth.getCurrentUser();
if(currentUser == null){
sendToStart();
}
}
private void sendToStart() {
Intent startIntent = new Intent(NotesActivity.this, LoginActivity.class);
startActivity(startIntent);
finish();
}
Please I need help on how should I modify my code to display the notes for a specific user when they create them. documentation links will be much appreciated.
you simply need to change this line of code from AddNotesActivity.java
mDatabase.child("Notes").child(id)
to
mDatabase.child("Users").child(userID).child("Notes").child(id)
and don't forget to retrieve the data in NotesActivity.java
databaseReference = FirebaseDatabase.getInstance().getReference().child("Users").child(userID).child("Notes");
I'm trying to change the user authentication email.
CustomDialogBox
public class ConfirmPasswordDialogBox extends Dialog implements android.view.View.OnClickListener {
private ImageButton cancel, confirm;
private EditText confirm_password;
public ConfirmPasswordDialogBox(#NonNull Context context) {
super(context);
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dailog_box_foremail);
confirm_password = findViewById(R.id.password);
cancel = findViewById(R.id.cancel_btn);
confirm = findViewById(R.id.confirm_btn);
cancel.setOnClickListener(this);
confirm.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch(view.getId()){
case R.id.cancel_btn:
dismiss();
break;
case R.id.confirm_btn:
String mpassword = confirm_password.getText().toString();
if(!mpassword.equals("")){
new EditProfileActivity().updatingemail(mpassword);
dismiss();
}else{
Toast.makeText(getContext(), "Password can't be empty.", Toast.LENGTH_SHORT).show();
}
break;
}
}
}
Activity where null pointer exception is thrown
public class EditProfileActivity extends AppCompatActivity {
private EditText descript, firstName, lastName, email;
private Button updatebtn;
private ImageButton back;
private Context mcontext;
private FirebaseAuth auth;
private FirebaseAuth.AuthStateListener authStateListener;
private FirebaseUser user;
private FirebaseDatabase database;
private DatabaseReference myRef;
private FirebaseMethods firebaseMethods;
private String userID;
private ProgressDialog pb;
private UserInformation userInformationx;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_profile);
mcontext = EditProfileActivity.this;
descript = findViewById(R.id.descript);
firstName = findViewById(R.id.firstName);
email = findViewById(R.id.email);
lastName = findViewById(R.id.lastName);
auth = FirebaseAuth.getInstance();
user = auth.getCurrentUser();
firebaseMethods = new FirebaseMethods(mcontext);
pb = new ProgressDialog(this);
pb.setMessage("Updaing Profile ...");
pb.setCancelable(true);
pb.setCanceledOnTouchOutside(false);
init();
setupFirebaseAuth();
}
public void updatingemail(String password){
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
// Get auth credentials from the user for re-authentication. The example below shows
// email and password credentials but there are multiple possible providers,
// such as GoogleAuthProvider or FacebookAuthProvider.
AuthCredential credential = EmailAuthProvider
.getCredential(user.getEmail(), password);
// Prompt the user to re-provide their sign-in credentials
user.reauthenticate(credential)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Log.d(TAG, "User re-authenticated.");
if(task.isSuccessful()){
FirebaseAuth.getInstance().fetchSignInMethodsForEmail(email.getText().toString()).addOnCompleteListener(new OnCompleteListener<SignInMethodQueryResult>() {
#Override
public void onComplete(#NonNull Task<SignInMethodQueryResult> task) {
if(task.isSuccessful()){
if(task.getResult().getSignInMethods().size() == 1){
Toast.makeText(mcontext, "That email is already in use.", Toast.LENGTH_SHORT).show();
}else{
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
user.updateEmail(email.getText().toString())
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "User email address updated.");
Toast.makeText(mcontext, "Email address updated.", Toast.LENGTH_SHORT).show();
myRef.child(mcontext.getString(R.string.dbname_users))
.child(userID)
.child(mcontext.getString(R.string.email))
.setValue(email.getText().toString());
}
}
});
}
}
}
});
}
}
});
}
The EditText widget is already intialized, still email.getText.toString() is throwing null. I'm just passing the string value to a method, which is called when a button is clicked in Dialog box.
I've tried and debug all possible ways I know.
I'm just trying to update the user authentication email in firebase.
The EditText widget is already intialized, still email.getText.toString() is throwing null.
Actually the EditText email is only intialized in the onCreate of the activity, this means that it's only initialized when you open the activity using startActivity(intent).
Edit - Since you're calling the ConfirmPasswordDialogBox from the EditProfileActivity, something along the following lines should work.
public class ConfirmPasswordDialogBox extends Dialog {
private ImageButton cancel, confirm;
public EditText confirm_password;
public ConfirmPasswordDialogBox(#NonNull Context context) {
super(context);
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dailog_box_foremail);
confirm_password = findViewById(R.id.password);
cancel = findViewById(R.id.cancel_btn);
confirm = findViewById(R.id.confirm_btn);
//cancel.setOnClickListener(this);
//confirm.setOnClickListener(this);
}
public void setOnClickListeners(View.OnClickListener listener) {
cancel.setOnClickListener(listener);
confirm.setOnClickListener(listener);
}
/*
#Override
public void onClick(View view) {
switch(view.getId()){
case R.id.cancel_btn:
dismiss();
break;
case R.id.confirm_btn:
String mpassword = confirm_password.getText().toString();
if(!mpassword.equals("")){
new EditProfileActivity().updatingemail(mpassword);
dismiss();
}else{
Toast.makeText(getContext(), "Password can't be empty.", Toast.LENGTH_SHORT).show();
}
break;
}
}
*/
}
public class EditProfileActivity extends AppCompatActivity implements android.view.View.OnClickListener {
//Other code
//At some point in some method you'll create the dialog
//Say you create the dialog object here. Now set this activity as the onClickListener
dialog.setOnClickListeners(this);
#Override
public void onClick(View view) {
switch(view.getId()){
case R.id.cancel_btn:
dismiss();
break;
case R.id.confirm_btn:
String mpassword = dialog.confirm_password.getText().toString();
if(!mpassword.equals("")){
//Now you can directly call the method
updatingemail(mpassword);
dismiss();
}else{
Toast.makeText(getContext(), "Password can't be empty.", Toast.LENGTH_SHORT).show();
}
break;
}
}
public void updatingemail(String password){
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
// Get auth credentials from the user for re-authentication. The example below shows
// email and password credentials but there are multiple possible providers,
// such as GoogleAuthProvider or FacebookAuthProvider.
AuthCredential credential = EmailAuthProvider
.getCredential(user.getEmail(), password);
// Prompt the user to re-provide their sign-in credentials
user.reauthenticate(credential)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Log.d(TAG, "User re-authenticated.");
if(task.isSuccessful()){
FirebaseAuth.getInstance().fetchSignInMethodsForEmail(email.getText().toString()).addOnCompleteListener(new OnCompleteListener<SignInMethodQueryResult>() {
#Override
public void onComplete(#NonNull Task<SignInMethodQueryResult> task) {
if(task.isSuccessful()){
if(task.getResult().getSignInMethods().size() == 1){
Toast.makeText(mcontext, "That email is already in use.", Toast.LENGTH_SHORT).show();
}else{
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
user.updateEmail(email.getText().toString())
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "User email address updated.");
Toast.makeText(mcontext, "Email address updated.", Toast.LENGTH_SHORT).show();
myRef.child(mcontext.getString(R.string.dbname_users))
.child(userID)
.child(mcontext.getString(R.string.email))
.setValue(email.getText().toString());
}
}
});
}
}
}
});
}
}
});
}
I wrote the code for firebase phone auth, and no error occured. But when i execute the app and entered the number ,i am getting as verification failed .pls help me out
I even connected to firebase proj and enables phone and also wrote SHA certificate
my code for main activity-
public class MainActivity extends AppCompatActivity {
EditText phone,vcode;
TextView msg;
Button getcode,verify;
private FirebaseAuth mAuth;
private String mVerificationId;
private PhoneAuthProvider.ForceResendingToken mResendToken;
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
phone = findViewById(R.id.phone);
vcode = findViewById(R.id.code);
getcode = findViewById(R.id.getcode);
verify = findViewById(R.id.verify);
msg = findViewById(R.id.msgtxt);
mAuth = FirebaseAuth.getInstance();
mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential credential) {
Toast.makeText(MainActivity.this, "Verified", Toast.LENGTH_LONG).show();
vcode.setVisibility(View.GONE);
verify.setVisibility(View.GONE);
msg.setVisibility(View.VISIBLE);
signInWithPhoneAuthCredential(credential);
}
#Override
public void onVerificationFailed(FirebaseException e) {
Toast.makeText(MainActivity.this, "Login Failed", Toast.LENGTH_LONG).show();
if (e instanceof FirebaseAuthInvalidCredentialsException) {
phone.setError("Invalid phone number");
} else if (e instanceof FirebaseTooManyRequestsException) {
}
}
#Override
public void onCodeSent(String verificationId,
PhoneAuthProvider.ForceResendingToken token) {
mVerificationId = verificationId;
mResendToken = token;
}
};
}
public void GetCode(View view) {
PhoneAuthProvider.getInstance().verifyPhoneNumber(
phone.getText().toString(),
60,
TimeUnit.SECONDS,
this,
mCallbacks);
phone.setVisibility(View.GONE);
getcode.setVisibility(View.GONE);
vcode.setVisibility(View.VISIBLE);
verify.setVisibility(View.VISIBLE);
}
public void verify(View view) {
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(mVerificationId, vcode.getText().toString());
signInWithPhoneAuthCredential(credential);
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>
() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
FirebaseUser user=task.getResult().getUser();
startActivity(new Intent(MainActivity.this,MainActivity.class));
vcode.setVisibility(View.GONE);
verify.setVisibility(View.GONE);
msg.setVisibility(View.VISIBLE);
finish();
} else {
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
Toast.makeText(MainActivity.this, "Invalid code", Toast.LENGTH_LONG).show();
}
}
}
});
}
}
For main2 activity-
public class Main2Activity extends AppCompatActivity {
Button start;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
start = (Button) findViewById(R.id.start);
start.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(Main2Activity.this, MainActivity.class);
startActivity(i);
}
});
}
}