I am having an issue running my app after connecting to firebasefirstore. The idea is that the user can write a username during signup which will be stored on the firestore. then this username will be called in the main activity of the app. Everything is working fine until I click the logout button in the main activity which shall sign user out of firebase and get back to login activity. But once the logout button is clicked, the the app goes to the login activity but then crashes.
Here is the code I used:
Signup activity:
public class SignUpActivity extends AppCompatActivity { EditText signupEmail, signupPassword, username; Button signupBtn, cancelBtn; String userID; FirebaseAuth mAuth; FirebaseFirestore fStore; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sign_up); //Initialize Variables username = findViewById(R.id.username); signupEmail = findViewById(R.id.signupemail); signupPassword = findViewById(R.id.signuppasword); signupBtn = findViewById(R.id.signupBtn); cancelBtn = findViewById(R.id.signupCancelBtn); mAuth = FirebaseAuth.getInstance(); fStore = FirebaseFirestore.getInstance(); //Manage click on Sign-up Button signupBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (signupEmail.getText().toString().isEmpty()){ Toast.makeText(SignUpActivity.this, "Email Field is required", Toast.LENGTH_LONG).show(); } else if (signupPassword.getText().toString().isEmpty()){ Toast.makeText(SignUpActivity.this, "Password Field is required", Toast.LENGTH_SHORT).show(); }else{ mAuth.createUserWithEmailAndPassword(signupEmail.getText().toString(), signupPassword.getText().toString()).addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()){ mAuth.getCurrentUser().sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()){ userID = mAuth.getCurrentUser().getUid(); String userName = username.getText().toString(); DocumentReference docRef = fStore.collection("users").document(userID); Map<String, Object> user = new HashMap<>(); user.put("userName", userName); docRef.set(user); startActivity(new Intent(SignUpActivity.this, EmailVerActivity.class)); }else{ Toast.makeText(SignUpActivity.this, task.getException().getMessage(),Toast.LENGTH_LONG).show(); } } }); }else{ Toast.makeText(SignUpActivity.this, task.getException().getMessage(),Toast.LENGTH_LONG).show(); } } }); } } }); cancelBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(SignUpActivity.this, LoginActivity.class)); } }); }//end onCreate @Override public void onBackPressed() { super.onBackPressed(); startActivity(new Intent(SignUpActivity.this, LoginActivity.class)); }}//end Class
MainActivity (CategoriesActivity):
public class CategoriesActivity extends AppCompatActivity { //create variables: HomeWatcher mHomeWatcher; private ImageView animalBtn, seaWorldBtn, astronomyBtn, fruitsBtn, vegBtn,quizBtn, coloringbookBtn, humanBodyBtn, birdsBtn, shapesBtn; private TextView toolText, userText; private Toolbar toolbar; public ToggleButton muteBtn; Button logout; SharedPreferences sharedPreferences; //create variable for back press private long backPressedTime; private Toast backToast; FirebaseAuth mAuth; FirebaseFirestore mStore; String userID; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_categories); userText = findViewById(R.id.usernameText); mAuth = FirebaseAuth.getInstance(); mStore = FirebaseFirestore.getInstance(); userID = mAuth.getCurrentUser().getUid(); DocumentReference docRef = mStore.collection("users").document(userID); docRef.addSnapshotListener(this, new EventListener<DocumentSnapshot>() { @Override public void onEvent(@Nullable DocumentSnapshot value, @Nullable FirebaseFirestoreException error) { userText.setText(value.getString("userName") ); } }); //Assign Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); //Assign TextView in Toolbar toolText = (TextView) findViewById(R.id.toolbar_text); //Set Text to TextView in Toolbar toolText.setText("Let's Learn"); //Assign MUTE Button muteBtn = (ToggleButton) findViewById(R.id.mute_button); logout = findViewById(R.id.logout); //Use Shared Preferences to save the state of MUTE when clicked sharedPreferences = getSharedPreferences("save" , MODE_PRIVATE); muteBtn.setChecked(sharedPreferences.getBoolean("value", false)); //setOnCheckedChangeListener for UTE button to decide what to do when clicked muteBtn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { mServ.muteMusic(); //Save state in Shared Preferences SharedPreferences.Editor editor = getSharedPreferences("save" , MODE_PRIVATE).edit(); editor.putBoolean("value", true); editor.apply(); muteBtn.setChecked(true); }//end if else { mServ.unMuteMusic(); //Save state in Shared Preferences SharedPreferences.Editor editor = getSharedPreferences("save" , MODE_PRIVATE).edit(); editor.putBoolean("value", false); editor.apply(); muteBtn.setChecked(false); }//end else }//end onCheckedChanged });//end setOnCheckedChangeListener logout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { FirebaseAuth.getInstance().signOut(); startActivity(new Intent(CategoriesActivity.this, LoginActivity.class)); } }); //Use doBindService to bind this activity to Music Service class doBindService(); Intent music = new Intent(); music.setClass(this, MusicService.class); startService(music); //Use Homewatcher class to decide what to do when hoe button is clicked mHomeWatcher = new HomeWatcher(this); mHomeWatcher.setOnHomePressedListener(new HomeWatcher.OnHomePressedListener() { @Override public void onHomePressed() { if (mServ != null) { mServ.pauseMusic(); } } @Override public void onHomeLongPressed() { if (mServ != null) { mServ.pauseMusic(); } } }); mHomeWatcher.startWatch(); //Assign Animal's World Category Button animalBtn = findViewById(R.id.animals_world); //Assign Sea World Category Button seaWorldBtn = findViewById(R.id.sea_world); //Assign Astronomy World Category Button astronomyBtn = findViewById(R.id.astronomy_world); //Assign Fruits Category Button fruitsBtn = findViewById(R.id.fruits); //Assign Vegetables Category Button vegBtn = findViewById(R.id.vegetables); //Assign Quiz Category Button quizBtn = findViewById(R.id.quiz);// //Assign Coloring Book Category Button// coloringbookBtn = findViewById(R.id.coloringbook); //Assign Human Body Category Button humanBodyBtn = findViewById(R.id.humanbody); //Assign Birds Category Button birdsBtn = findViewById(R.id.birds); shapesBtn = findViewById(R.id.shapes); //setOnClickListener for Animal's World Btn animalBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent animalsIntent = new Intent(CategoriesActivity.this, AnimalsWorld.class); startActivity(animalsIntent); }//end onClick for animalBtn });//end setOnClickListener for animalBtn //setOnClickListener for Sea World Btn seaWorldBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent seaWorldIntent = new Intent(CategoriesActivity.this, SeaWorld.class); startActivity(seaWorldIntent); }//end onClick for seaWorldBtn });//end setOnClickListener for seaWorldBtn //setOnClickListener for Astronomy World Btn astronomyBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent astroWorldIntent = new Intent(CategoriesActivity.this, AstronomyWorld.class); startActivity(astroWorldIntent); }//end onClick for AstronomyWorldBtn });//end setOnClickListener for AstronomyWorldBtn //setOnClickListener for Fruits Btn fruitsBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent fruitsIntent = new Intent(CategoriesActivity.this, Fruits.class); startActivity(fruitsIntent); }//end onClick for fruitsBtn });//end setOnClickListener for fruitsBtn //setOnClickListener for Fruits Btn vegBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent vegIntent = new Intent(CategoriesActivity.this, Vegetables.class); startActivity(vegIntent); }//end onClick for fruitsBtn });//end setOnClickListener for fruitsBtn //setOnClickListener for Quiz Btn quizBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent quizIntent = new Intent(CategoriesActivity.this, QuizStartUpActivity.class); startActivity(quizIntent); }//end onClick for quizBtn });//end setOnClickListener for QuizBtn// //setOnClickListener for Coloring Book Btn// coloringbookBtn.setOnClickListener(new View.OnClickListener() {// @Override// public void onClick(View v) {// Intent coloringBookIntent = new Intent(MainActivity.this, ColoringBook.class);// startActivity(coloringBookIntent);// }//end onClick for quizBtn// });//end setOnClickListener for Coloring Book Btn //setOnClickListener for Human Body Btn humanBodyBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent humanBodyIntent = new Intent(CategoriesActivity.this, HumanBody.class); startActivity(humanBodyIntent); }//end onClick for quizBtn });//end setOnClickListener for HumanBody Btn //setOnClickListener for Birds Btn birdsBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent birdsIntent = new Intent(CategoriesActivity.this, Birds.class); startActivity(birdsIntent); }//end onClick for birdsBtn });//end setOnClickListener for Birds Btn //setOnClickListener for Shapes Btn shapesBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent shapesIntent = new Intent(CategoriesActivity.this, Shapes.class); startActivity(shapesIntent); }//end onClick for shapesBtn });//end setOnClickListener for Shapes Btn }//end onCreate //use onCreateOptionsMenu to make mehu list appear in toolbar @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main_act_list, menu); return true; }// end onCreateOptionsMenu //use onOptionsItemSelected to take action when item is clicked @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { //use switch to take action according to item ID switch (item.getItemId()){ case R.id.exit: Toast.makeText(getApplicationContext(), "Exiting", Toast.LENGTH_SHORT).show(); exit(); break; }//end switch return super.onOptionsItemSelected(item); }//end onOptionsItemSelected //Declaration of Music Service, service connection and Boolean private boolean mIsBound = false; private MusicService mServ; private ServiceConnection Scon =new ServiceConnection(){ //create onServiceConnected method public void onServiceConnected(ComponentName name, IBinder binder) { mServ = ((MusicService.ServiceBinder)binder).getService(); }//end of onServiceConnected //create onServiceDisconnected method public void onServiceDisconnected(ComponentName name) { mServ = null; } };//end of onServiceDisconnected //create doBindService method void doBindService(){ bindService(new Intent(this,MusicService.class), Scon,Context.BIND_AUTO_CREATE); mIsBound = true; }//end of doBindService //create doUnbindService method void doUnbindService() { if(mIsBound) { unbindService(Scon); mIsBound = false; } }//end of doUnbindService //create onStart Method @Override protected void onStart() { super.onStart(); //clear all preferences on Start SharedPreferences.Editor editor = sharedPreferences.edit(); editor.clear(); editor.commit(); } @Override protected void onRestart() { super.onRestart(); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.clear(); editor.commit(); } //create onResume method @Override protected void onResume() { super.onResume(); if (mServ != null) { mServ.resumeMusic(); } SharedPreferences.Editor editor = sharedPreferences.edit(); editor.clear(); editor.commit(); }//end of onResume //create onPause method @Override protected void onPause() { super.onPause(); PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); boolean isScreenOn = false; if (pm != null) { isScreenOn = pm.isScreenOn(); mServ.pauseMusic(); } if (!isScreenOn) { if (mServ != null) { mServ.pauseMusic(); } } }//end of onPause //create onStop method so that the music pauses when going to other activities @Override protected void onStop() { super.onStop(); mServ.pauseMusic(); } //create onDestroy mthod @Override protected void onDestroy() { super.onDestroy(); doUnbindService(); Intent music = new Intent(); music.setClass(this,MusicService.class); stopService(music); }//end onDestroy //create onBackPressed to exit @Override public void onBackPressed() { exit(); }//end onBackPressed public void exit(){ Intent a = new Intent(Intent.ACTION_MAIN); a.addCategory(Intent.CATEGORY_HOME); a.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(a); }}//end Class
LoginActivity:
public class LoginActivity extends AppCompatActivity { Button loginBtn; TextView newAcc, forgotPass; EditText loginEmail, loginPassword; FirebaseAuth mAuth; FirebaseUser mUser; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); mAuth=FirebaseAuth.getInstance(); mUser = mAuth.getCurrentUser(); //Initialize variables loginBtn=findViewById(R.id.loginBtn); newAcc=findViewById(R.id.noaccountBtn); forgotPass=findViewById(R.id.forgotpassBtn); loginEmail=findViewById(R.id.loginEmail); loginPassword=findViewById(R.id.loginPassword); if (mUser != null && mUser.isEmailVerified()){ startActivity(new Intent(LoginActivity.this, CategoriesActivity.class)); }else{ loginBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (loginEmail.getText().toString().isEmpty()){ Toast.makeText(LoginActivity.this, "Email Field is required", Toast.LENGTH_LONG).show(); } else if (loginPassword.getText().toString().isEmpty()){ Toast.makeText(LoginActivity.this, "Password Field is required", Toast.LENGTH_LONG).show(); }else{ mAuth.signInWithEmailAndPassword(loginEmail.getText().toString(), loginPassword.getText().toString()).addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()){ if (mAuth.getCurrentUser().isEmailVerified()){ startActivity(new Intent(LoginActivity.this, CategoriesActivity.class)); }else{ Toast.makeText(LoginActivity.this, "Please Verify Your Account First", Toast.LENGTH_LONG).show(); } }else{ Toast.makeText(LoginActivity.this, task.getException().getMessage(), Toast.LENGTH_LONG).show(); }//end if else } }); } } }); newAcc.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent (LoginActivity.this, SignUpActivity.class)); } }); forgotPass.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(LoginActivity.this, ForgotPasswordActivity.class)); } }); } }//end onCreate}//end Class