Firebase Sms verification on phone number does not working manually - java

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.

Related

android.text.Editable android.widget.EditText.getText() on a null object reference

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

int obtained from editText is not displayed

I am doing a saving system with sharedPreferences, the problem is that when I run the application it seems that if the String is saved but when converting it to int later it returns null values or 0...
the edit text only receives numbers, and what I try is to obtain its value as a string and then convert it to int, since I want to use that value in another activity
package com.example.ml_prototipe_a;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
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 org.w3c.dom.Text;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class MainActivity extends AppCompatActivity {
private EditText inputLimiter;
private TextView mostrarLimite;
public String limiterStr;
public int limiterInt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mostrarLimite = (TextView)findViewById(R.id.MostrarAciertos);
inputLimiter = (EditText) findViewById(R.id.InLimAciertos);
limiterStr = inputLimiter.getText().toString().trim();
Button btnRecNotas = findViewById(R.id.recNotasBtn);
Button btnGuardarLim = findViewById(R.id.GuardarLimite);
btnRecNotas.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intRecNotas = new Intent(MainActivity.this, MainRecNotas.class);
startActivityForResult(intRecNotas, 0);
}
});
btnGuardarLim.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
public void Cargar(View view){
SharedPreferences limitPrefs= getBaseContext().getSharedPreferences("limitData", Context.MODE_PRIVATE);
String recovaStr = limitPrefs.getString("numbreLimiter", "");
if(!"".equals(recovaStr)) {
limiterInt = Integer.parseInt(recovaStr);
mostrarLimite.setText("aciertos: " + limiterInt);
System.out.println(limiterInt);
}
}
public void Guardar(View view){
if(mostrarLimite!=null) {
SharedPreferences limitPrefs = getBaseContext().getSharedPreferences("limitData", Context.MODE_PRIVATE);
SharedPreferences.Editor editer = limitPrefs.edit();
editer.putString("numberLimiter", limiterStr);
editer.apply();
}
}
}
NEW CODE!!!!********************************
package com.example.ml_prototipe_a;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
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 org.w3c.dom.Text;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class MainActivity extends AppCompatActivity {
private EditText inputLimiter;
private TextView mostrarLimite;
public String limiterStr;
public int limiterInt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mostrarLimite = (TextView) findViewById(R.id.MostrarAciertos);
inputLimiter = (EditText) findViewById(R.id.InLimAciertos);
Button btnRecNotas = findViewById(R.id.recNotasBtn);
Button btnGuardarLim = findViewById(R.id.GuardarLimite);
Button btnCargarLimTEMP = findViewById(R.id.cargarTemp);
btnRecNotas.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intRecNotas = new Intent(MainActivity.this, MainRecNotas.class);
startActivityForResult(intRecNotas, 0);
}
});
btnGuardarLim.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Guardar();
}
});
btnCargarLimTEMP.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Cargar();
}
});
}
private void Cargar() {
SharedPreferences limitPrefs = getBaseContext().getSharedPreferences("limitData", Context.MODE_PRIVATE);
String recovaStr = limitPrefs.getString("numbreLimiter", "");
try {
limiterInt = Integer.parseInt(recovaStr);
} catch (NumberFormatException nfe) {
System.out.println("Could not parse " + nfe);
}
mostrarLimite.setText("aciertos: " + limiterInt);
System.out.println(limiterInt);
Toast.makeText(this, "Limite de aciertos: " + limiterInt, Toast.LENGTH_SHORT).show();
}
private void Guardar() {
if (mostrarLimite != null) {
SharedPreferences limitPrefs = getBaseContext().getSharedPreferences("limitData", Context.MODE_PRIVATE);
SharedPreferences.Editor editer = limitPrefs.edit();
editer.putString("numberLimiter", limiterStr);
editer.apply();
limiterStr = inputLimiter.getText().toString().trim();
Toast.makeText(this, "Limite de aciertos actualizado: " + limiterStr, Toast.LENGTH_SHORT).show();
System.out.println(limiterStr);
}
}
}

error in simple log in form in android studio java

I am beginner. I have made a simple log in form in android studio. I face a fault in if condition. Please solve this.
If username box is empty then control should go in if(...) but it goes to else part and open next intent
code is here:
package com.android.dumbseraaz;
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;
public class MainActivity extends AppCompatActivity {
private EditText uname;
private EditText pwd;
private Button login;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uname = (EditText)findViewById(R.id.txt_userName);
pwd = (EditText)findViewById(R.id.txt_Password);
login = (Button)findViewById(R.id.button);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validate(uname.getText().toString(),pwd.getText().toString());
}
});
}
private void validate(String myuname, String Pswd) {
if(myuname == "")
{
uname.setText("user");
}
else if(Pswd == "")
{
pwd.setText("PasswordMe");
}
else {
Intent intent = new Intent(MainActivity.this, app_home.class);
startActivity(intent);
}
}
}

I was trying to sign in and rearrange Android Studio, I used firebase. but when i run the screen turns on and off immediately

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

Java Android application quickly closes after opening

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.

Categories

Resources