Android App keeps crashing when performing user authentication - java

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.

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

Username and password wont save in Firebase database

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.

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.

When using android studio on my phone, creating an account does not work with firebase

So, I just started using Firebase and can't seem to create an account when I'm on my phone vs. my emulator. I'm not sure what the problem is, but when I click the create account button it just shows me the "User already exists" toast but there is no user with the same email and the the next activity does not open.
START ACTIVITY
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class StartActivity extends AppCompatActivity {
private Button mRegBtn;
private ImageView imageView;
private Button mLogInBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
imageView= (ImageView)findViewById(R.id.imageView);
imageView.setImageResource(R.drawable.mocha);
mRegBtn= (Button)findViewById(R.id.start_reg_btn);
mLogInBtn=(Button)findViewById(R.id.start_login_btn);
mRegBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent reg_intent= new Intent(StartActivity.this, RegisterActivity.class);
startActivity(reg_intent);
}
});
mLogInBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent login_intent= new Intent(StartActivity.this, LoginActivity.class);
startActivity(login_intent);
}
});
}
}
LOGIN ACTIVITY
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
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 LoginActivity extends AppCompatActivity {
private Button login_btn;
private TextInputLayout login_email;
private TextInputLayout login_password;
private FirebaseAuth mAuth;
private Toolbar mToolbar;
private Button create_acct_btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
login_email=(TextInputLayout)findViewById(R.id.login_email);
login_password=(TextInputLayout)findViewById(R.id.login_password);
login_btn= (Button)findViewById(R.id.login_btn);
mToolbar=(Toolbar)findViewById(R.id.login_toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle("Login");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mAuth = FirebaseAuth.getInstance();
create_acct_btn=(Button)findViewById(R.id.create_acct_btn);
login_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String displayName = login_email.getEditText().getText().toString();
String loginPassword = login_password.getEditText().getText().toString();
if (displayName.equals("") || loginPassword.equals("")) {
Toast.makeText(LoginActivity.this, "Complete fields", Toast.LENGTH_LONG).show();
}
else{
signIn(displayName, loginPassword);
}
}
});
create_acct_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent createAcc= new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(createAcc);
}
});
}
private void signIn(String email, String password) {
mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Intent loginHome= new Intent(LoginActivity.this, MainActivity.class);
startActivity(loginHome);
finish();
}
else{
Toast.makeText(LoginActivity.this, "User does not exist", Toast.LENGTH_LONG).show();
}
}
});
}
}
REGISTER ACTIVITY
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.support.v7.widget.Toolbar;
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 {
private TextInputLayout mDisplayName;
private TextInputLayout mEmail;
private TextInputLayout mPassword;
private Button mCreateBtn;
private FirebaseAuth mAuth;
private Toolbar mToolbar;
private Button login_acct_btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
mAuth = FirebaseAuth.getInstance();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
mDisplayName = (TextInputLayout) findViewById(R.id.reg_display_name);
mEmail = (TextInputLayout) findViewById(R.id.reg_email);
mPassword = (TextInputLayout) findViewById(R.id.reg_password);
mCreateBtn = (Button) findViewById(R.id.reg_create_btn);
mToolbar = (Toolbar) findViewById(R.id.register_toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle("Create Account");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
login_acct_btn= (Button)findViewById(R.id.login_acct_btn);
mCreateBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String display_name = mDisplayName.getEditText().getText().toString();
String email = mEmail.getEditText().getText().toString();
String password = mPassword.getEditText().getText().toString();
if (email.equals("") || password.equals("") || display_name.equals("")) {
Toast.makeText(RegisterActivity.this, "Complete Fields", Toast.LENGTH_LONG).show();
} else {
registerUser(display_name, email, password);
}
}
});
login_acct_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent loginAcc= new Intent(RegisterActivity.this, LoginActivity.class);
startActivity(loginAcc);
}
});
}
private void registerUser(final String display_name, final String email, final String password) {
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful() && email.length() > 5) {
Intent mainIntent = new Intent(RegisterActivity.this, MainActivity.class);
startActivity(mainIntent);
finish();
}
else if(email.length() < 5){
Toast.makeText(RegisterActivity.this, "Make email longer", Toast.LENGTH_LONG).show();
}
else if(password.length() < 5){
Toast.makeText(RegisterActivity.this, "Password must be 5 or more characters", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(RegisterActivity.this, "User already exists", Toast.LENGTH_LONG).show();
}
}
});
}
}
MAIN ACTIVITY
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class MainActivity extends AppCompatActivity {
private FirebaseAuth mAuth;
private Toolbar mToolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
mToolbar=(Toolbar)findViewById(R.id.main_page_toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle("Mocha");
}
public void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
FirebaseUser currentUser = mAuth.getCurrentUser();
if(currentUser == null){
sendToStart();
}
}
private void sendToStart(){
Intent startIntent= new Intent(MainActivity.this, StartActivity.class);
startActivity(startIntent);
finish();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
if(item.getItemId() == R.id.main_logout_btn){
FirebaseAuth.getInstance().signOut();
sendToStart();
}
return true;
}
}
MANIFEST
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".StartActivity" />
<activity
android:name=".RegisterActivity"
android:parentActivityName=".StartActivity" />
<activity android:name=".LoginActivity"
android:parentActivityName=".StartActivity"/>
</application>
</manifest>
Any help would be appreciated!
The problem can be -
private void registerUser(final String display_name, final String email, final String password) {
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful() && email.length() > 5) {
Intent mainIntent = new Intent(RegisterActivity.this, MainActivity.class);
startActivity(mainIntent);
finish();
}
else if(email.length() < 5){
Toast.makeText(RegisterActivity.this, "Make email longer", Toast.LENGTH_LONG).show();
}
else if(password.length() < 5){
Toast.makeText(RegisterActivity.this, "Password must be 5 or more characters", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(RegisterActivity.this, "User already exists", Toast.LENGTH_LONG).show();
}
}
});
}
As when a user is created successfully and length of email is greater than 5 only then it goes to main activity. But when any one of the condition is false it moves to else if.
I think email.length()>5 condition cannot be false. So task.isSuccessful() seems to be false. It means the user is not created. So problem seems in authentication rules i.e. Sign-in method. So check that once.
Moreover you can check exactly where the error is using task.getException() Refer below code -
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Intent mainIntent = new Intent(RegisterActivity.this, MainActivity.class);
startActivity(mainIntent);
finish();
}
else {
Log.i("Error is ", task.getException().toString());
}
}
});
Realized that I was missing
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></usespermission>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>

Categories

Resources