A while ago, i had the main login/signup screen and the drawer working, but when i tried to implement a item database, which class while implemented i did not instantiate or call anywhere, still the app stopped working, it would open and quickly close, the mobile would report that "The app was presenting continuous failures" even without changing the business rules or model.
This my launch activity the MainActivity which is the SignIn
package com.example.appteste;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import com.example.appteste.ui.login.LoginActivity;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.UserProfileChangeRequest;
import java.util.ArrayList;
import lecho.lib.hellocharts.model.PieChartData;
import static android.content.ContentValues.TAG;
public class MainActivity extends AppCompatActivity {
private FirebaseAuth mAuth;
// private PieChart pieChart;w
final Button signUpButton = findViewById(R.id.createUserButton);
final EditText displayNameEditText = findViewById(R.id.name_field);
final EditText usernameEditText = findViewById(R.id.mail_field);
final EditText passwordEditText = findViewById(R.id.password_field);
final Button login = findViewById(R.id.login);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// sets the .xml current view
setContentView(R.layout.activity_sign_in);
// pie start
// pieChart = findViewById(R.id0
// pie end
// getEntries();
// declarations
mAuth = FirebaseAuth.getInstance();
signUpButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// calls createAccount
createAccount(displayNameEditText.getText().toString(), usernameEditText.getText().toString(), passwordEditText.getText().toString());
// logs in the system that
Log.v("signUp", "UserSignedUp:"+ usernameEditText.getText().toString() + "password: " + passwordEditText.getText().toString());
// Logs in the created user
mAuth.signInWithEmailAndPassword(usernameEditText.getText().toString(),
passwordEditText.getText().toString())
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// startActivity(new Intent(MainActivity.this, MenuActivity.class));
startActivity(new Intent(MainActivity.this, HomeActivity.class));
} else {
Toast.makeText(MainActivity.this, task.getException().getMessage(), Toast.LENGTH_LONG).show();
}
}
});
// supposed to show a welcome message
// updateUiWithUser(mAuth.getCurrentUser());
// shows message to user? maybe?
Toast.makeText(MainActivity.this, "Register Succeed.",
Toast.LENGTH_SHORT).show();
}
});
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// change to Login screen
startActivity(new Intent(MainActivity.this, LoginActivity.class));
}
});
}
public void createAccount(final String displayName, String email, String password) {
mAuth.createUserWithEmailAndPassword(email, password)
.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, "createUserWithEmail:success");
FirebaseUser user = mAuth.getCurrentUser();
// sets the display Name for the user
user.updateProfile(new UserProfileChangeRequest.Builder().setDisplayName(displayName).build());
startActivity(new Intent(MainActivity.this, LoginActivity.class));
updateUiWithUser();
} else {
// If sign in fails, display a mcessage to the user.
Log.w(TAG, "createUserWithEmail:failure", task.getException());
Toast.makeText(MainActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
// updateUiWithUser(null);
}
// TODO discover what to add here
}
});
}
private void updateUiWithUser(FirebaseUser model) {
String welcome = getString(R.string.welcome) + model.getDisplayName();
// TODO : initiate successful logged in experience
Toast.makeText(getApplicationContext(), welcome, Toast.LENGTH_LONG).show();
}
private void updateUiWithUser() {
String welcome = getString(R.string.welcome) + mAuth.getCurrentUser().getDisplayName();
// TODO : initiate successful logged in experience
Toast.makeText(getApplicationContext(), welcome, Toast.LENGTH_LONG).show();
}
}
LoginActivity(where the MainActivity goes after registering )
package com.example.appteste.ui.login;
import android.app.Activity;
import androidx.annotation.NonNull;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.appcompat.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.example.appteste.HomeActivity;
import com.example.appteste.MenuActivity;
import com.example.appteste.R;
import com.example.appteste.ui.login.LoginViewModel;
import com.example.appteste.ui.login.LoginViewModelFactory;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import static android.content.ContentValues.TAG;
public class LoginActivity extends AppCompatActivity {
private LoginViewModel loginViewModel;
private FirebaseAuth mAuth;
private LoginResult login;
public LoginResult getLogin() {
return login;
}
public void setLogin(LoginResult login) {
this.login = login;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
loginViewModel = ViewModelProviders.of(this, new LoginViewModelFactory())
.get(LoginViewModel.class);
final EditText usernameEditText = findViewById(R.id.username);
final EditText passwordEditText = findViewById(R.id.password);
final Button loginButton = findViewById(R.id.login);
final ProgressBar loadingProgressBar = findViewById(R.id.loading);
mAuth = FirebaseAuth.getInstance();
loginViewModel.getLoginFormState().observe(this, new Observer<LoginFormState>() {
#Override
public void onChanged(#Nullable LoginFormState loginFormState) {
if (loginFormState == null) {
return;
}
loginButton.setEnabled(loginFormState.isDataValid());
if (loginFormState.getUsernameError() != null) {
usernameEditText.setError(getString(loginFormState.getUsernameError()));
}
if (loginFormState.getPasswordError() != null) {
passwordEditText.setError(getString(loginFormState.getPasswordError()));
}
}
});
loginViewModel.getLoginResult().observe(this, new Observer<LoginResult>() {
#Override
public void onChanged(#Nullable LoginResult loginResult) {
if (loginResult == null) {
return;
}
loadingProgressBar.setVisibility(View.GONE);
if (loginResult.getError() != null) {
setLogin(loginResult);
showLoginFailed(loginResult.getError());
}
if (loginResult.getSuccess() != null) {
// updateUiWithUser(loginResult.getSuccess());
}
setResult(Activity.RESULT_OK);
//Complete and destroy login activity once successful
finish();
}
});
TextWatcher afterTextChangedListener = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// ignore
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// ignore
}
#Override
public void afterTextChanged(Editable s) {
loginViewModel.loginDataChanged(usernameEditText.getText().toString(),
passwordEditText.getText().toString());
}
};
usernameEditText.addTextChangedListener(afterTextChangedListener);
passwordEditText.addTextChangedListener(afterTextChangedListener);
passwordEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
loginViewModel.login(usernameEditText.getText().toString(),
passwordEditText.getText().toString());
}
return false;
}
});
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mAuth.signInWithEmailAndPassword(usernameEditText.getText().toString(),
passwordEditText.getText().toString())
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
updateUiWithUser(mAuth.getCurrentUser());
// startActivity(new Intent(LoginActivity.this, MenuActivity.class));
startActivity(new Intent(LoginActivity.this, HomeActivity.class));
} else {
Toast.makeText(LoginActivity.this, task.getException().getMessage(), Toast.LENGTH_LONG).show();
}
}
});
}
});
}
// [START on_start_check_user]
#Override
public void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
FirebaseUser currentUser = mAuth.getCurrentUser();
// updateUiWithUser(getLogin().getSuccess());
updateUiWithUser(currentUser);
}
// [END on_start_check_user]
private void updateUiWithUser(FirebaseUser user) {
String welcome = getString(R.string.welcome) + user.getDisplayName();
// TODO : initiate successful logged in experience
Toast.makeText(getApplicationContext(), welcome, Toast.LENGTH_LONG).show();
}
private void showLoginFailed(#StringRes Integer errorString) {
Toast.makeText(getApplicationContext(), errorString, Toast.LENGTH_SHORT).show();
}
}
my logcat:
2019-10-24 16:39:39.723 711-711/? E/Zygote: isWhitelistProcess - Process is Whitelisted
2019-10-24 16:39:39.723 711-711/? E/Zygote: accessInfo : 1
2019-10-24 16:39:40.209 711-711/com.example.appteste E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.appteste, PID: 711
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.appteste/com.example.appteste.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3019)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3256)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1947)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7037)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:965)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:164)
at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:157)
at android.content.Context.obtainStyledAttributes(Context.java:677)
at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:692)
at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:659)
at androidx.appcompat.app.AppCompatDelegateImpl.findViewById(AppCompatDelegateImpl.java:479)
at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:214)
at com.example.appteste.MainActivity.<init>(MainActivity.java:42)
at java.lang.Class.newInstance(Native Method)
at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:69)
at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:41)
at android.app.Instrumentation.newActivity(Instrumentation.java:1215)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3007)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3256)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1947)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7037)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:965)
Button signUpButton;
EditText displayNameEditText;
EditText usernameEditText;
EditText passwordEditText;
Button login;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// sets the .xml current view
setContentView(R.layout.activity_sign_in);
signUpButton = findViewById(R.id.createUserButton);
displayNameEditText = findViewById(R.id.name_field);
usernameEditText = findViewById(R.id.mail_field);
passwordEditText = findViewById(R.id.password_field);
login = findViewById(R.id.login);
You are trying to inflate your views upon class initialization and not in the corresponding life cycle method.
As ANDRE OLIVERA suggested, move
final Button signUpButton = findViewById(R.id.createUserButton);
final EditText displayNameEditText = findViewById(R.id.name_field);
final EditText usernameEditText = findViewById(R.id.mail_field);
final EditText passwordEditText = findViewById(R.id.password_field);
final Button login = findViewById(R.id.login);
Inside onCreate just under setContentView(R.layout.activity_sign_in); which the method that inflates the layout.
Related
I've built an app for user authentication.
My app is crashing when I'm calling a setOnClickListener with Intent filter.
MainActivity.Java:
package com.example.passiveincome;
import android.content.Intent;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
public class MainActivity extends AppCompatActivity {
public EditText emailId, passwd;
Button btnSignUp;
TextView signIn;
FirebaseAuth firebaseAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firebaseAuth = FirebaseAuth.getInstance();
emailId = findViewById(R.id.ETemail);
passwd = findViewById(R.id.ETpassword);
btnSignUp = findViewById(R.id.btnSignUp);
signIn = findViewById(R.id.TVSignIn);
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String emailID = emailId.getText().toString();
String paswd = passwd.getText().toString();
if (emailID.isEmpty()) {
emailId.setError("Provide your Email first!");
emailId.requestFocus();
} else if (paswd.isEmpty()) {
passwd.setError("Set your password");
passwd.requestFocus();
} else if (emailID.isEmpty() && paswd.isEmpty()) {
Toast.makeText(MainActivity.this, "Fields Empty!", Toast.LENGTH_SHORT).show();
} else if (!(emailID.isEmpty() && paswd.isEmpty())) {
firebaseAuth.createUserWithEmailAndPassword(emailID, paswd).addOnCompleteListener(MainActivity.this, new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (!task.isSuccessful()) {
Toast.makeText(MainActivity.this.getApplicationContext(),
"SignUp unsuccessful: " + task.getException().getMessage(),
Toast.LENGTH_SHORT).show();
} else {
startActivity(new Intent(MainActivity.this, RegistrationActivity.class));
}
}
});
} else {
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_SHORT).show();
}
}
});
signIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent I = new Intent(MainActivity.this, LoginActivity.class);
startActivity(I);
}
});
}
}
The crash is happening when I'm transitioning from MainActivity class to LoginActivity class.
LoginActivity class:
package com.example.passiveincome;
import android.content.Intent;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class LoginActivity extends AppCompatActivity {
public EditText loginEmailId, logInpasswd;
Button btnLogIn;
TextView signup;
FirebaseAuth firebaseAuth;
private FirebaseAuth.AuthStateListener authStateListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
firebaseAuth = FirebaseAuth.getInstance();
loginEmailId = findViewById(R.id.loginEmail);
logInpasswd = findViewById(R.id.loginpaswd);
btnLogIn = findViewById(R.id.btnLogIn);
signup = findViewById(R.id.TVSignIn);
authStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
Toast.makeText(LoginActivity.this, "User logged in ", Toast.LENGTH_SHORT).show();
Intent I = new Intent(LoginActivity.this, RegistrationActivity.class);
startActivity(I);
} else {
Toast.makeText(LoginActivity.this, "Login to continue", Toast.LENGTH_SHORT).show();
}
}
};
signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent I = new Intent(LoginActivity.this, MainActivity.class);
startActivity(I);
}
});
btnLogIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String userEmail = loginEmailId.getText().toString();
String userPaswd = logInpasswd.getText().toString();
if (userEmail.isEmpty()) {
loginEmailId.setError("Provide your Email first!");
loginEmailId.requestFocus();
} else if (userPaswd.isEmpty()) {
logInpasswd.setError("Enter Password!");
logInpasswd.requestFocus();
} else if (userEmail.isEmpty() && userPaswd.isEmpty()) {
Toast.makeText(LoginActivity.this, "Fields Empty!", Toast.LENGTH_SHORT).show();
} else if (!(userEmail.isEmpty() && userPaswd.isEmpty())) {
firebaseAuth.signInWithEmailAndPassword(userEmail, userPaswd).addOnCompleteListener(LoginActivity.this, new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (!task.isSuccessful()) {
Toast.makeText(LoginActivity.this, "Not sucessfull", Toast.LENGTH_SHORT).show();
} else {
startActivity(new Intent(LoginActivity.this, RegistrationActivity.class));
}
}
});
} else {
Toast.makeText(LoginActivity.this, "Error", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
protected void onStart() {
super.onStart();
firebaseAuth.addAuthStateListener(authStateListener);
}
}
Here is the log file with error only:
2021-09-13 20:24:21.222 11737-11776/com.example.passiveincome E/eglCodecCommon: GoldfishAddressSpaceHostMemoryAllocator: ioctl_ping failed for device_type=5, ret=-1
2021-09-13 20:24:26.961 11737-11737/com.example.passiveincome E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.passiveincome, PID: 11737
android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.passiveincome/com.example.passiveincome.LoginActivity}; have you declared this activity in your AndroidManifest.xml?
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:2005)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1673)
at android.app.Activity.startActivityForResult(Activity.java:4586)
at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:676)
at android.app.Activity.startActivityForResult(Activity.java:4544)
at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:663)
at android.app.Activity.startActivity(Activity.java:4905)
at android.app.Activity.startActivity(Activity.java:4873)
at com.example.passiveincome.MainActivity$2.onClick(MainActivity.java:69)
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 app crashes before I could see the LoginActivity layout.
I created a app in which i created login and register activity and also coded its java file . when im executing it and clicking on signup after filling all details , App closed suddenly . then i searched the issue in Run panel and its below error . I tried what ever i can do but i couldn't find the main reason. please help me to clear this issue . I'm tried of it. below error is showing in register.java
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.marvi, PID: 28256
java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
at com.example.marvi.register$1.onClick(register.java:67)
at android.view.View.performClick(View.java:6256)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:992)
at android.view.View$PerformClick.run(View.java:24701)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
can anyone tell me , that why its happen
login.java
package com.example.marvi;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
public class login extends AppCompatActivity {
EditText memail , mpass ;
FirebaseAuth fAuth;
Button mlogin;
TextView mcreate , mforgot;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mlogin = findViewById(R.id.signbtn);
mcreate = findViewById(R.id.create);
mforgot = findViewById(R.id.forgot);
fAuth = FirebaseAuth.getInstance();
memail = findViewById(R.id.email);
mpass = findViewById(R.id.passbox);
mlogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = memail.getText().toString().trim();
String password = mpass.getText().toString().trim();
if(TextUtils.isEmpty((email))){
memail.setError("E-mail is required");
}
if(TextUtils.isEmpty((password))){
memail.setError("Password is required");
}
if(password.length() <6){
mpass.setError("Password must be > 6");
}
//authenticate
fAuth.signInWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Toast.makeText(login.this, "Logged in successfully", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(),MainActivity.class));
}else{
Toast.makeText(login.this, "Error !"+ task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
});
mcreate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(),register.class));
finish();
}
});
}
}
register.java
package com.example.marvi;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.FirebaseFirestore;
import java.util.HashMap;
import java.util.Map;
public class register extends AppCompatActivity {
public static final String TAG = "TAG";
EditText mfullname,memail,mpass,mphone;
FirebaseAuth fAuth;
RadioButton mcheckmale,mcheckfemale;
String userID;
String gender="";
FirebaseFirestore fStore;
Button mlogin;
TextView mcreate , mforgot;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
mfullname = findViewById(R.id.name);
memail = findViewById(R.id.email);
mpass = findViewById(R.id.pass);
mphone = findViewById(R.id.number);
mcheckmale= findViewById(R.id.malebtn);
mcheckfemale = findViewById(R.id.femalebtn);
fStore = FirebaseFirestore.getInstance();
fAuth = FirebaseAuth.getInstance();
mlogin = findViewById(R.id.signbtn);
mcreate = findViewById(R.id.create);
mforgot = findViewById(R.id.forgot);
if(fAuth.getCurrentUser() !=null){
Toast.makeText(register.this, "user created", Toast.LENGTH_SHORT).show();
finish();
}
mlogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = memail.getText().toString().trim();
String password = mpass.getText().toString().trim();
if(TextUtils.isEmpty(email)){
memail.setError("Email is Required.");
return;
}
if(TextUtils.isEmpty(password)){
mpass.setError("Password is Required.");
return;
}
if(password.length() < 6){
mpass.setError("Password Must be >= 6 Characters");
return;
}
if(mcheckmale.isChecked()){
gender="Male";
}
if(mcheckfemale.isChecked()){
gender="Female";
}
fAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Toast.makeText(register.this, "user created", Toast.LENGTH_SHORT).show();
userID = fAuth.getCurrentUser().getUid();
DocumentReference documentReference = fStore.collection("users").document(userID);
Map<String,Object> user = new HashMap<>();
user.put("email",email);
user.put("pass",password);
user.put("gender",gender);
documentReference.set(user).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Log.d(TAG, "onSuccess: user profile is created for " +userID);
}
});
startActivity(new Intent(getApplicationContext(),MainActivity.class));
}else{
Toast.makeText(register.this, "Error !"+task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
});
mcreate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(),login.class));
finish();
}
});
}
}
Instantiate your edit texts like this on the onCreate() method:
memail = findViewById(R.id.yourEmailFieldID);
mpass = findViewById(R.id.yourPasswordFieldID);
Wrong reference, on the Register class for editText.
The "id = memail" you tried to referenece is the one on the wrong layout. instead of calling the two of them by the same name use a different name. either that or use different id names for different layouts. for example...
EditText android:id="#+id/editTextEmail
Below is my code for both my registration page and sign in page in android studio. The code runs however when registering the user's details does not seem to upload onto my firebase database. Therefore unable to use this data when on my sign in page. Unsure on how to rectify this within my code. Any help would be appreciated.
package com.example.spaceattack;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
public class RegisterActivity extends AppCompatActivity {
EditText emailId, password;
Button btnSignUp;
TextView tvSignIn;
FirebaseAuth mFirebaseAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
mFirebaseAuth = FirebaseAuth.getInstance();
emailId = findViewById(R.id.editText);
password = findViewById(R.id.editText2);
btnSignUp = findViewById(R.id.button2);
tvSignIn = findViewById(R.id.textView);
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = emailId.getText().toString();
String pwd = password.getText().toString();
if(email.isEmpty()) {
emailId.setError("Please enter email id");
emailId.requestFocus();
}
else if(pwd.isEmpty()) {
password.setError("Enter your password");
password.requestFocus();
}
else if(email.isEmpty() && pwd.isEmpty()) {
Toast.makeText(RegisterActivity.this,"Fields are Empty",Toast.LENGTH_SHORT).show();
}
else if(! (email.isEmpty() && pwd.isEmpty())) {
mFirebaseAuth.createUserWithEmailAndPassword(email, pwd) .addOnCompleteListener(RegisterActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(!task.isSuccessful()) {
Toast.makeText(RegisterActivity.this,"SignUp Unsuccessful, Try again",Toast.LENGTH_SHORT).show();
}
else {
startActivity(new Intent(RegisterActivity.this, WaterActivity.class));
}
}
});
}
else {
Toast.makeText(RegisterActivity.this,"Error!",Toast.LENGTH_SHORT).show();
}
}
});
tvSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent (RegisterActivity.this, LoginActivity.class);
startActivity(i);
}
});
}
}
package com.example.spaceattack;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class LoginActivity extends AppCompatActivity {
EditText emailId, password;
Button btnSignUp;
TextView tvSignUp;
FirebaseAuth mFirebaseAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mFirebaseAuth = FirebaseAuth.getInstance();
emailId = findViewById(R.id.editText);
password = findViewById(R.id.editText2);
btnSignUp = findViewById(R.id.button2);
tvSignUp = findViewById(R.id.textView2);
mAuthStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser mFirebaseUser = mFirebaseAuth.getCurrentUser();
if (mFirebaseUser != null) {
Toast.makeText(LoginActivity.this, "Logged in", Toast.LENGTH_SHORT).show();
Intent i = new Intent(LoginActivity.this, MainActivity.class);
startActivity(i);
} else {
Toast.makeText(LoginActivity.this, "Please Login", Toast.LENGTH_SHORT).show();
}
}
};
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = emailId.getText().toString();
String pwd = password.getText().toString();
if (email.isEmpty()) {
emailId.setError("Please enter email id");
emailId.requestFocus();
} else if (pwd.isEmpty()) {
password.setError("Enter your password");
password.requestFocus();
} else if (email.isEmpty() && pwd.isEmpty()) {
Toast.makeText(LoginActivity.this, "Fields are Empty", Toast.LENGTH_SHORT).show();
} else if (!(email.isEmpty() && pwd.isEmpty())) {
mFirebaseAuth.signInWithEmailAndPassword(email, pwd).addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
Toast.makeText(LoginActivity.this, "Login Error, Please Login Again", Toast.LENGTH_SHORT).show();
} else {
Intent intToHome = new Intent(LoginActivity.this, WaterActivity.class);
startActivity(intToHome);
}
}
});
} else {
Toast.makeText(LoginActivity.this, "Error!", Toast.LENGTH_SHORT).show();
}
}
});
tvSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intSignUp = new Intent(LoginActivity.this, WaterActivity.class);
startActivity(intSignUp);
}
});
}
#Override
protected void onStart() {
super.onStart();
mFirebaseAuth.addAuthStateListener(mAuthStateListener);
}
}
None of the code in your question writes to the Firebase Realtime Database as far as I can see. Keep in mind that Firebase Authentication only writes user profiles to its own internal storage. If you also want that information to be stored in the database, you'll have to do that from your application code yourself.
/AndroidRuntime: FATAL EXCEPTION: main
Process: com.aytacmelihkilic.badboy, PID: 26142
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.aytacmelihkilic.badboy/com.aytacmelihkilic.badboy.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2977)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3114)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:113)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:71)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1859)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6831)
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:927)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.aytacmelihkilic.badboy.MainActivity.onCreate(MainActivity.java:67)
at android.app.Activity.performCreate(Activity.java:7224)
at android.app.Activity.performCreate(Activity.java:7213)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2957)
MainActivity
package com.aytacmelihkilic.badboy;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
public class MainActivity extends AppCompatActivity {
EditText emailId,password;
Button btnSignUp;
TextView tvSignIn;
FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth=FirebaseAuth.getInstance();
emailId=findViewById(R.id.editText);
password=findViewById(R.id.editText2);
btnSignUp=findViewById(R.id.button);
tvSignIn=findViewById(R.id.textView);
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = emailId.getText().toString();
String pwd=password.getText().toString();
if(email.isEmpty()){
emailId.setError("lütfen e maili tekrar girin");
}
else if (pwd.isEmpty()){
password.setError("şifre yanlış");
password.requestFocus();
}
else if (email.isEmpty()&&pwd.isEmpty()){
Toast.makeText(MainActivity.this,"alanlar boş",Toast.LENGTH_SHORT).show();
}
else if (!(email.isEmpty()&&pwd.isEmpty())){
mAuth.createUserWithEmailAndPassword(email,pwd).addOnCompleteListener(MainActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()){
Toast.makeText(MainActivity.this,"kayıt başarısız lütfen tekrar deneyiniz",Toast.LENGTH_SHORT).show();
}
else {
startActivity(new Intent(MainActivity.this,HomeActivity.class));
}
}
});
}
else {
Toast.makeText(MainActivity.this,"ERROR!",Toast.LENGTH_SHORT).show();
}
}
});
tvSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i =new Intent(MainActivity.this,LoginActivity.class);
startActivity(i);
}
});
}
}
HomeActivity
package com.aytacmelihkilic.badboy;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.google.firebase.auth.FirebaseAuth;
public class HomeActivity extends AppCompatActivity {
Button btnLogout;
FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
btnLogout=findViewById(R.id.logout);
btnLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FirebaseAuth.getInstance().signOut();
Intent inToMailn=new Intent(HomeActivity.this,MainActivity.class);
startActivity(inToMailn);
}
});
}
}
LoginActivity
package com.aytacmelihkilic.badboy;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class LoginActivity extends AppCompatActivity {
EditText emailId,password;
Button btnSignIn;
TextView tvSignUp;
FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mAuth=FirebaseAuth.getInstance();
emailId=findViewById(R.id.editText);
password=findViewById(R.id.editText2);
btnSignIn=findViewById(R.id.button);
tvSignUp=findViewById(R.id.textView);
mAuthStateListener=new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = mAuth.getCurrentUser();
if (user != null) {
Toast.makeText(LoginActivity.this, "giriş yaptın", Toast.LENGTH_SHORT).show();
Intent i =new Intent(LoginActivity.this,HomeActivity.class);
startActivity(i);
}
else {
Toast.makeText(LoginActivity.this, "Lütfen giriş yapın", Toast.LENGTH_SHORT).show();
}
}
};
btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
{
String email = emailId.getText().toString();
String pwd=password.getText().toString();
if(email.isEmpty()){
emailId.setError("lütfen e maili tekrar girin");
}
else if (pwd.isEmpty()){
password.setError("şifre yanlış");
password.requestFocus();
}
else if (email.isEmpty()&&pwd.isEmpty()){
Toast.makeText(LoginActivity.this,"alanlar boş",Toast.LENGTH_SHORT).show();
}
else if (!(email.isEmpty()&&pwd.isEmpty())){
mAuth.signInWithEmailAndPassword(email,pwd).addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(!task.isSuccessful()){
Toast.makeText(LoginActivity.this,"girişde bir hata oluşdu,yekrar girmeyi deneyin",Toast.LENGTH_SHORT).show();
}
else {
Intent intToHome=new Intent(LoginActivity.this,HomeActivity.class);
startActivity(intToHome);
}
}
});
}
else {
Toast.makeText(LoginActivity.this,"ERROR!",Toast.LENGTH_SHORT).show();
}
}
}
});
tvSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intSingnUp=new Intent(LoginActivity.this,MainActivity.class);
startActivity(intSingnUp);
}
});
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthStateListener);
}
}
I use Firebase Sms verification which sends OTP to the provided number. But the problem is it detects the number automatically if the number is within the phone.But i want to enter any number and when i put the number and i can access to the next activity by manually putting the otp. But in my case the the otp is received by any number(i mean outside of the device) but when i enter the code manually in the edittext, the app crashes.
Activity where the number is given and Otp send to the number
package com.example.bohon_final__001;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Random;
public class LoginActivity extends AppCompatActivity {
private EditText LoginPhone;
private Button LoginConfirmButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
LoginPhone = (EditText) findViewById(R.id.PhoneNumberLogin);
LoginConfirmButton = (Button) findViewById(R.id.Loginbutton);
Button registerbutton=(Button)findViewById(R.id.RegisterButton);
LoginConfirmButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String number=LoginPhone.getText().toString();
if(number.isEmpty() || number.length()<11)
{
LoginPhone.setError("Valied Number Required");
LoginPhone.requestFocus();
}
else {
String PhoneNumber = "+88" + number;
Intent firstintent = new Intent(LoginActivity.this, CodeConfirm.class);
firstintent.putExtra("PhoneNumber", PhoneNumber);
startActivity(firstintent);
}
}
});
registerbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(LoginActivity.this,User_Registration.class));
}
});
}
}
Activity that receives the OTP
package com.example.bohon_final__001;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.tasks.TaskExecutors;
import com.google.firebase.FirebaseException;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.PhoneAuthCredential;
import com.google.firebase.auth.PhoneAuthProvider;
import java.util.concurrent.TimeUnit;
public class CodeConfirm extends AppCompatActivity {
EditText Otpverify;
int s;
private String VerificationCode;
Button confirmbutton,test;
private FirebaseAuth mAuth;
String code,PhoneNumber;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_code_confirm);
Otpverify = (EditText) findViewById(R.id.ConfirmCode);
test=(Button)findViewById(R.id.testbutton);
mAuth= FirebaseAuth.getInstance();
PhoneNumber = getIntent().getStringExtra("PhoneNumber");
SendVerificationCode(PhoneNumber);
confirmbutton=(Button)findViewById(R.id.ConfirmButton);
test.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent nactivity=new Intent(CodeConfirm.this,Current_Location.class);
nactivity.putExtra("Phone",PhoneNumber);
startActivity(nactivity);
}
});
confirmbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
code=Otpverify.getText().toString().trim();
if(code.isEmpty() || code.length()<6)
{
Otpverify.setError("Enter the OTP properly");
Otpverify.requestFocus();
}
Verifycode(code);
}
});
}
private void Verifycode(String code) {
PhoneAuthCredential credential=PhoneAuthProvider.getCredential(VerificationCode,code);
Signin(credential);
}
private void Signin(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful())
{
Intent WorkingSwitch=new Intent(CodeConfirm.this,Current_Location.class);
WorkingSwitch.putExtra("Phone",PhoneNumber);
WorkingSwitch.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(WorkingSwitch);
}
}
});
}
private void SendVerificationCode(String Number) {
PhoneAuthProvider.getInstance().verifyPhoneNumber(
Number,
60,
TimeUnit.SECONDS,
TaskExecutors.MAIN_THREAD,
mCallBack
);
}
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallBack = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
String code=phoneAuthCredential.getSmsCode();
if(code!=null)
{
Verifycode(code);
}
}
#Override
public void onVerificationFailed(FirebaseException e) {
Toast.makeText(CodeConfirm.this,e.getMessage(),Toast.LENGTH_LONG).show();
}
#Override
public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
VerificationCode=s;
}
};
}
I've seen similar question but the answer is not satishfying.