How can I solve this issue with FirebaseAuth? [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
i want to register a new user using firebaseAuth but i keep getting error
i have debugged using invalidate and restart and rebuilt the project, and even clean project yet it won't run successfully
RegisterActivity
public class RegisterActivity extends AppCompatActivity{
private EditText mNickname;
private EditText mEmail;
private EditText mPassword;
private TextView gotoLoginPage;
private Button mRegisterbutton;
private FirebaseAuth mAuth;
private ProgressDialog mRegProgress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
mNickname = findViewById(R.id.registerNicknameId);
mEmail = findViewById(R.id.registerEmailId);
mPassword = findViewById(R.id.registerPasswordId);
FirebaseApp.initializeApp(this);
mRegisterbutton = findViewById(R.id.registerButton);
gotoLoginPage = findViewById(R.id.gotoLoginPage);
getSupportActionBar().setTitle("Create new account");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mRegProgress = new ProgressDialog(this);
mRegisterbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String nickname = mNickname.getText().toString();
String email = mEmail.getText().toString();
String password = mPassword.getText().toString();
if (mNickname.equals("")|| mEmail.equals("") || mPassword.equals("")){
Toast.makeText(getApplicationContext(), "Fill in the fields", Toast.LENGTH_LONG).show();
mRegProgress.show();
registerUser(email, password);
}
Intent toHomePage = new Intent(RegisterActivity.this, HomeActivity.class);
startActivity(toHomePage);
finish();
}
});
gotoLoginPage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent tologinPage = new Intent(RegisterActivity.this, LoginActivity.class);
startActivity(tologinPage);
}
});
}
private void registerUser(String email, String password) {
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
Intent gotoHomePage = new Intent(RegisterActivity.this, HomeActivity.class);
startActivity(gotoHomePage);
finish();
}
}
});
}
}
MainActivity
public class HomeActivity extends AppCompatActivity {
private FirebaseAuth mAuth;
private Toolbar mToolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
FirebaseApp.initializeApp(this);
mToolbar =findViewById(R.id.toolbarId);
getSupportActionBar().setTitle("PhorumChat");
}
private void sendToStart() {
Intent goToWelcomePage = new Intent(HomeActivity.this, WelcomeActivity.class);
startActivity(goToWelcomePage);
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_logoutBtn){
FirebaseAuth.getInstance().signOut();
sendToStart();
}
return true;
}
#Override
public void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
FirebaseUser currentUser = mAuth.getCurrentUser();
updateUI(currentUser);
}
private void updateUI(FirebaseUser currentUser) {
if (currentUser ==null){
Intent homepage= new Intent(HomeActivity.this, WelcomeActivity.class);
startActivity(homepage);
finish();
}
}
}
This is the error i got when i run the program. Attempt to invoke virtual method 'com.google.firebase.auth.FirebaseUser com.google.firebase.auth.FirebaseAuth.getCurrentUser()' on a null object refererence

The error comes from:
public void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
FirebaseUser currentUser = mAuth.getCurrentUser();
updateUI(currentUser);
}
Since you're not initializing mAuth anywhere, this is null.getCurrentUser(), which throws the error you get.
Either initialize mAuth in onCreate:
mAuth = FirebaseAuth.getInstance();
Or just replace mAuth with FirebaseAuth.getInstance() where you use it.

Related

Facing Crash error or Redirecting to Mainactivity when clicking on Signup button and login both

I don't know why I am getting error on login and sign up activity with firebase.
Problem what I am facing is - whenever i click on signup button or in login button its start crashing sometimes and sometimes its redirect me to Mainactivity.class.
my Signupactivity.class
public class SignUpActivity extends AppCompatActivity {
ActivitySignUpBinding binding;
private FirebaseAuth auth;
FirebaseDatabase database;
ProgressDialog progress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivitySignUpBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
getSupportActionBar().hide();
auth = FirebaseAuth.getInstance();
database = FirebaseDatabase.getInstance();
progress = new ProgressDialog(this);
progress.setTitle("Creating Account");
progress.setMessage("We're Creating your Account");
binding.btnSignup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
progress.show();
auth.createUserWithEmailAndPassword
(binding.edEmail.getText().toString() , binding.edPassword.getText().toString()).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
userModels user = new userModels
(binding.edUsername.getText().toString() , binding.edEmail.getText().toString() , binding.edPassword.getText().toString());
String id = task.getResult().getUser().getUid();
database.getReference().child("Users").child(id).setValue(user);
progress.dismiss();
if (task.isSuccessful()){
Intent intent = new Intent(SignUpActivity.this , LoginActivty.class);
startActivity(intent);
}
else {
Toast.makeText(SignUpActivity.this, "Authentication faild", Toast.LENGTH_SHORT).show();
}
}
});
}
});
binding.tvRegister.setOnClickListener(view -> {
Intent intent = new Intent(SignUpActivity.this , LoginActivty.class);
startActivity(intent);
});
}
}

can someone help me with a warning a resource failed to call close

I am getting an error 'Failed to instrument: android/app/ResourcesManager'. This is probably the reason when I open the app it crashes immediately. There are no other errors but this error in the logcat.
The warning appears only AFTER the first time I use the emulator.
I download the avd again and open it for the first time the code works perfectly
It would mean the world to me if someone can help me fix this issue.
here is the code for MainActivity
public class MainActivity extends AppCompatActivity {
TextInputEditText textEmail, textPassword;
ProgressBar progressBar;
TextView forgotPassword;
private FirebaseAuth auth;
DatabaseReference reference;
private FirebaseAuth.AuthStateListener mAuthStateListener;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.exitmenu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.exitMenuBtn) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("Are you sure you wanna exit UwU :( ?");
builder.setCancelable(true);
builder.setNegativeButton("Yea", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
});
builder.setPositiveButton("Nah", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
return true;
}
#Override
protected void onStart() {
super.onStart();
//Attach the firebase authentication instance to the change listener
auth.addAuthStateListener(mAuthStateListener);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
auth = FirebaseAuth.getInstance();
//authChangeListener will send intent whenever the state changes => whenever user successfully logs in
mAuthStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if(firebaseAuth.getCurrentUser() != null){
// startActivity(new Intent(MainActivity.this, )); //todo: send intent to missions page
finish(); //finishes current activity
}
}
};
// if (auth.getCurrentUser() !=null)
// {
// Intent i = new Intent(MainActivity.this, GroupChatActivity.class);
// startActivity(i);
// }
// else{
textEmail = (TextInputEditText) findViewById(R.id.emailLogin);
textPassword = (TextInputEditText) findViewById(R.id.passwordLogin);
progressBar = (ProgressBar) findViewById(R.id.progressBarLogin);
forgotPassword = (TextView) findViewById(R.id.forgetBtn);
reference = FirebaseDatabase.getInstance().getReference().child("Users");
findViewById(R.id.loginBtn).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
loginUser();
}
});
}
public void loginUser()
{
progressBar.setVisibility(View.VISIBLE);
String email = Objects.requireNonNull(textEmail.getText()).toString();
String password = Objects.requireNonNull(textPassword.getText()).toString();
if (!email.equals("") && !password.equals(""))
{
auth.signInWithEmailAndPassword(email,password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful())
{
progressBar.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), "Logged In Successfully!", Toast.LENGTH_SHORT).show();
Intent i = new Intent(MainActivity.this, BottomNavigationActivity.class);
startActivity(i);
}
else {
Toast.makeText(getApplicationContext(), "Error Occurred, Try Again!", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
}
});
}
}
}

Skipping my Login activity with no reason

My problem is the title
As soon as I have done Login activity, it skips my Login activity, it shows the main activity without sign in.
Before i code in Login activity, it ran normally, meaning that the Login activity would show 1st
Here my code
MainActivity
public class MainActivity extends AppCompatActivity {
private Toolbar mToolbar;
private ViewPager viewPager;
private TabLayout tabLayout;
private TabsAccessorAdapter tabsAccessorAdapter;
private FirebaseUser currentUser;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth=FirebaseAuth.getInstance();
currentUser=mAuth.getCurrentUser();
mToolbar= findViewById(R.id.main_page_toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle("F9");
viewPager= findViewById(R.id.main_tabs_paper);
tabsAccessorAdapter= new TabsAccessorAdapter(getSupportFragmentManager());
viewPager.setAdapter(tabsAccessorAdapter);
tabLayout= findViewById(R.id.main_tabs);
tabLayout.setupWithViewPager(viewPager);
}
#Override
protected void onStart() {
super.onStart();
if(currentUser==null)
{
SendUserToLoginActivity();
}
}
private void SendUserToLoginActivity() {
Intent loginIntent = new Intent(MainActivity.this,LoginActivity.class);
startActivity(loginIntent);
}
}
LoginActivity
public class LoginActivity extends AppCompatActivity {
private FirebaseUser currentUser;
private Button LoginButton,PhoneLoginButton;
private TextInputLayout UserEmail,UserPassword;
private Button CreateNewAccount ;
private TextView ForgetPassword;
private FirebaseAuth mAuth;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mAuth = FirebaseAuth.getInstance();
currentUser=mAuth.getCurrentUser();
InitializeFields();
CreateNewAccount.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SendUserToRegisterActivity();
}
});
LoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AllowUserToLogin();
}
});
}
private void AllowUserToLogin() {
String email=UserEmail.getEditText().getText().toString();
String password=UserPassword.getEditText().getText().toString();
if(email.isEmpty()||!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()){
Toast.makeText(this,"Enter a valid email address...",Toast.LENGTH_SHORT).show();
}
if(password.isEmpty() || password.length() < 5){
Toast.makeText(this,"Password should be at least 6 character",Toast.LENGTH_SHORT).show();
}
if(password.isEmpty()&&email.isEmpty()){
Toast.makeText(this,"Please enter your email and password",Toast.LENGTH_SHORT).show();
}
else{
progressDialog.setMessage("Loading...");
progressDialog.setCanceledOnTouchOutside(true);
progressDialog.show();
mAuth.signInWithEmailAndPassword(email,password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
SendUserToMainActivity();
Toast.makeText(LoginActivity.this, "Successful!!", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
else
{
String message = task.getException().toString();
Toast.makeText(LoginActivity.this,"Error: "+ message,Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}
});
}
}
private void InitializeFields() {
LoginButton =(Button) findViewById(R.id.buttonLogin);
PhoneLoginButton =(Button) findViewById(R.id.buttonLoginByPhone);
UserEmail = (TextInputLayout) findViewById(R.id.emailLogin);
UserPassword = (TextInputLayout) findViewById(R.id.passwordLogin);
CreateNewAccount=(Button) findViewById(R.id.buttonRegister);
ForgetPassword=(TextView) findViewById(R.id.forgetpasswordLogin);
progressDialog = new ProgressDialog(this);
}
/////Neu da dang nhap se chuyen den trang mainactivity
#Override
protected void onStart() {
super.onStart();
if(currentUser !=null)
{
SendUserToMainActivity();
}
}
private void SendUserToMainActivity() {
Intent loginIntent = new Intent(LoginActivity.this,MainActivity.class);
startActivity(loginIntent);
}
private void SendUserToRegisterActivity() {
Intent registerIntent = new Intent(LoginActivity.this,RegisterActivity.class);
startActivity(registerIntent);
}
}
RegisterActivity
public class RegisterActivity extends AppCompatActivity {
private Button CreateButton,AlreadyHaveAccount;
private TextInputLayout UserEmail,UserPassword;
private FirebaseAuth mAuth;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
mAuth=FirebaseAuth.getInstance();
InitializeFields();
AlreadyHaveAccount.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SendUserToLoginActivity();
}
});
CreateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CreateNewAccount();
}
});
}
private void CreateNewAccount() {
String email=UserEmail.getEditText().getText().toString();
String password=UserPassword.getEditText().getText().toString();
if(email.isEmpty()||!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()){
Toast.makeText(this,"Enter a valid email address...",Toast.LENGTH_SHORT).show();
}
if(password.isEmpty() || password.length() < 5){
Toast.makeText(this,"Password should be at least 6 character",Toast.LENGTH_SHORT).show();
}
if(password.isEmpty()&&email.isEmpty()){
Toast.makeText(this,"Please enter your email and password",Toast.LENGTH_SHORT).show();
}
else{
progressDialog.setMessage("Creating.....");
progressDialog.setCanceledOnTouchOutside(true);
progressDialog.show();
//Ket noi FireBase tao email mat khau
mAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(this,new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful())
{
SendUserToLoginActivity();
Toast.makeText(RegisterActivity.this,"Account Created Successfully...",Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
else
{
String message = task.getException().toString();
Toast.makeText(RegisterActivity.this,"Error: "+ message,Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}
});
}
}
private void InitializeFields() {
CreateButton =(Button) findViewById(R.id.buttonRegister);
UserEmail = (TextInputLayout) findViewById(R.id.emailRegister);
UserPassword = (TextInputLayout) findViewById(R.id.passwordRegister);
AlreadyHaveAccount=(Button) findViewById(R.id.buttonHaveAccount);
progressDialog=new ProgressDialog(this);
}
private void SendUserToLoginActivity() {
Intent loginIntent = new Intent(RegisterActivity.this,LoginActivity.class);
startActivity(loginIntent);
}
}
I think the problem is in the LoginActivity, because when I wrote some code in it, the problem arose
Once the user is logged in, onStart will send the user to mainActivity
You need to create a logOut button in MainActivity, So it will not skip login page
you can also clear data of the app from the devices to make the currentUser == null
for logout
FirebaseAuth auth = FirebaseAuth.getInstance()
auth.logOut();

java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
when I am trying to run app it automatically crashing showing an error
Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method 'java.lang.String
com.google.firebase.auth.FirebaseUser.getUid()' on a null object
reference
at com.example.akhilkumar.chitchat.MainActivity.onCreate(MainActivity.java:55)
error pointing to
currentUserID = mAuth.getCurrentUser().getUid();
public class MainActivity extends AppCompatActivity {
private NavigationView navigationView;
private DrawerLayout drawerLayout;
private RecyclerView postList;
private Toolbar mToolbar;
private ActionBarDrawerToggle actionBarDrawerToggle;
private FirebaseAuth mAuth;
private DatabaseReference userRef;
private CircleImageView navProfileImage;
private TextView navProfileUserName;
String currentUserID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
userRef = FirebaseDatabase.getInstance().getReference().child("Users");
/*
mToolbar = (Toolbar)findViewById(R.id.main_page_toolbar);
setSupportActionBar(mToolbar);
*/
getSupportActionBar().setTitle("Home");
drawerLayout = (DrawerLayout)findViewById(R.id.drawable_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(MainActivity.this, drawerLayout, R.string.drawer_open, R.string.drawer_close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
navigationView = (NavigationView)findViewById(R.id.navigation_view);
View navView = navigationView.inflateHeaderView(R.layout.navigation_header);
navProfileImage = (CircleImageView)navView.findViewById(R.id.nav_profile_image);
navProfileUserName =(TextView)navView.findViewById(R.id.nav_user_full_name);
userRef.child(currentUserID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
if(dataSnapshot.exists())
{
if(dataSnapshot.hasChild("fullname"))
{
String fullname = dataSnapshot.child("fullname").getValue().toString();
navProfileUserName.setText(fullname);
}
if(dataSnapshot.hasChild("profileimage"))
{
String image = dataSnapshot.child("profileimage").getValue().toString();
Picasso.get().load(image).placeholder(R.drawable.profile).into(navProfileImage);
}
else
{
Toast.makeText(MainActivity.this, "Profile name do not exists...", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
UserMenuSelector(item);
return false;
}
});
}
#Override
protected void onStart() {
super.onStart();
FirebaseUser currentUser = mAuth.getCurrentUser();
if(currentUser == null){
SendUserToLoginActivity();
}
else{
CheckUserExistence();
}
}
private void CheckUserExistence() {
final String current_user_id = mAuth.getCurrentUser().getUid();
userRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
if(!dataSnapshot.hasChild(current_user_id))
{
SendUserToSetupActivity();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void SendUserToSetupActivity() {
Intent setupIntent = new Intent(MainActivity.this, SetupActivity.class);
setupIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(setupIntent);
finish();
}
private void SendUserToLoginActivity() {
Intent loginIntenet = new Intent(MainActivity.this, LoginActivity.class);
loginIntenet.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(loginIntenet);
finish();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(actionBarDrawerToggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
private void UserMenuSelector(MenuItem item) {
switch (item.getItemId()){
case R.id.nav_profile:
Toast.makeText(this,"Profile",Toast.LENGTH_LONG).show();
break;
case R.id.nav_home:
Toast.makeText(this,"Home",Toast.LENGTH_LONG).show();
break;
case R.id.nav_friends:
Toast.makeText(this,"Friends",Toast.LENGTH_LONG).show();
break;
case R.id.nav_find_friends:
Toast.makeText(this,"Find Friends",Toast.LENGTH_LONG).show();
break;
case R.id.nav_messages:
Toast.makeText(this,"Messages",Toast.LENGTH_LONG).show();
break;
case R.id.nav_settings:
Toast.makeText(this,"Settings",Toast.LENGTH_LONG).show();
break;
case R.id.nav_logout:
mAuth.signOut();
SendUserToLoginActivity();
Toast.makeText(this,"Logout Successfully",Toast.LENGTH_LONG).show();
break;
case R.id.nav_about_app:
Toast.makeText(this,"About",Toast.LENGTH_LONG).show();
break;
}
}
}
The following line of code:
currentUserID = mAuth.getCurrentUser().getUid();
May produce NullPointerException. So to solve this, you need to check first for nullity. So please use the following lines of code:
FirebaseUser mFirebaseUser = mAuth.getCurrentUser();
if(mFirebaseUser != null) {
currentUserID = mFirebaseUser.getUid(); //Do what you need to do with the id
}
You are accessing mAuth in onStart method but you are initializing it in onCreate. So that's why you are getting this error.
So write the following code in onCreate() method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
FirebaseUser currentUser = mAuth.getCurrentUser();
if(currentUser == null){
SendUserToLoginActivity();
}
else{
CheckUserExistence();
}
}

All intents leading to mainactivity?

Here is a code for one of my Android studio java classes:
Button button1; //log in
Button button2; //sign up
public View.OnClickListener button1Listener = new View.OnClickListener() {
public void onClick (View view){
Intent loginActivity = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(loginActivity);
}};
public View.OnClickListener button2Listener = new View.OnClickListener() {
public void onClick (View view){
Intent signupActivity = new Intent(getApplicationContext(), MainActivity.class);
startActivity(signupActivity);
}};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_front_page);
button1 = (Button) findViewById(R.id.button3);
button2 = (Button) findViewById(R.id.button4);
button1.setOnClickListener(button1Listener);
button2.setOnClickListener(button2Listener);
}
Main Activity:
public class MainActivity extends AppCompatActivity {
EditText editText;
EditText editText2;
Button button, button2;
public FirebaseAuth auth;
public FirebaseAuth.AuthStateListener authlistener;
String email, pass;
ProgressBar bar;
public View.OnClickListener buttonListener = new View.OnClickListener() {
public void onClick (View view){
email = editText.getText().toString().trim();
pass = editText2.getText().toString().trim();
createUser();
}};
public View.OnClickListener backButtonListener = new View.OnClickListener() {
public void onClick (View view){
Intent backtoMain = new Intent(getApplicationContext(), FrontPageActivity.class);
startActivity(backtoMain);
}};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText)findViewById(R.id.editText);
editText2 = (EditText)findViewById(R.id.editText2);
button = (Button)findViewById(R.id.button2);
auth = FirebaseAuth.getInstance();
button.setOnClickListener(buttonListener);
bar = (ProgressBar)findViewById(R.id.progressBar2);
bar.setVisibility(View.INVISIBLE);
button2 = (Button)findViewById(R.id.button5);
button2.setOnClickListener(backButtonListener);
}
public void createUser(){
bar.setVisibility(View.VISIBLE);
auth.createUserWithEmailAndPassword(email, pass)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_LONG).show();
bar.setVisibility(View.INVISIBLE);
} else{
Toast.makeText(getApplicationContext(), "Failed, Password must be >=6 characters", Toast.LENGTH_LONG).show();
bar.setVisibility(View.INVISIBLE);
}
}
});
}
}
Login Activity:
public class LoginActivity extends AppCompatActivity {
EditText editText;
EditText editText2;
Button button;
public FirebaseAuth Auth = FirebaseAuth.getInstance();
public FirebaseAuth.AuthStateListener authlistener;
String email, pass;
ProgressBar bar;
public View.OnClickListener buttonListener = new View.OnClickListener() {
public void onClick (View view){
email = editText.getText().toString().trim();
pass = editText2.getText().toString().trim();
logInUser();
}};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText)findViewById(R.id.editText);
editText2 = (EditText)findViewById(R.id.editText2);
button = (Button)findViewById(R.id.button2);
Auth = FirebaseAuth.getInstance();
button.setOnClickListener(buttonListener);
bar = (ProgressBar)findViewById(R.id.progressBar2);
bar.setVisibility(View.INVISIBLE);
authlistener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
} else {
// User is signed out
}
// ...
}
};
// ...
}
#Override
public void onStart() {
super.onStart();
Auth.addAuthStateListener(authlistener);
}
#Override
public void onStop() {
super.onStop();
if (authlistener != null) {
Auth.removeAuthStateListener(authlistener);
}
}
public void logInUser(){
bar.setVisibility(View.VISIBLE);
Auth.signInWithEmailAndPassword(email, pass)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()) {
Intent loggedInActivity = new Intent(getApplicationContext(), Loggedin.class);
startActivity(loggedInActivity);
}
else{
Toast.makeText(getApplicationContext(), "There was an error, try again", Toast.LENGTH_SHORT).show();
}
}
});
}
}
So, I have 2 buttons, "login," and "sign-up" and both should lead to a different intent. The sign-up leads to the mainactivity.class which is the sign up page basically.
However, even though I have mapped button1 to the loginAcitivty class, it still goes to MainActivity.class. Why is this happening?
Check your LoginActivity in this you have set setContentView(R.layout.activity_main); it is inflating the content layout of activity_main
The layout you are inflating in both the activities are same..
change your code like this,
Button button1; //log in
Button button2; //sign up
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent loginActivity = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(loginActivity);
}};
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent signupActivity = new Intent(getApplicationContext(), MainActivity.class);
startActivity(signupActivity);
}};

Categories

Resources