Null string error on Firebase phone authentication in android studio - java

I'm trying to implement two step verification with Firebase Auth
When user proceed to PelephoneActivity, he has a unique uuid , he get it when subscribed by email.
In the PelephoneActivity I'm trying to get also the user phone number.
I'm not really need another auth, but i don't know how to stop auth after getting sms code.
Anyway, my code is:
public class PelephoneActivity extends AppCompatActivity {
private static final String TAG = "PelephoneActivity";
private FirebaseAuth mAuth;
private DatabaseReference UsersRef;
String currentUserID;
private Spinner spinner;
private EditText editText;
private String verificationId,phoneNumber;
private ProgressBar progressBar;
private EditText editTextC;
private Button signIn;
private TextView plsWait;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pelephone);
Log.d(TAG, "onCreate: started.");
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
UsersRef = FirebaseDatabase.getInstance().getReference().child("users").child(currentUserID);
spinner = findViewById(R.id.spinnerCountries);
spinner.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, CountryData.countryNames));
editText = findViewById(R.id.editTextPhone);
//////////////////////////////////////////////
progressBar = findViewById(R.id.progressbar);
editTextC = findViewById(R.id.editTextCode);
signIn=findViewById(R.id.buttonSignIn);
editTextC.setVisibility(View.INVISIBLE);
signIn.setVisibility(View.INVISIBLE);
plsWait.setVisibility(View.INVISIBLE);
/////////////////////////////////////////////
findViewById(R.id.buttonContinue).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String code = CountryData.countryAreaCodes[spinner.getSelectedItemPosition()];
String number = editText.getText().toString().trim();
if (number.isEmpty() || number.length() < 9) {
editText.setError("Valid number is required");
editText.requestFocus();
return;
}
phoneNumber = "+" + code + number;
signIn.setVisibility(View.VISIBLE);
plsWait.setVisibility(View.VISIBLE);
}
});
findViewById(R.id.buttonSignIn).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String code = editTextC.getText().toString().trim();
if (code.isEmpty() || code.length() < 6)
{
editTextC.setError("Enter code...");
editTextC.requestFocus();
return;
}
verifyCode(code);
}
});
}
private void sendVerificationCode(String number) {
progressBar.setVisibility(View.VISIBLE);
PhoneAuthProvider.getInstance().verifyPhoneNumber(
number, //Phone number to verify
60, //timeout duration
TimeUnit.SECONDS, //unit of timeout
TaskExecutors.MAIN_THREAD, //Activity for callback binding
mCallBack //OnVerificationStateChangedCallbacks
);
}
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()) {
progressBar.setVisibility(View.GONE);
} else {
}
}
});
}
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) {
editTextC.setText(code);
verifyCode(code);
Intent intent = new Intent(PelephoneActivity.this, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
#Override
public void onVerificationFailed(FirebaseException e) {
Toast.makeText(PelephoneActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
};
}
And the error is:
--------- beginning of crash
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.blue, PID: 6726
java.lang.IllegalArgumentException: Given String is empty or null
at com.google.android.gms.common.internal.zzbo.zzcF(Unknown Source:11)
at com.google.firebase.auth.PhoneAuthCredential.<init>(Unknown Source:3)
at com.google.firebase.auth.PhoneAuthProvider.getCredential(Unknown Source:2)
at com.example.android.bluesky.SetupAccount.PelephoneActivity.verifyCode(PelephoneActivity.java:176)
at com.example.android.bluesky.SetupAccount.PelephoneActivity.access$900(PelephoneActivity.java:52)
at com.example.android.bluesky.SetupAccount.PelephoneActivity$2.onClick(PelephoneActivity.java:150)
at android.view.View.performClick(View.java:6597)
at android.view.View.performClickInternal(View.java:6574)
at android.view.View.access$3100(View.java:778)
at android.view.View$PerformClick.run(View.java:25885)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
The database structure is:
Any ideas how to solve it?

Related

Firebase is not sending OTP code on my Phone number | Java | Android Studio

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();
}
}
});
}
}

firebase phone number authentication getting null reference

I am trying to create a phone number logging section in my application so that the user can log in using the phone number. I am trying to run my application on the physical device when I try to login using the phone number and received an error says the null reference. I have searched for the solution all over the internet but didn't get any proper solution to remove this error. I have allowed the phone authentication in firebase still, I am getting the error. I have used the country picker in my activity to get the country code and it works file.
Error occurs in
PhoneAuthProvider.getInstance().verifyPhoneNumber(
phonestring,
60,
TimeUnit.SECONDS,
Phoneactivity.this,
mCallbacks
);
Phoneactivity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_phoneactivity);
mAuth = FirebaseAuth.getInstance();
initalization();
phonenumbermethod();
emailloginmethod();
}
private void emailloginmethod() {
emaillogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),Loginactivity.class);
startActivity(intent);
}
});
}
private void phonenumbermethod() {
if(REQUEST.equals("phone")){
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
REQUEST = "OTP";
String phonenumberstring = phone.getText().toString();
String countrycode = ccp.getSelectedCountryCodeWithPlus();
phonestring = countrycode + phonenumberstring;
//Toast.makeText(getApplicationContext(),phonestring,Toast.LENGTH_SHORT).show();
verificationcodesend();
}
});
}else{
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
REQUEST = "phone";
otpstring = otp.getText().toString();
otpmethod();
}
});
}
}
private void otpmethod() {
if (TextUtils.isEmpty(otpstring)){
Toast.makeText(getApplicationContext(),"Please enter the verification code", Toast.LENGTH_SHORT).show();
}else{
loadingBar.setTitle("Verification code");
loadingBar.setMessage("Please wait...");
loadingBar.setCanceledOnTouchOutside(false);
loadingBar.show();
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(mVerificationId, otpstring);
signInWithPhoneAuthCredential(credential);
}
}
private void verificationcodesend() {
if(TextUtils.isEmpty(phonestring)){
Toast.makeText(getApplicationContext(),"Please enter phone number",Toast.LENGTH_SHORT).show();
}else{
loadingBar.setTitle("Phone verification");
loadingBar.setMessage("Please wait till we verify your account");
loadingBar.setCanceledOnTouchOutside(false);
loadingBar.show();
Log.i("phoneactivity",phonestring);
PhoneAuthProvider.getInstance().verifyPhoneNumber(
phonestring,
60,
TimeUnit.SECONDS,
Phoneactivity.this,
mCallbacks
);
}
mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(#NonNull PhoneAuthCredential phoneAuthCredential) {
signInWithPhoneAuthCredential(phoneAuthCredential);
}
#Override
public void onVerificationFailed(#NonNull FirebaseException e) {
loadingBar.dismiss();
Toast.makeText(getApplicationContext(),"Please enter the correct phone number", Toast.LENGTH_SHORT).show();
}
#Override
public void onCodeSent(#NonNull String verificationId,
#NonNull PhoneAuthProvider.ForceResendingToken token) {
loadingBar.dismiss();
mVerificationId = verificationId;
mResendToken = token;
Toast.makeText(getApplicationContext(),"Verification code has been send", Toast.LENGTH_SHORT).show();
otpnumber.setVisibility(View.VISIBLE);
phonenumber.setVisibility(View.GONE);
}
};
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
loadingBar.dismiss();
sendusertomainActivity();
Toast.makeText(getApplicationContext(),"welcome",Toast.LENGTH_SHORT).show();
} else {
String msg = task.getException().toString();
Toast.makeText(getApplicationContext(),"Error: "+ msg, Toast.LENGTH_SHORT).show();
}
}
});
}
private void sendusertomainActivity() {
Intent intent = new Intent(getApplicationContext(),HomeActivity.class);
startActivity(intent);
}
error: null reference
java.lang.NullPointerException: null reference
at com.google.android.gms.common.internal.Preconditions.checkNotNull(Unknown Source:2)
at com.google.firebase.auth.PhoneAuthProvider.verifyPhoneNumber(com.google.firebase:firebase-auth##19.2.0:9)
at com.nanb.Alpha.Phoneactivity.verificationcodesend(Phoneactivity.java:109)
at com.nanb.Alpha.Phoneactivity.access$300(Phoneactivity.java:28)
at com.nanb.Alpha.Phoneactivity$2.onClick(Phoneactivity.java:72)
at android.view.View.performClick(View.java:6608)
at android.view.View.performClickInternal(View.java:6585)
at android.view.View.access$3100(View.java:785)
at android.view.View$PerformClick.run(View.java:25921)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6864)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
update
2020-03-15 21:03:00.382 30384-30384/com.nanb.Alpha I/phoneactivity: +919771553694
You're not initializing mCallback before passing it into verifyPhoneNumber, which is what the null check is complaining about.
To fix it, move the mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {... before the call to verifyPhoneNumber.

NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
java.lang.NullPointerException:Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
Logcat
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
at com.marsad.earningapp.activity.RegisterActivity$4.onComplete(RegisterActivity.java:138)
at com.google.android.gms.tasks.zzj.run(Unknown Source:4)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:192)
at android.app.ActivityThread.main(ActivityThread.java:6711)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:549)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:826)
Error
reference.child(currentUser.getUid()).setValue(userInformation).addOnSuccessListener(new OnSuccessListener() {...
Here is the RegisterActivity.java
public class RegisterActivity extends AppCompatActivity {
private EditText nameEdit, emailEdit, phoneEdit, passwordEdit;
private Button loginBtn, signupBtn;
private static final String TAG = "SignUpActivity";
String defaultImage = "https://firebasestorage.googleapis.com/v0/b/earning-app-27780.appspot.com/o/woman.png?alt=media&token=4d66f140-4bd9-4a25-9838-cca28ebf48bb";
private FirebaseDatabase userinfoDatabase;
private DatabaseReference reference;
private FirebaseAuth mAuth;
private FirebaseUser currentUser;
private SweetAlertDialog sweetAlertDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
nameEdit = findViewById(R.id.nameEditSignup);
emailEdit = findViewById(R.id.emailEditSignup);
phoneEdit = findViewById(R.id.phoneEditSignup);
passwordEdit = findViewById(R.id.passwordEditSignup);
loginBtn = findViewById(R.id.loginBtnSignup);
signupBtn = findViewById(R.id.registerBTn);
userinfoDatabase = FirebaseDatabase.getInstance();
reference = userinfoDatabase.getReference("Users");
mAuth = FirebaseAuth.getInstance();
currentUser = mAuth.getCurrentUser();
loginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
finish();
}
});
signupBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name = nameEdit.getText().toString();
String phone = phoneEdit.getText().toString();
if (TextUtils.isEmpty(name) && TextUtils.isEmpty(phone)){
if (TextUtils.isEmpty(name)){
nameEdit.setError("Enter Your Name");
nameEdit.requestFocus();
}
if (TextUtils.isEmpty(phone)){
phoneEdit.setError("Enter Your Phone Number");
phoneEdit.requestFocus();
}
} else {
showRegisterDialog();
authenticationListener();
}
}
});
}
private void authenticationListener(){
final String email = emailEdit.getText().toString();
final String password = passwordEdit.getText().toString();
if(TextUtils.isEmpty(email) && TextUtils.isEmpty(password)){
if (TextUtils.isEmpty(email)){
emailEdit.setError("Enter Your Email");
emailEdit.requestFocus();
}
if (TextUtils.isEmpty(password)){
passwordEdit.setError("Enter Your Password");
passwordEdit.requestFocus();
}
} else
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
RegisterModel userInformation = new RegisterModel();
userInformation.setEmail(email);
userInformation.setName(nameEdit.getText().toString());
userInformation.setPassword(password);
userInformation.setPhone(phoneEdit.getText().toString());
userInformation.setRupees(0);
userInformation.setPoints(0);
userInformation.setImage(defaultImage);
reference.child(currentUser.getUid()).setValue(userInformation).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
//user registered successfully
sweetAlertDialog.dismissWithAnimation();
startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
finish();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
//user failed to register
sweetAlertDialog.dismissWithAnimation();
showRegisterErrorDialog();
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
//Error
sweetAlertDialog.dismissWithAnimation();
showRegisterErrorDialog();
}
});
}
}
The following lines of code
String currentUserId;
mAuth = FirebaseAuth.getInstance();
currentUser = mAuth.getCurrentUser();
if(currentUser!= null) {
currentUserId = currentUser.getUid(); //Do what you need to do with the id
}
currentUser is null, which means no user is signed in. You need to check for this case before calling getUid() on it.

How to create phone auth credential like Uber?

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);
}
};

java.lang.NullPointerException: Attempt to invoke virtual method ... FirebaseAuth.getCurrentUser()' on a null object reference [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I am trying to create a simple journal app but it keeps crashing because of a java null.pointer exception problem. I have been trying to fix it for a while but still could not figure it out. I am using firestore with its authentication feature.
The error is showed at the NewNoteActivity that has the getCurrentUser line.
This is the register activity:
...
public class RegisterActivity extends AppCompatActivity {
private static final String TAG = "003";
private EditText emailfield, passfield;
private FirebaseAuth mAuth;
private String email, password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
emailfield = (EditText) findViewById(R.id.reg_email);
passfield = (EditText) findViewById(R.id.reg_password);
Button submitbtn = (Button) findViewById(R.id.submitRegBtn);
mAuth = FirebaseAuth.getInstance();
submitbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!hasValidationErrors(email, password)) {
register();
}
}
});
}
private void register() {
//create user
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(RegisterActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
FirebaseFirestore db = FirebaseFirestore.getInstance();
String userId = mAuth.getCurrentUser().getUid();
//save username
CollectionReference userRef = db.collection("main").document(userId).collection("userinfo");
UserInfo userinfo = new UserInfo(email);
userRef.add(userinfo).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.e("Failed at userinfo", e.getMessage());
}
});
Intent toMain = new Intent(RegisterActivity.this, NewNoteActivity.class);
toMain.putExtra("userinfo", userinfo);
startActivity(toMain);
Toast.makeText(RegisterActivity.this, "User Created", Toast.LENGTH_SHORT).show();
} else {
Log.w(TAG, "createUserWithEmail:failure", task.getException());
Toast.makeText(RegisterActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
protected void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser != null) {
Intent toMain = new Intent(RegisterActivity.this, NewNoteActivity.class);
startActivity(toMain);
}
}
private boolean hasValidationErrors(String emailText, String passText) {
if (emailText.isEmpty()) {
emailfield.setError("Required");
emailfield.requestFocus();
return true;
} else if (passText.isEmpty()) {
passfield.setError("Required");
passfield.requestFocus();
return true;
}
return false;
}
}
This is the login activity.
...
public class LoginActivity extends AppCompatActivity {
private static final String TAG = "002";
private EditText emailfield, passfield;
private FirebaseAuth mAuth;
private String email, password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
emailfield = (EditText) findViewById(R.id.reg_email);
passfield = (EditText) findViewById(R.id.reg_password);
Button submitbtn = (Button) findViewById(R.id.submitbtn);
mAuth = FirebaseAuth.getInstance();
//get data
email = emailfield.getText().toString().trim();
password = passfield.getText().toString().trim();
submitbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!hasValidationErrors(email, password)){
login();
}
}
});
}
private void login() {
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
Log.d(TAG, "signInWithEmail:success");
FirebaseUser user = mAuth.getCurrentUser();
Toast.makeText(LoginActivity.this, "You're logged in :)", Toast.LENGTH_SHORT).show();
startActivity(new Intent(LoginActivity.this, NewNoteActivity.class));
} else {
Log.w(TAG, "signInWithEmail:failure", task.getException());
Toast.makeText(LoginActivity.this, Objects.requireNonNull(task.getException()).getMessage(), Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(LoginActivity.this, "failure listener " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
public void toRegisterpage(View view) {
startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
}
#Override
protected void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser!=null){
Intent toMain = new Intent(LoginActivity.this, NewNoteActivity.class);
startActivity(toMain);
}
}
private boolean hasValidationErrors(String emailText, String passText) {
if (emailText.isEmpty()) {
emailfield.setError("Required");
emailfield.requestFocus();
return true;
} else if (passText.isEmpty()){
passfield.setError("Required");
passfield.requestFocus();
return true;
}
return false;
}
}
add new entry activity
...
public class NewNoteActivity extends AppCompatActivity {
private RelativeLayout wholeLayout;
private EditText titleInput, desInput, reflecInput;
private Toolbar toolbar;
private FirebaseFirestore db;
private FirebaseAuth mAuth;
private String userId;
private CollectionReference userIdRef;
private Journal journal;
private String date, titleText, descText, reflecText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_newnote);
wholeLayout = (RelativeLayout) findViewById(R.id.wholeLayout);
titleInput = (EditText) findViewById(R.id.title);
desInput = (EditText) findViewById(R.id.description);
reflecInput = (EditText) findViewById(R.id.reflection);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Objects.requireNonNull(getSupportActionBar()).setDisplayShowTitleEnabled(false);
db = FirebaseFirestore.getInstance();
mAuth = FirebaseAuth.getInstance();
date = new SimpleDateFormat("EEEE, dd MMM yyyy hh:mm", Locale.getDefault()).format(new Date());
titleText = titleInput.getText().toString().trim();
descText = desInput.getText().toString().trim();
reflecText = reflecInput.getText().toString().trim();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_save:
saveNote();
Toast.makeText(this, "Saved!", Toast.LENGTH_SHORT).show();
break;
case R.id.action_list:
Toast.makeText(this, "Loading entries", Toast.LENGTH_SHORT).show();
break;
case R.id.action_mail:
Toast.makeText(this, "Have a suggestion?", Toast.LENGTH_SHORT).show();
break;
case R.id.action_settings:
Toast.makeText(this, "Loading settings", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
return true;
}
private void saveNote() {
if (!hasValidationErrors(descText)) {
if (titleText.isEmpty()) {
titleText = date;
} else {
userId = mAuth.getCurrentUser().getUid();
userIdRef = db.collection("main").document(userId).collection("journal");
journal = new Journal(userId, titleText, descText, reflecText, date);
userIdRef.add(journal).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
Toast.makeText(NewNoteActivity.this, "Saved note", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.e("Failed at saving note", e.getMessage());
Toast.makeText(NewNoteActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
}
}
private boolean hasValidationErrors(String descText) {
if (descText.isEmpty()) {
desInput.setError("Required");
desInput.requestFocus();
return true;
}
return false;
}
}
error from logcat
08-20 19:11:10.341 6603-6751/com.amethyst.within I/OpenGLRenderer: Initialized EGL, version 1.4
08-20 19:11:10.441 6603-6751/com.amethyst.within D/OpenGLRenderer: Enabling debug mode 0
08-20 19:11:15.601 6603-6603/com.amethyst.within D/AndroidRuntime: Shutting down VM
08-20 19:11:15.601 6603-6603/com.amethyst.within E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.amethyst.within, PID: 6603
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.amethyst.within/com.amethyst.within.NewNoteActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2462)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2534)
at android.app.ActivityThread.access$900(ActivityThread.java:164)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1419)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:159)
at android.app.ActivityThread.main(ActivityThread.java:5461)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:964)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:759)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
at com.amethyst.within.NewNoteActivity.onCreate(NewNoteActivity.java:69)
at android.app.Activity.performCreate(Activity.java:6093)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2415)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2534) 
at android.app.ActivityThread.access$900(ActivityThread.java:164) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1419) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:159) 
at android.app.ActivityThread.main(ActivityThread.java:5461) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:964) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:759) 
08-20 19:11:15.691 6603-6603/com.amethyst.within I/Process: Sending signal. PID: 6603 SIG: 9
08-20 19:11:15.691 6603-6603/com.amethyst.within V/Process: killProcess [6603] Callers=com.android.internal.os.RuntimeInit$UncaughtHandler.uncaughtException:99 java.lang.ThreadGroup.uncaughtException:693 java.lang.ThreadGroup.uncaughtException:690 <bottom of call stack>
Any help would be very much appreciated.
added this:
#Override
protected void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser == null) {
Intent toMain = new Intent(NewNoteActivity.this, RegisterActivity.class);
startActivity(toMain);
}
}

Categories

Resources