FragmentActivity, AppCompatActivity, and Fragments - java

I added this to be more clear and more easily to understand the problem.
1st Scenario: I launch the activity > opens the LoginFragment > I click the TextView to navigate to FragmentActivity. So there is no error here. Now in 2nd Scenario, I logged in a user > navigated to the MainActivity then pressed the Logout Button > navigated to the LogoutConfirmation (Remember, this is a another Activity to open the LogoutConfirmation, the LogoutConfirmation is a Fragment) then I pressed Logout button to logout and > navigated to the LoginFragment again. Lastly, I pressed the TextView to navigate again to the RegisterFragment but this time it gives me error.
This is the error I got:
java.lang.IllegalArgumentException: No view found for id 0x7f07002e (com.example.asus.perfectlogin:id/container) for fragment RegisterFragment{5285de6c #2 id=0x7f07002e}
What I notice here why the system can't find the id:container because the time I logged in then pressed the Logout button > navigate to the LogoutConfirmation (because I call this Fragment to LogoutFragment extends AppCompatActivity then to open this I use Intent and call the LogoutFragment) So now it is another Activity that contains another container, because in my code of LoginFragment to navigate the Fragment I used the id: container but the running activity is the LogoutFragment which is the id: container2. I hope you understand all of my explanation. Thank you!
Here are my codes: Main Activity extends FragmentActity
This is my Launcher.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnLogout = findViewById(R.id.btnLogout);
mAuth = FirebaseAuth.getInstance();
//mAuth.signOut();
logOut();
setupFirebaseAuth();
}
public void logOut(){
btnLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, LogoutFragment.class);
startActivity(intent);
}
});
}
/*
-------------------------------Firebase--------------------------------
*/
/*
check if the user is logged in
*/
private void checkCurrentUser(FirebaseUser user){
Log.d(TAG, "checkCurrentUser: checking if user is logged in.");
if (user == null){
Intent intent = new Intent(this, MainFragment.class);
startActivity(intent);
}
}
private void setupFirebaseAuth(){
Log.d(TAG, "setupFirebaseAuth: setting up firebase auth.");
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
//checking if the user is logged in or not
checkCurrentUser(user);
if (user != null){
//User is signed in
Log.d(TAG, "onAuthStateChanged: signed_in: " + user.getUid());
}else {
// User is signed out
Log.d(TAG, "onAuthStateChanged: signed_out");
}
}
};
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
checkCurrentUser(mAuth.getCurrentUser());
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null){
mAuth.removeAuthStateListener(mAuthListener);
}
}
Codes for: MainFragment extends AppCompatActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
LoginFragment loginFragment = new LoginFragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.container, loginFragment, loginFragment.getTag()).commit();
}
Codes for: fragment_main
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/container">
</FrameLayout>
Codes for: LoginFragment extends Fragment
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.login_fragment, container, false);
mEmail = view.findViewById(R.id.tvEmail);
mPassword = view.findViewById(R.id.tvPassword);
mForRegister = view.findViewById(R.id.tvForRegister);
mHeading = view.findViewById(R.id.heading);
eEmail = view.findViewById(R.id.etEmail);
ePassword = view.findViewById(R.id.etPassword);
btnLogin = view.findViewById(R.id.btnLogin);
// Progress Bar and Text view : GONE
mPleaseWait = view.findViewById(R.id.pleaseWait);
mProgressBar = view.findViewById(R.id.progressBar);
mProgressBar.setVisibility(View.GONE);
mPleaseWait.setVisibility(View.GONE);
//Firebase
mAuth = FirebaseAuth.getInstance();
navigatetoRegister();
setupFirebaseAuth();
signInUser();
return view;
}
public void navigatetoRegister(){
mForRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FragmentTransaction fr = getFragmentManager().beginTransaction();
fr.replace(R.id.container, new RegisterFragment());
fr.commit();
}
});
}
private boolean isStringNull(String string){
if (string.equals("")){
return true;
}
return false;
}
/*
---------------------------------Firebase-----------------------------------
*/
private void signInUser(){
// Button = to sign in the user.
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String email = eEmail.getText().toString();
String password = ePassword.getText().toString();
if (isStringNull(email) && isStringNull(password)){
Toast.makeText(getActivity(), "You must field out all the fields.", Toast.LENGTH_SHORT).show();
}else {
//Progress Bar and TextView be visible
mProgressBar.setVisibility(View.VISIBLE);
mPleaseWait.setVisibility(View.VISIBLE);
//To sign in users
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
Toast.makeText(getActivity(), "Sign in Successful!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getContext(), MainActivity.class);
startActivity(intent);
}else {
mProgressBar.setVisibility(View.GONE);
mPleaseWait.setVisibility(View.GONE);
Toast.makeText(getActivity(), "Could not sign in. Please try again.", Toast.LENGTH_SHORT).show();
}
}
});
}
}
});
}
private void setupFirebaseAuth(){
Log.d(TAG, "setupFirebaseAuth: setting up firebase auth.");
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null){
//User is signed in
Log.d(TAG, "onAuthStateChanged: signed_in: " + user.getUid());
}else {
// User is signed out
Log.d(TAG, "onAuthStateChanged: signed_out");
}
}
};
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null){
mAuth.removeAuthStateListener(mAuthListener);
}
}
Codes for: RegisterFragment extends Fragment
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.register_fragment, container, false);
mEmail = view.findViewById(R.id.tvEmail);
mPassword = view.findViewById(R.id.tvPassword);
mForLogin = view.findViewById(R.id.tvForLogin);
mHeading = view.findViewById(R.id.heading);
eEmail = view.findViewById(R.id.etEmail);
ePassword = view.findViewById(R.id.etPassword);
btnRegister = view.findViewById(R.id.btnRegister);
// Progress Bar and Text view : GONE
mPleaseWait = view.findViewById(R.id.pleaseWait);
mProgressBar = view.findViewById(R.id.progressBar);
mProgressBar.setVisibility(View.GONE);
mPleaseWait.setVisibility(View.GONE);
navigateToLogin();
registerNewUser();
setupFirebaseAuth();
return view;
}
public void navigateToLogin(){
mForLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FragmentTransaction fr = getFragmentManager().beginTransaction();
fr.replace(R.id.container, new LoginFragment());
fr.commit();
}
});
}
private boolean isStringNull(String string){
if (string.equals("")){
return true;
}
return false;
}
/*
To check if the user is creating a same email.
*/
public void checkUserId(){
if (mAuth.getCurrentUser() != null){
userID = mAuth.getCurrentUser().getUid();
}
}
/*
---------------------------------Firebase-----------------------------------
*/
public void registerNewUser(){
// To register new user
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String email = eEmail.getText().toString();
String password = ePassword.getText().toString();
if (isStringNull(email) && isStringNull(password)){
Toast.makeText(getContext(), "You must field out all the fields.", Toast.LENGTH_SHORT).show();
}else {
//Progress Bar and TextView be visible
mProgressBar.setVisibility(View.VISIBLE);
mPleaseWait.setVisibility(View.VISIBLE);
//To create/register new user
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
//user is succesfully registered and logged in
checkUserId(); //Checking if the user is create same email
Log.d(TAG, "onComplete: AuthstateChange: " + userID);
Toast.makeText(getActivity(), "Registered Successfully", Toast.LENGTH_SHORT).show();
//AFter Registering account it will navigate to the Login Fragment
FragmentTransaction fr = getFragmentManager().beginTransaction();
fr.replace(R.id.container, new LoginFragment());
fr.commit();
}else {
mProgressBar.setVisibility(View.GONE);
mPleaseWait.setVisibility(View.GONE);
Toast.makeText(getActivity(), "Please check your internet. Or maybe you registered same email.", Toast.LENGTH_SHORT).show();
}
}
});
}
}
});
}
//This is the listener to check the Firebase if there is user logged in or not.
private void setupFirebaseAuth(){
Log.d(TAG, "setupFirebaseAuth: setting up firebase auth.");
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null){
//User is signed in
Log.d(TAG, "onAuthStateChanged: signed_in: " + user.getUid());
}else {
// User is signed out
Log.d(TAG, "onAuthStateChanged: signed_out");
}
}
};
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null){
mAuth.removeAuthStateListener(mAuthListener);
}
}
Codes for: LogoutFragment extends AppCompatActivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.logout_fragment);
LogOutConfirmation fragment = new LogOutConfirmation();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.container2, fragment, null).commit();
}
Codes for: fragment_logout.xml
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/container2">
</FrameLayout>
Codes for: LogoutConfirmation extends Fragment
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.logout_confirmation, container, false);
mLogout = view.findViewById(R.id.heading);
mPleaseWait = view.findViewById(R.id.tvPleaseWait);
mProgressBar = view.findViewById(R.id.progressBar);
btnLogout = view.findViewById(R.id.btnLogout);
mPleaseWait.setVisibility(View.GONE);
mProgressBar.setVisibility(View.GONE);
mAuth = FirebaseAuth.getInstance();
signOut();
setupFirebaseAuth();
return view;
}
/*
//This is the button to sign out. Then system will read next the `setupFirebaseAuth`. So if mAuthListener
knows there is no user signed it so it will navigate to the LoginFragment
*/
public void signOut(){
btnLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mAuth.signOut();
//Progress Bar and TextView
mPleaseWait.setVisibility(View.VISIBLE);
mProgressBar.setVisibility(View.VISIBLE);
Log.d(TAG, "onClick: attempting to log out.");
}
});
}
/*
--------------------------------------Firebase-------------------------------------------
*/
private void setupFirebaseAuth(){
Log.d(TAG, "setupFirebaseAuth: setting up firebase auth.");
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
//checking if the user is logged in or not
if (user != null){
//User is signed in
Log.d(TAG, "onAuthStateChanged: signed_in: " + user.getUid());
}else {
// User is signed out
Log.d(TAG, "onAuthStateChanged: signed_out");
//After logging out, it will navigate to LoginFragment
FragmentTransaction fr = getFragmentManager().beginTransaction();
fr.replace(R.id.container2, new LoginFragment());
fr.commit();
}
}
};
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null){
mAuth.removeAuthStateListener(mAuthListener);
}
}

Related

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();

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

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.

Using FirebaseAuthListener and it will navigate to activity with fragment if there is no user logged in

What I am trying to do here is when I launch my MainActivity with FirebaseAuthListener and there is no user logged in it will navigate to the MainFragment and the MainFragment is for the container that connects to my SignInFragment(this SignInFragment is extended Fragment). So basically, the MainFragment is extended to AppCompatActivity.
It actually works all but my problem is the MainFragemnt is blank in my emulator, it supposed to be display the LoginFragment.
Here are my codes: MainActivity class
//Firebase
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private TextView mWelcome;
private Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWelcome = findViewById(R.id.tvWelcome);
setupFirebaseAuth();
}
/*
--------------------------------------Firebase-----------------------------------------
*/
private void getCurrentUser(FirebaseUser user){
Log.d(TAG, "getCurrentUser: checking if user is logged in.");
if (user == null){
Intent intent = new Intent(this, MainFragment.class);
startActivity(intent);
}
}
private void setupFirebaseAuth(){
Log.d(TAG, "setupFirebaseAuth: setting up firebase auth.");
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
//Check if the user is logged in
FirebaseUser user = firebaseAuth.getCurrentUser();
getCurrentUser(user);
if (user != null){
//User is signed in
Log.d(TAG, "onAuthStateChanged: signed _in: " + user.getUid());
} else {
//User is signed out
Log.d(TAG, "onAuthStateChanged: signed_out");
}
}
};
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
protected void onStop() {
super.onStop();
if (mAuthListener != null){
mAuth.removeAuthStateListener(mAuthListener);
}
}
My codes for MainFragment:
public class MainFragment extends AppCompatActivity {
#Override
public void onCreate(#Nullable Bundle savedInstanceState, #Nullable PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
setContentView(R.layout.fragment_main);
SignInFragment fragment = new SignInFragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.container, fragment, null).commit();
My code for SignInFragment:
public class SignInFragment extends Fragment {
private static final String TAG = "SignInFragment";
private TextView mEmail, mPassword, mForRegister;
private EditText eEmail, ePassword;
private Button btnLogin;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.signin_fragment,container,false);
//TextView
mEmail = view.findViewById(R.id.tvEmail);
mPassword = view.findViewById(R.id.tvPassword);
mForRegister = view.findViewById(R.id.tvForRegister);
//EditText
eEmail = view.findViewById(R.id.etEmail);
ePassword = view.findViewById(R.id.etPassword);
//Button
btnLogin = view.findViewById(R.id.btnLogin);
//Navigating to RegisterFragment
mForRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentTransaction fr = getFragmentManager().beginTransaction();
fr.replace(R.id.container, new RegisterFragment());
fr.commit();
}
});
return view;
}
This is the picture of the emulator:
Thank you!
try changing your onCreate method. use the following instead:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

Exit App When Pressed Back Button after Login, but OnPressedBack keep Coming Back to First Page

I have 3 activity the first one is LandingActivity. This is the launcher activity when you open the app and not logged in, the second is SignInActivity and the third is HomeActivity, this activity is launched when you're already logged in and open the app.
Here's the code:
LandingActivity
public class LandingActivity extends AppCompatActivity {
private FirebaseAuth auth;
private Button btnSignIn, btnSignUp;
TextView textSlogan;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_landing);
//Init Firebase Auth
auth = FirebaseAuth.getInstance();
//Check if Already Session
if (auth.getCurrentUser() != null){
startActivity(new Intent(LandingActivity.this, HomeActivity.class));
}
textSlogan = (TextView)findViewById(R.id.textSlogan);
Typeface face = Typeface.createFromAsset(getAssets(),"fonts/NABILA.TTF");
textSlogan.setTypeface(face);
btnSignIn = (Button)findViewById(R.id.main_sign_in_button);
btnSignUp = (Button)findViewById(R.id.main_sign_up_button);
btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LandingActivity.this, SignInActivity.class));
}
});
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LandingActivity.this, SignUpActivity.class));
}
});
}
}
SignInActivity
public class SignInActivity extends AppCompatActivity {
private EditText inputEmail, inputPassword;
private FirebaseAuth auth;
private ProgressBar progressBar;
private Button btnSignIn, btnResetPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Get Firebase Auth Instance
auth = FirebaseAuth.getInstance();
setContentView(R.layout.activity_sign_in);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
btnSignIn = (Button) findViewById(R.id.action_sign_in_button);
btnResetPassword = (Button) findViewById(R.id.intent_reset_password_button);
//Get Firebase auth instance
auth = FirebaseAuth.getInstance();
btnSignIn.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
auth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(SignInActivity.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(SignInActivity.this, getString(R.string.auth_failed), Toast.LENGTH_SHORT).show();
}
} else {
Intent intent = new Intent(SignInActivity.this, HomeActivity.class);
startActivity(intent);
finish();
}
}
});
}
});
btnResetPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(SignInActivity.this, ResetPasswordActivity.class));
}
});
}
}
HomeActivity
public class HomeActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private FirebaseAuth auth;
private FirebaseAuth.AuthStateListener authStateListener;
private ProgressBar progressBar;
private long backPressedTime;
private Toast backToast;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(this);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
//Get Firebase Auth Instance
auth = FirebaseAuth.getInstance();
//Get Current User
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
authStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if (user == null) {
//User Auth State is Changed - User is Null
//Launch Login Activity
startActivity(new Intent(HomeActivity.this, LandingActivity.class));
finish();
}
}
};
}
#Override
public void onBackPressed() {
if (backPressedTime + 2000 > System.currentTimeMillis()){
backToast.cancel();
super.onBackPressed();
} else {
backToast = Toast.makeText(getBaseContext(), "Press Back again to Exit", Toast.LENGTH_SHORT);
backToast.show();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.actbar_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
int id = menuItem.getItemId();
progressBar.setVisibility(View.VISIBLE);
switch (id) {
case R.id.action_edit_password:
startActivity(new Intent(HomeActivity.this, ChangePasswordActivity.class));
progressBar.setVisibility(View.GONE);
break;
case R.id.action_sign_out:
auth.signOut();
progressBar.setVisibility(View.GONE);
Toast.makeText(this, "Signed Out", Toast.LENGTH_SHORT).show();
finish();
startActivity(new Intent(HomeActivity.this, LandingActivity.class));
}
return super.onOptionsItemSelected(menuItem);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_home) {
auth.getCurrentUser();
startActivity(new Intent(HomeActivity.this, HomeActivity.class));
} else if (id == R.id.nav_app_received) {
} else if (id == R.id.nav_app_submitted) {
} else if (id == R.id.nav_tutorial) {
startActivity(new Intent(HomeActivity.this, TutorialActivity.class));
} else if (id == R.id.nav_about_us) {
startActivity(new Intent(HomeActivity.this, AboutUsActivity.class));
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
I've tried onBackPressed() method to exit the app if back button pressed, but it still comes back to the LandingActivity instead of exiting the app. So, how to exit the app when back button is pressed but the user did not log out.
After startActivity() methods in your LandingPage activity use the method finish(). An excellent explanation of the finish method is given here

Categories

Resources