Android studio : FATAL EXCEPTION: main - java

while I testing my app, I get the following error in the Android-Studio-logcat:
before getting this error, I was clicked on setPositiveButton of alert Dialog Button name is "EMAIL ME" with empty EditText.
and then I got Unfortunately twist has stopped.
please I need help!!
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.testing.twist, PID: 30072
java.lang.IllegalArgumentException: Given String is empty or null
at com.google.android.gms.common.internal.Preconditions.checkNotEmpty(Unknown
Source)
at com.google.firebase.auth.FirebaseAuth.sendPasswordResetEmail(com.google.firebase:firebase-auth##19.3.1:307)
at com.testing.twist.login.beginforgotpasswd(login.java:141)
at com.testing.twist.login.access$400(login.java:26)
at com.testing.twist.login$4.onClick(login.java:119)
at androidx.appcompat.app.AlertController$ButtonHandler.handleMessage(AlertController.java:167)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5268)
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:902)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:697)
here is some code of my login.java file
public class login extends AppCompatActivity {
private EditText Email;
private EditText password;
private Button btn_login;
private TextView tv_signup;
private FirebaseAuth firebaseAuth;
private TextView tv_forgotpasswd_l;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Email = (EditText)findViewById(R.id.et_email_l);
password = (EditText)findViewById(R.id.et_passwd_l);
btn_login = (Button)findViewById(R.id.btn_l);
tv_signup = (TextView)findViewById(R.id.tv_sign_up);
tv_forgotpasswd_l = (TextView)findViewById(R.id.tv_f_passwd);
firebaseAuth = FirebaseAuth.getInstance();
FirebaseUser user = firebaseAuth.getCurrentUser();
if(user != null){
finish();
startActivity(new Intent(login.this, MainActivity.class));
}
btn_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validate(Email.getText().toString(), password.getText().toString());
}
});
tv_signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(login.this,Register.class));
}
});
// Login button hide
Email.addTextChangedListener(loginTextWatcher);
password.addTextChangedListener(loginTextWatcher);
// recover pass textview click
tv_forgotpasswd_l.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showForgotpasswdDialog();
}
});
}
// Alert Dialog
private void showForgotpasswdDialog()
{
//Dialog Box code
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Forgot your password?");
//set linear layout
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setPadding(30,30,30,30);
Email.setPadding(10,10,10,10);
//view to set an dialog
final EditText Email = new EditText(this);
Email.setHint("Email");
Email.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
//text view
linearLayout.addView(Email);
builder.setView(linearLayout);
//text style
// Text view
final TextView tv = new TextView(this);
tv.setTextSize(14);
tv.setTypeface(null, Typeface.BOLD);
tv.setTextColor(Color.parseColor("black"));
tv.setText("Unfortunately, if you have never given us your email, we will not be able to reset your password.");
tv.setPadding(10,10,10,10);
linearLayout.addView(tv);
builder.setView(linearLayout);
//buttons for EMAIL ME
builder.setPositiveButton("EMAIL ME", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//input email
String email = Email.getText().toString().trim();
beginforgotpasswd(email);
}
});
//buttons for CANCEL
builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
// dismiss dialog
dialog.dismiss();
}
});
///show dialog
builder.create().show();
}
private void beginforgotpasswd(String email)
{
firebaseAuth.sendPasswordResetEmail(email).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task)
{
if (task.isSuccessful())
{
Toast.makeText(login.this,"Email sent",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(login.this,"Failed...",Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
//get and show proper error message
Toast.makeText(login.this,""+e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
private TextWatcher loginTextWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
String emailInput = Email.getText().toString().trim();
String passwdInput = password.getText().toString().trim();
btn_login.setEnabled(!emailInput.isEmpty() && !passwdInput.isEmpty());
}
#Override
public void afterTextChanged(Editable editable) {
}
};
private void validate(String usremail, String usrpassword){
firebaseAuth.signInWithEmailAndPassword(usremail,usrpassword).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(Task<AuthResult> task) {
if(task.isSuccessful()){
//Toast.makeText(login.this, "Login Successful",Toast.LENGTH_SHORT).show();
checkEmailVerification();
}
else{
Toast.makeText(login.this, "Login Failed",Toast.LENGTH_SHORT).show();
}
}
});
}
private void checkEmailVerification()
{
FirebaseUser firebaseUser = firebaseAuth.getInstance().getCurrentUser();
Boolean emailflag = firebaseUser.isEmailVerified();
if(emailflag)
{
finish();
startActivity(new Intent(login.this,MainActivity.class));
}
else
{
Toast.makeText(login.this, "Verify your email", Toast.LENGTH_SHORT).show();
firebaseAuth.signOut();
}
}
}

The call to firebaseAuth.sendPasswordResetEmail requires that the email you're sending the forgot password email to is not empty. Before calling the function check if the email is not empty.
private void beginforgotpasswd(String email)
{
if(email.isEmpty()) {
// display toast
} else {
firebaseAuth.sendPasswordResetEmail(email).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task)
{
if (task.isSuccessful())
{
Toast.makeText(login.this,"Email sent",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(login.this,"Failed...",Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
//get and show proper error message
Toast.makeText(login.this,""+e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
}

Related

How do I make the terms and conditions appear only when I log in to Google for the first time?

I want to add terms and conditions when users use my app.
But I have to show terms and conditions only one time.
I'm using firebase google login. But I have a problem when I show terms and conditions and how code remembers users accept terms and conditions and shows only one time.
Here's a google login code.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//새로운 코드다 마
signInButton = findViewById(R.id.signInButton);
GoogleSignInOptions googleSignInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
googleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this,this)
.addApi(Auth.GOOGLE_SIGN_IN_API, googleSignInOptions)
.build();
auth = FirebaseAuth.getInstance(); //파이어 베이스 인증 객체 초기화
signInButton.setOnClickListener(new View.OnClickListener() { // 구글 로그인 버튼을 클릭했을때 이곳을 수행
#Override
public void onClick(View view) {
Intent intent = Auth.GoogleSignInApi.getSignInIntent(googleApiClient);
startActivityForResult(intent,REQ_SIGN_GOOGLE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) { // 구글 로그인 인증을 요청했을때 결과 값을 되돌려 받는 곳
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == REQ_SIGN_GOOGLE) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if(result.isSuccess() == true) { // true 생략 가능, 인증 결과가 성공적이면
GoogleSignInAccount account = result.getSignInAccount(); //account 라는 데이터는 구글 로그인 정보를 담고 있습니다. - 닉네임,프로필사진uri,이메일 주소등
resultLogin(account); // 로그인 결과 값 출력 수행하라는 메서드
}
}
}
private void resultLogin(GoogleSignInAccount account) {
AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
auth.signInWithCredential(credential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()) { //로그인이 성공했으면
Intent intent = new Intent(getApplicationContext(),Home.class);
startActivity(intent);
}
else{
Toast.makeText(LoginActivity.this,"로그인 실패",Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void onBackPressed() {
long curTime=System.currentTimeMillis();
long gapTime=curTime-backBtnTime;
if(0<=gapTime && 2000>= gapTime){
moveTaskToBack(true);
finishAndRemoveTask();
android.os.Process.killProcess(android.os.Process.myPid());
}
else {
backBtnTime = curTime;
Toast.makeText(this,"뒤로 버튼을 한 번 더 누르면 종료됩니다.",Toast.LENGTH_SHORT).show();
}
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
Here is a code I want to show (terms and conditions)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_terms);
CheckBox checkBox=findViewById(R.id.checkbox);
CheckBox checkBox2=findViewById(R.id.checkbox2);
CheckBox checkBox3=findViewById(R.id.checkbox3);
checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(checkBox.isChecked()){
checkBox2.setChecked(true);
checkBox3.setChecked(true);
}else {
checkBox2.setChecked(false);
checkBox3.setChecked(false);
}
}
});
checkBox2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(checkBox.isChecked()){
checkBox.setChecked(false);
}else if(checkBox2.isChecked()&&checkBox3.isChecked()){
checkBox.setChecked(true);
}
}
});
checkBox3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(checkBox.isChecked()){
checkBox.setChecked(false);
}else if(checkBox2.isChecked()&&checkBox3.isChecked()){
checkBox.setChecked(true);
}
}
});
Button btn_agr = findViewById(R.id.btn_agr1);
btn_agr.setText(R.string.app_name);
btn_agr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(TermsActivity.this);
builder.setTitle("서비스 이용약관 ");
builder.setMessage(R.string.app_name);
builder.setNegativeButton("닫기",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
System.out.println(TAG + "이용약관 닫기");
}
});
builder.show();
}
});
Button btn_agr2 = findViewById(R.id.btn_agr2);
btn_agr2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(TermsActivity.this);
builder.setTitle("위치 정보 이용 약관 ");
builder.setMessage(R.string.app_name);
builder.setNegativeButton("닫기",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
System.out.println(TAG + "이용약관 닫기");
}
});
builder.show();
}
});
Button btn_complete = findViewById(R.id.button_complete);
btn_complete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
I tried my self - transmit variables when the user accept terms and conditions but when the user reopens the app user has to open it again
Maybe there is a way to transmit certain variables to firebase and confirm it when the user clicks the login button??
There is a way to transmit certain variables to firebase and confirm it when the user clicks the login button?
The simplest solution would be to call AuthResult#getAdditionalUserInfo() method on the Task object, because it returns an object of type AdditionalUserInfo. In this class, you can find a very useful method called isNewUser(), which can help you check if the user signs in for the first time. In code should look like this:
AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
auth.signInWithCredential(credential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()) { //로그인이 성공했으면
boolean isNewUser = task.getResult().getAdditionalUserInfo().isNewUser();
if (isNewUser) {
//Display Terms & Conditions
}
Intent intent = new Intent(getApplicationContext(),Home.class);
startActivity(intent);
}
else{
Toast.makeText(LoginActivity.this,"로그인 실패",Toast.LENGTH_SHORT).show();
}
}
});

How to delete data from firebase and recyclerview Android Studio

I try making program for deleting program from firebase. I use alertdialog so user can choose will delete data or not but when i try choose delete data my app get crashed. I have try some method for similar case but still not solved my case. Can someone tell me how to fix this?
My code for deleting data
#Override
protected void onStart(){
super.onStart();
firebaseRecyclerAdapter =
new FirebaseRecyclerAdapter<AdminStockIn, AdminViewHolder>(
AdminStockIn.class,
R.layout.row_admin_stockin_new,
AdminViewHolder.class,
DatabaseAddStock
) {
#Override
protected void populateViewHolder( AdminViewHolder adminViewHolder, AdminStockIn adminStockIn, int i) {
adminViewHolder.SetDetails(getApplicationContext(), adminStockIn.getDate(),
adminStockIn.getTime(), adminStockIn.getName(), adminStockIn.getQuantity(),
adminStockIn.getVendor(), adminStockIn.getRack());
adminViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Dialog dialog = new Dialog(AdminStockInActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.admin_stock_in_popup);
Objects.requireNonNull(dialog.getWindow());
dialog.setCancelable(true);
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(Objects.requireNonNull(dialog.getWindow()).getAttributes());
lp.width = WindowManager.LayoutParams.MATCH_PARENT;
lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
dialog.getWindow().setAttributes(lp);
EditText namepop = dialog.findViewById(R.id.nameSearchPop);
EditText quantitypop = dialog.findViewById(R.id.inputItemQuantityPop);
EditText vendorpop = dialog.findViewById(R.id.inputItemVendorPop);
EditText rackpop = dialog.findViewById(R.id.inputItemRackPop);
Button updatepop = dialog.findViewById(R.id.buttonUpdateStockPop);
namepop.setText(adminStockIn.getName());
quantitypop.setText(adminStockIn.getQuantity().toString());
vendorpop.setText(adminStockIn.getVendor());
rackpop.setText(adminStockIn.getRack());
dialog.show();
updatepop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Map<String, Object> map = new HashMap();
map.put("name", namepop.getText().toString());
map.put("quantity", quantitypop.getText().toString());
map.put("vendor", vendorpop.getText().toString());
map.put("rack", rackpop.getText().toString());
DatabaseAddStock.child(getRef(i).getKey()).updateChildren(map).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
Toast.makeText(AdminStockInActivity.this, "Data Have Updated", Toast.LENGTH_LONG).show();
dialog.dismiss();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(AdminStockInActivity.this, "Data Can't Updated", Toast.LENGTH_LONG).show();
dialog.dismiss();
}
});
}
});
}
});
//Hapus file
adminViewHolder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(AdminStockInActivity.this);
builder.setTitle("Hapus Barang Ini?");
builder.setMessage("Data tidak bisa dipulihkan setelah dihapus");
builder.setPositiveButton("Ya", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
int index = i-1;
firebaseRecyclerAdapter.getRef(index).removeValue();
firebaseRecyclerAdapter.notifyItemRemoved(i);
DatabaseAddStock.child(getRef(i).getKey()).removeValue();
firebaseRecyclerAdapter.notifyDataSetChanged();
}
});
builder.setNegativeButton("Tidak", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(AdminStockInActivity.this, "Data tidak jadi dihapus", Toast.LENGTH_SHORT).show();
}
});
builder.show();
return true;
}
});
}
};
rv_item.setAdapter(firebaseRecyclerAdapter);
}
Here my logcat
2021-11-15 13:41:52.836 24724-24724/com.example.w_a_m_s_y E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.w_a_m_s_y, PID: 24724
java.lang.ArrayIndexOutOfBoundsException: length=10; index=-2
at java.util.ArrayList.get(ArrayList.java:439)
at com.firebase.ui.database.ObservableSnapshotArray.get(ObservableSnapshotArray.java:165)
at com.firebase.ui.database.FirebaseRecyclerAdapter.getRef(FirebaseRecyclerAdapter.java:185)
at com.example.w_a_m_s_y.Admin.AdminStockFlow.AdminStockInActivity$5$2$1.onClick(AdminStockInActivity.java:348)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:174)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:236)
at android.app.ActivityThread.main(ActivityThread.java:8043)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:620)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1011)

Authorized user condition that opens another DialogFragment

Made registration using Firebase. I need that when clicking on the same CardView different DialogFragment opens and the condition is whether the user is logged in or not, i.e. by clicking on the CardView, DialogFragment1 opens in which the user logs in, if everything is successful DialogFragment1 is closed and when the CardView is pressed again, DialogFragment2 is opened, how to do this?
My dialog through which the user logs in
public class FragmentDialogLogin extends Fragment {
public static CardView close_dl, login_LG;
public static boolean isRememberUserLogin;
CardView registration;
public static EditText User_Name_LG;
public static EditText User_Password_LG;
public static String name;
public static String surname;
public static String email;
FirebaseAuth firebaseAuth;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
#SuppressLint("StaticFieldLeak")
public static LinearLayout Ll_LG;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_dialog_login, container, false);
}
#SuppressLint("SetJavaScriptEnabled")
#Override
public void onViewCreated(#NonNull final View view, #Nullable Bundle savedInstanceState) {
firebaseAuth = FirebaseAuth.getInstance();
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference("Users");
close_dl = view.findViewById(R.id.close_dl);
close_dl.setOnClickListener(v -> {
closeDialog();
});
registration = view.findViewById(R.id.registration);
registration.setOnClickListener(v -> {
int current = DialogAuthorization.VP_dialog_authorization.getCurrentItem();
int totalItems = DialogAuthorization.VP_dialog_authorization.getAdapter().getCount();
if (current < totalItems - 1) {
DialogAuthorization.VP_dialog_authorization.setCurrentItem(current + 1, true);
}
});
User_Name_LG = view.findViewById(R.id.User_Name_LG);
User_Password_LG = view.findViewById(R.id.User_Password_LG);
login_LG = view.findViewById(R.id.login_LG);
login_LG.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = User_Name_LG.getText().toString().trim();
String password = User_Password_LG.getText().toString().trim();
if (TextUtils.isEmpty(email)) {
User_Name_LG.setError("Email is Required.");
return;
}
if (TextUtils.isEmpty(password)) {
User_Password_LG.setError(getText(R.string.Rink));
return;
}
if (password.length() < 6) {
User_Password_LG.setError("Password Must be >= 6 Characters");
return;
}
firebaseAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(getContext(), "Logged in Successfully", Toast.LENGTH_SHORT).show();
DialogProfile dialog = new DialogProfile();
dialog.show(requireFragmentManager(), "DialogProfile");
} else {
Toast.makeText(getContext(), "Error ! " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
private void closeDialog() {
Fragment prev = requireActivity().getSupportFragmentManager().findFragmentByTag("DialogAuthorization");
if (prev != null) {
DialogAuthorization df = (DialogAuthorization) prev;
df.dismiss();
}
}
}
The simplest way to check whether user logged in or not is to call getCurrentUser();
private DatabaseReference rootReference;
private DatabaseReference usersRef;
#SuppressLint("SetJavaScriptEnabled")
#Override
public void onViewCreated(#NonNull final View view, #Nullable Bundle savedInstanceState) {
...
rootReference = FirebaseDatabase.getInstance().getReference();
usersRef = rootReference.child("Users");
...
login_LG.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
...
// User already logged in
if (firebaseAuth.getCurrentUser() != null) {
// Todo: close dialog fragment 1 and open dialog fragment 2
return;
}
// user did not log in
firebaseAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Store that user logged in with email
String currentUserId = firebaseAuth.getCurrentUser().getUid();
rootReference.child("Users").child(currentUserId).setValue("email");
Toast.makeText(getContext(), "Logged in Successfully", Toast.LENGTH_SHORT).show();
DialogProfile dialog = new DialogProfile();
dialog.show(requireFragmentManager(), "DialogProfile");
} else {
Toast.makeText(getContext(), "Error ! " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
You can add the int at the class as increment. You can do something like this.
At the class.
public static String surname;
public static String email;
private int counter = 1; //Add this one.
And then at the method onComplete()
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(getContext(), "Logged in Successfully", Toast.LENGTH_SHORT).show();
if (counter >1){
//DialogFragment2
}else{
DialogProfile dialog = new DialogProfile();
dialog.show(requireFragmentManager(), "DialogProfile");
counter++; //increment
}
} else {
Toast.makeText(getContext(), "Error ! " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}

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.

In my code the if part is working correctly however, the else part is not executing

I am trying to set up OTP verification
I have already tried many possibilities with the if and else, however, it didn't help out.
public class userLogin extends Activity {
EditText phnNum=null, veri = null;
FirebaseAuth au;
Button forgotpass, login;
PhoneAuthProvider.OnVerificationStateChangedCallbacks otp;
String verifyCode;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.userlogin);
login = findViewById(R.id.loginButton);
phnNum = findViewById(R.id.enter_phone);
forgotpass = findViewById(R.id.forgot_pass);
au = FirebaseAuth.getInstance();
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if ((phnNum.getText().toString()).equals("")) {
(Toast.makeText(getApplicationContext(), "Please enter the phone number and proceed to receive an OTP", Toast.LENGTH_SHORT)).show();
}
else{
otp = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(#NonNull PhoneAuthCredential phoneAuthCredential) {
}
#Override
public void onVerificationFailed(#NonNull FirebaseException e) {
}
#Override
public void onCodeSent(#NonNull String s, #NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
verifyCode = s;
(Toast.makeText(getApplicationContext(), "The OTP Code has been send, please verify the code", Toast.LENGTH_SHORT)).show();
}
};
}
}
});
}
public void send_sms (View v){
String i = (phnNum.getText()).toString();
PhoneAuthProvider.getInstance().verifyPhoneNumber(i, 60, TimeUnit.SECONDS, this, otp);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent u = new Intent(view.getContext(), otp_verify.class);
startActivity(u);
}
});
}
//SignIn Method
// We will pass value in the method with "PhoneAuthCredential" data-type.
public void SignIn(PhoneAuthCredential credential) {
//" au " is the firebase variable and call the method
au.signInWithCredential(credential).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
(Toast.makeText(getApplicationContext(), "You have Sign-In Successfully", Toast.LENGTH_SHORT)).show();
}
else{
(Toast.makeText(getApplicationContext(), "Please try again", Toast.LENGTH_SHORT)).show();
}
}
});
}
}
When I log-in with blank EditText, the if part executes but when I enter the phone number it doesn't execute the else part. I expect the when the user enters their phone number the else part should execute.
final String i = (phnNum.getText()).toString();
if ("".equals(i)) {
(Toast.makeText(getApplicationContext(), "Please enter the phone number and proceed to receive an OTP", Toast.LENGTH_SHORT)).show();
} else {
// 1. prepare callback for async call
otp = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(#NonNull PhoneAuthCredential phoneAuthCredential) {
}
#Override
public void onVerificationFailed(#NonNull FirebaseException e) {
}
#Override
public void onCodeSent(#NonNull String s, #NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
verifyCode = s;
(Toast.makeText(getApplicationContext(), "The OTP Code has been send, please verify the code", Toast.LENGTH_SHORT)).show();
Intent u = new Intent(userLogin.this, otp_verify.class);
startActivity(u);
}
};
// 2. execute actual call
PhoneAuthProvider.getInstance().verifyPhoneNumber(i, 60, TimeUnit.SECONDS, userLogin.this, otp);
}
The code snippet prepares callback and uses it on Firebase auth call. When the verification code is actually sent, the onCodeSent called and new activity launched.

Categories

Resources