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.
Related
I've built an app for user authentication.
My app is crashing when I'm calling a setOnClickListener with Intent filter.
MainActivity.Java:
package com.example.passiveincome;
import android.content.Intent;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
public class MainActivity extends AppCompatActivity {
public EditText emailId, passwd;
Button btnSignUp;
TextView signIn;
FirebaseAuth firebaseAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firebaseAuth = FirebaseAuth.getInstance();
emailId = findViewById(R.id.ETemail);
passwd = findViewById(R.id.ETpassword);
btnSignUp = findViewById(R.id.btnSignUp);
signIn = findViewById(R.id.TVSignIn);
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String emailID = emailId.getText().toString();
String paswd = passwd.getText().toString();
if (emailID.isEmpty()) {
emailId.setError("Provide your Email first!");
emailId.requestFocus();
} else if (paswd.isEmpty()) {
passwd.setError("Set your password");
passwd.requestFocus();
} else if (emailID.isEmpty() && paswd.isEmpty()) {
Toast.makeText(MainActivity.this, "Fields Empty!", Toast.LENGTH_SHORT).show();
} else if (!(emailID.isEmpty() && paswd.isEmpty())) {
firebaseAuth.createUserWithEmailAndPassword(emailID, paswd).addOnCompleteListener(MainActivity.this, new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (!task.isSuccessful()) {
Toast.makeText(MainActivity.this.getApplicationContext(),
"SignUp unsuccessful: " + task.getException().getMessage(),
Toast.LENGTH_SHORT).show();
} else {
startActivity(new Intent(MainActivity.this, RegistrationActivity.class));
}
}
});
} else {
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_SHORT).show();
}
}
});
signIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent I = new Intent(MainActivity.this, LoginActivity.class);
startActivity(I);
}
});
}
}
The crash is happening when I'm transitioning from MainActivity class to LoginActivity class.
LoginActivity class:
package com.example.passiveincome;
import android.content.Intent;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class LoginActivity extends AppCompatActivity {
public EditText loginEmailId, logInpasswd;
Button btnLogIn;
TextView signup;
FirebaseAuth firebaseAuth;
private FirebaseAuth.AuthStateListener authStateListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
firebaseAuth = FirebaseAuth.getInstance();
loginEmailId = findViewById(R.id.loginEmail);
logInpasswd = findViewById(R.id.loginpaswd);
btnLogIn = findViewById(R.id.btnLogIn);
signup = findViewById(R.id.TVSignIn);
authStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
Toast.makeText(LoginActivity.this, "User logged in ", Toast.LENGTH_SHORT).show();
Intent I = new Intent(LoginActivity.this, RegistrationActivity.class);
startActivity(I);
} else {
Toast.makeText(LoginActivity.this, "Login to continue", Toast.LENGTH_SHORT).show();
}
}
};
signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent I = new Intent(LoginActivity.this, MainActivity.class);
startActivity(I);
}
});
btnLogIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String userEmail = loginEmailId.getText().toString();
String userPaswd = logInpasswd.getText().toString();
if (userEmail.isEmpty()) {
loginEmailId.setError("Provide your Email first!");
loginEmailId.requestFocus();
} else if (userPaswd.isEmpty()) {
logInpasswd.setError("Enter Password!");
logInpasswd.requestFocus();
} else if (userEmail.isEmpty() && userPaswd.isEmpty()) {
Toast.makeText(LoginActivity.this, "Fields Empty!", Toast.LENGTH_SHORT).show();
} else if (!(userEmail.isEmpty() && userPaswd.isEmpty())) {
firebaseAuth.signInWithEmailAndPassword(userEmail, userPaswd).addOnCompleteListener(LoginActivity.this, new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (!task.isSuccessful()) {
Toast.makeText(LoginActivity.this, "Not sucessfull", Toast.LENGTH_SHORT).show();
} else {
startActivity(new Intent(LoginActivity.this, RegistrationActivity.class));
}
}
});
} else {
Toast.makeText(LoginActivity.this, "Error", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
protected void onStart() {
super.onStart();
firebaseAuth.addAuthStateListener(authStateListener);
}
}
Here is the log file with error only:
2021-09-13 20:24:21.222 11737-11776/com.example.passiveincome E/eglCodecCommon: GoldfishAddressSpaceHostMemoryAllocator: ioctl_ping failed for device_type=5, ret=-1
2021-09-13 20:24:26.961 11737-11737/com.example.passiveincome E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.passiveincome, PID: 11737
android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.passiveincome/com.example.passiveincome.LoginActivity}; have you declared this activity in your AndroidManifest.xml?
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:2005)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1673)
at android.app.Activity.startActivityForResult(Activity.java:4586)
at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:676)
at android.app.Activity.startActivityForResult(Activity.java:4544)
at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:663)
at android.app.Activity.startActivity(Activity.java:4905)
at android.app.Activity.startActivity(Activity.java:4873)
at com.example.passiveincome.MainActivity$2.onClick(MainActivity.java:69)
at android.view.View.performClick(View.java:6597)
at android.view.View.performClickInternal(View.java:6574)
at android.view.View.access$3100(View.java:778)
at android.view.View$PerformClick.run(View.java:25885)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
The app crashes before I could see the LoginActivity layout.
My app crashes every time I use intent to start this activity, the activity allows people to enter some details for registering themselves, and creating an account with an email and password for login, using Firebase Auth & Database.
package com.example.jamsecure;
import android.content.Intent;
import android.os.Bundle;
import android.util.Patterns;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Spinner;
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.database.FirebaseDatabase;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
public class Register extends AppCompatActivity {
EditText email, pw, mob, pwr, fname;
Spinner loc;
ProgressBar progressBar;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_register);
progressBar=(ProgressBar) findViewById(R.id.progressBar);
progressBar.setVisibility(View.GONE);
email=findViewById(R.id.temail);
pw=findViewById(R.id.tpw);
mob=findViewById(R.id.tcn);
loc=findViewById(R.id.tl);
pwr=findViewById(R.id.tpwr);
fname=findViewById(R.id.tfn);
mAuth = FirebaseAuth.getInstance();
findViewById(R.id.br).setOnClickListener((View.OnClickListener) this);
}
#Override
protected void onStart() {
super.onStart();
if(mAuth.getCurrentUser()!=null){
//handle it
}
}
private void registerUser(){
final String em=email.getText().toString().trim();
final String name=fname.getText().toString().trim();
String password=pw.getText().toString().trim();
String password_re=pwr.getText().toString().trim();
final String phone=mob.getText().toString().trim();
final String location=loc.getSelectedItem().toString().trim();
if(name.isEmpty()){
fname.setError("Please Enter Full Name");
fname.requestFocus();
return;
}
if(em.isEmpty()){
email.setError("Email Required");
email.requestFocus();
return;
}
if(!Patterns.EMAIL_ADDRESS.matcher(em).matches()){
email.setError("Enter Valid Email");
email.requestFocus();
return;
}
if(password.isEmpty()){
pw.setError("Enter Password");
pw.requestFocus();
return;
}
if(password_re.isEmpty()){
pw.setError("Enter Password Again");
pw.requestFocus();
return;
}
if(phone.isEmpty()){
mob.setError("Please Enter Contact Info");
mob.requestFocus();
return;
}
if(location.isEmpty()){
Toast toast = Toast.makeText(this, "Please Select Location", Toast.LENGTH_LONG);
toast.show();
return;
}
progressBar.setVisibility(View.VISIBLE);
mAuth.createUserWithEmailAndPassword(em,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
User user = new User(name,em,phone,location);
FirebaseDatabase.getInstance().getReference("Users")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
progressBar.setVisibility(View.GONE);
if(task.isSuccessful()){
Toast.makeText(Register.this,"Registration Successful" ,Toast.LENGTH_LONG).show();
Intent i = new Intent(Register.this,MainActivity.class);
startActivity(i);
}
else{
Toast.makeText(Register.this,"Unable To Register",Toast.LENGTH_LONG).show();
}
}
});
}
else{
Toast.makeText(Register.this, task.getException().getMessage(),Toast.LENGTH_LONG).show();
}
}
});
}
public void onClick(View v){
switch (v.getId()){
case R.id.br: registerUser();
break;
}
}
}
There is no error displayed in the logcat but there is a warning in the java console.
Method 'onClick(android.view.View)' is never used
You must implement View.OnClickListener:
public class Register extends AppCompatActivity implements View.OnClickListener {
and add #Override to your onClick method.
Make your class to implement View.OnClickListener, then add an #override to your onClick Method in the code.
public class Register extends AppCompatActivity implements View.OnCLickListener {
//your code here
}
#Override
public void onClick(View v){
switch (v.getId()){
case R.id.br: registerUser();
break;
}
}
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
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.
This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 4 years ago.
I Build My App And It Shows A Sucessfull Build But When I tried to run in my device then it shows your app keep stoping open again and this happen in only login activity if any one help me to fix this so please help me
my Login Activity Code
package com.eassycars.www.licencespot;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
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 Activity_Login extends AppCompatActivity {
private EditText inputEmail, inputPassword;
private FirebaseAuth mAuth;
private ProgressBar progressBar;
private Button singups,forgotpass,logins;
RelativeLayout really1, really2;
Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
really1.setVisibility(View.VISIBLE);
really2.setVisibility(View.VISIBLE);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Get Firebase auth instance
mAuth = FirebaseAuth.getInstance();
if (mAuth.getCurrentUser() != null) {
startActivity(new Intent(Activity_Login.this, MainActivity.class));
finish();
}
// set the view now
setContentView(R.layout.activity__login);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
singups = (Button) findViewById(R.id.singups);
logins = (Button) findViewById(R.id.logins);
forgotpass = (Button) findViewById(R.id.forgotpass);
//Get Firebase auth instance
mAuth = FirebaseAuth.getInstance();
singups.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Activity_Login.this, singup.class));
}
});
forgotpass.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Activity_Login.this, ForgotPassword.class));
}
});
really1 = (RelativeLayout) findViewById(R.id.rellayl);
really2 = (RelativeLayout) findViewById(R.id.really2);
handler.postDelayed(runnable, 2000);
logins.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = inputEmail.getText().toString();
final String password = inputPassword.getText().toString();
if (TextUtils.isEmpty(email)) {
Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show();
return;
}
progressBar.setVisibility(View.VISIBLE);
//authenticate user
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(Activity_Login.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
progressBar.setVisibility(View.GONE);
if (!task.isSuccessful()) {
// there was an error
if (password.length() < 6) {
inputPassword.setError(getString(R.string.minimum_password));
} else {
Toast.makeText(Activity_Login.this, getString(R.string.auth_failed), Toast.LENGTH_LONG).show();
}
} else {
Intent intent = new Intent(Activity_Login.this, MainActivity.class);
startActivity(intent);
finish();
}
}
});
}
});
}
}
These are my login activity code and cant able to find error and android studio also shows that you don't have any error but there is an error that's my app keep stopping when i use my login screen.
I build An Login Activity using Firebase
Please post your error message from logcat.
If calling Handler from a Thread leads to NullPointerException,
Try to call your handler in onCreate
public class LoginActivity extends Activity {
#Override
public void onCreate(Bundle bundle){
super.onCreate(bundle);
//move this HERE!!
new Handler().post(new Runnable() {
#Override
public void run() {
// Code here will run in UI thread
}
});
}
}