Firebase/DrawerLayout - Logged out for no reason? - java

I am working on a DrawerLayout, and when I click one of the items to go to a Profile page, it logs me out (I can notice this because I get a NullPointer error for the UserAuth [even though I was authed before clicking this]
Note: I didn't notice this until I tried to modularize my code by adding "initialize" methods and such.
This is the code for the items in the drawerlayout:
private void setupDrawerLayout() {
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
navigationView = (NavigationView) findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override public boolean onNavigationItemSelected(MenuItem menuItem) {
//If Clicked...then get item and go to associated page
switch(menuItem.getTitle().toString())
{
case "Profile":
Log.i("Profile", menuItem.getTitle().toString());
startActivity(new Intent(HomeActivity.this, ProfileActivity.class));
/*case "Share":
startActivity(new Intent(HomeActivity.this, ProfileActivity.class));
case "Settings":
startActivity(new Intent(HomeActivity.this, ProfileActivity.class)); */
case "Logout":
Log.i("Logout", menuItem.getTitle().toString());
FirebaseAuth.getInstance().signOut();
//startActivity(new Intent(HomeActivity.this, LoginActivity.class));
}
menuItem.setChecked(true);
drawerLayout.closeDrawers();
return true;
}
});
}
For some reason even though I'm clicking the "Profile" item, it goes to both the Case for that, AND for "Logout" as can be seen by the Log statements:
I/Profile: Profile
I/Logout: Profile
And then this leads to the Error:
E/UncaughtException: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.netgalaxystudios.timeclock/com.netgalaxystudios.timeclock.Activities.ProfileActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
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.netgalaxystudios.timeclock.Activities.ProfileActivity.onCreate(ProfileActivity.java:70)
ProfileActivity.java (is the activity I am trying to get to by clicking on the ITEM in the menu). It refers to this line, but really the error is coming from HomeActivity as I understand it... ) :
currentUserString = currentUser.getUid().toString();
HomeActivity.java:
public class HomeActivity extends AppCompatActivity {
private DrawerLayout drawerLayout;
private NavigationView navigationView;
ImageView menu, closeDrawer;
RelativeLayout navHeader;
//Profile Stuff
DatabaseReference employeesRefPhoto, employeesRefFname, employeesRefLname;
FirebaseDatabase database;
String photoUrl;
ImageView profilePhoto;
FirebaseUser currentUser;
String currentUserString;
TextView nameTV, lnameTV;
TextView businessesTV;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drawer_layout);
/////////////////////////
//METHODS
//initViews();
//setupDrawerLayout();
//footerOnClick();
//////////////////////////
menu = (ImageView) findViewById(R.id.menu);
menu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
drawerLayout.openDrawer(Gravity.LEFT);
}
});
currentUser = FirebaseAuth.getInstance().getCurrentUser();
currentUserString = currentUser.getUid().toString();
setupDrawerLayout();
//https://stackoverflow.com/questions/37163579/null-pointer-exception-on-navigation-header-initialized-variables
navHeader=(RelativeLayout) LayoutInflater.from(this).inflate(R.layout.drawer_header, null);
navigationView.addHeaderView(navHeader); //This seems to add a SECOND "X" image
nameTV = (TextView) navHeader.findViewById(R.id.employeeFname);
lnameTV = (TextView) navHeader.findViewById(R.id.employeeLname);
closeDrawer = (ImageView) navHeader.findViewById(R.id.closedrawer);
profilePhoto = (ImageView) navHeader.findViewById(R.id.profilephoto);
businessesTV = (TextView) findViewById(R.id.businesses);
closeDrawer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
drawerLayout.closeDrawer(Gravity.LEFT);
}
});
///////////////////////////////////////////////////////////////////////////
//INFORMATION FOR MENU/////////////////////
//PROFILE PHOTO
//currentUser = FirebaseAuth.getInstance().getCurrentUser();
//currentUserString = currentUser.getUid().toString();
setupDrawerLayout();
database = FirebaseDatabase.getInstance();
employeesRefPhoto = database.getReference("Employees").child(currentUserString).child("photoDownloadUrl");
employeesRefPhoto.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.i("onDataChange","Inside");
try {
photoUrl = dataSnapshot.getValue().toString();
Log.i("photoUrl", photoUrl);
Glide.with(getApplicationContext()).load(photoUrl).into(profilePhoto);
profilePhoto.setScaleType(ImageView.ScaleType.CENTER_CROP);
}
catch (NullPointerException e) {
Log.i("Null", e.toString());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d("Cancelled",databaseError.toString());
}
});
//////////////////////////////////////////////
//GET NAME//////////////////////////////////
//FIRST NAME
employeesRefFname = database.getReference("Employees").child(currentUserString).child("firstName");
employeesRefFname.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
try {
Log.i("firstname", dataSnapshot.getValue().toString());
nameTV.setText(dataSnapshot.getValue().toString());
}
catch (Exception e) { Log.i("FNull?", e.toString()); }
}
#Override
public void onCancelled(DatabaseError databaseError) { Log.d("Cancelled",databaseError.toString()); }
});
//LAST NAME
employeesRefLname = database.getReference("Employees").child(currentUserString).child("lastName");
employeesRefLname.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
try {
Log.i("lastname", dataSnapshot.getValue().toString());
lnameTV.setText(dataSnapshot.getValue().toString());
}
catch (Exception e) { Log.i("LNull?", e.toString()); }
}
#Override
public void onCancelled(DatabaseError databaseError) { Log.d("Cancelled",databaseError.toString()); }
});
//footerOnClick();
footerOnClick();
} //END OF ONCREATE
/////////////////////////////////////////////////////////////////////////////////
//INITIALIZE VIEWS
private void initViews(){
navHeader=(RelativeLayout) LayoutInflater.from(this).inflate(R.layout.drawer_header, null);
nameTV = (TextView) navHeader.findViewById(R.id.employeeFname);
lnameTV = (TextView) navHeader.findViewById(R.id.employeeLname);
menu = (ImageView) findViewById(R.id.menu);
closeDrawer = (ImageView) navHeader.findViewById(R.id.closedrawer);
profilePhoto = (ImageView) navHeader.findViewById(R.id.profilephoto);
businessesTV = (TextView) findViewById(R.id.businesses);
}
//INTENTS FOR THE FOOTER OF THE SCREEN
private void footerOnClick() {
businessesTV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
startActivity(new Intent(HomeActivity.this, BusinessesActivity.class));
}
});
//EMPLOYEES
//PAYROLL REPORT
}
//MENU / DRAWER
//https://antonioleiva.com/navigation-view/
private void setupDrawerLayout() {
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
navigationView = (NavigationView) findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override public boolean onNavigationItemSelected(MenuItem menuItem) {
//If Clicked...then get item and go to associated page
switch(menuItem.getTitle().toString())
{
case "Profile":
Log.i("Profile", menuItem.getTitle().toString());
startActivity(new Intent(HomeActivity.this, ProfileActivity.class));
/*case "Share":
startActivity(new Intent(HomeActivity.this, ProfileActivity.class));
case "Settings":
startActivity(new Intent(HomeActivity.this, ProfileActivity.class)); */
case "Logout":
Log.i("Logout", menuItem.getTitle().toString());
FirebaseAuth.getInstance().signOut();
//startActivity(new Intent(HomeActivity.this, LoginActivity.class));
}
menuItem.setChecked(true);
drawerLayout.closeDrawers();
return true;
}
});
}
//??????????????????????????????????????
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
drawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
} //END OF CLASS

Inside setupDrawerLayout() under onNavigationItemSelected() you have a switch statement.
In each case of the switch statement use break else all the following switch conditions may execute. Since the last case is to logout, the user might be getting signed out each time the switch statement executes.

Related

Attempt to invoke virtual method: has an error java.lang.NullPointerException [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
I am getting the following error in my logcat
2020-03-21 16:58:54.611 20322-20322/com.example.bookitup E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.bookitup, PID: 20322
java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setLayoutManager(androidx.recyclerview.widget.RecyclerView$LayoutManager)' on a null object reference
at com.example.bookitup.RecyclerView_Config.setConfig(RecyclerView_Config.java:22)
at com.example.bookitup.MainActivity$2.DataIsLoaded(MainActivity.java:90)
at com.example.bookitup.BookDatabaseEdit$1.onDataChange(BookDatabaseEdit.java:40)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database##19.2.1:75)
at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database##19.2.1:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database##19.2.1:55)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
2020-03-21 16:58:54.622 2004-2019/? W/ActivityTaskManager: Force finishing activity com.example.bookitup/.MainActivity
2020-03-21 16:58:54.622 2004-20389/? I/DropBoxManagerService: add tag=data_app_crash isTagEnabled=true flags=0x2
And here is my code that is causing this NPE of RecyclerView_Config.
public class RecyclerView_Config {
private Context mContext;
private BooksAdapter mBooksAdapter;
public void setConfig(RecyclerView recyclerView, Context context, List<BookActivity> books, List<String> keys){
mContext = context;
mBooksAdapter = new BooksAdapter(books,keys);
recyclerView.setLayoutManager(new LinearLayoutManager(context));/*here!!!!!!!!!!!!!!!!!!!!!!!!!*/
recyclerView.setAdapter(mBooksAdapter);
}
class BookItemView extends RecyclerView.ViewHolder {
private TextView mTitle;
private TextView mAuthor;
private TextView mISBN;
private TextView mCategory;
private String key;
public BookItemView(ViewGroup parent){
super(LayoutInflater.from(mContext).inflate(R.layout.book_list_item,parent,false));
mTitle = (TextView) itemView.findViewById(R.id.title_txtView);
mAuthor = (TextView) itemView.findViewById(R.id.author_txtView);
mCategory = (TextView) itemView.findViewById(R.id.category_txtView);
mISBN = (TextView) itemView.findViewById(R.id.isbn_txtView);
}
public void bind(BookActivity book, String key){
mTitle.setText(book.getXbook());
mAuthor.setText(book.getXauthor());
mCategory.setText(book.getXdescription());
mISBN.setText(book.getXisbn());
this.key = key;
}
}
class BooksAdapter extends RecyclerView.Adapter<BookItemView>{
private List<BookActivity> mBookList;
private List<String> mKeys;
public BooksAdapter(List<BookActivity> mBookList, List<String> mKeys) {
this.mBookList = mBookList;
this.mKeys = mKeys;
}
#NonNull
#Override
public BookItemView onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new BookItemView((parent));
}
#Override
public void onBindViewHolder(#NonNull BookItemView holder, int position) {
holder.bind(mBookList.get(position), mKeys.get(position));
}
#Override
public int getItemCount() {
return mBookList.size();
}
}
}
Here is the code from my activity
public class MainActivity extends AppCompatActivity {
private AppBarConfiguration mAppBarConfiguration;
private RecyclerView mRecyclerView;
//private ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
setTheme(R.style.AppTheme_NoActionBar);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FirebaseUser user= FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
//setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
Toast.makeText(getApplicationContext(), "on the main page", Toast.LENGTH_LONG).show();
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Snackbar.make(view, "Adding new book, please wait!", Snackbar.LENGTH_LONG).setAction("Action", null).show();
Toast.makeText(getApplicationContext(), "Adding new book, please wait ", Toast.LENGTH_LONG).show();
//progressBar.setVisibility(View.GONE);
Intent intent = new Intent(MainActivity.this, AddBookActivity.class);
startActivity(intent);
}
});
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow,
R.id.nav_tools, R.id.nav_share, R.id.nav_send, R.id.nav_profile_edit)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
//piling all books on the main page
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview_books);
new BookDatabaseEdit().readBooks(new BookDatabaseEdit.DataStatus() {
#Override
public void DataIsLoaded(List<BookActivity> books, List<String> keys) {
new RecyclerView_Config().setConfig(mRecyclerView,MainActivity.this,books,keys);
}
#Override
public void DataIsInserted() {
}
#Override
public void DataIsUpdated() {
}
#Override
public void DataIsDeleted() {
}
});
}
else {
Intent intent = new Intent(MainActivity.this, RegistrationActivity.class);
startActivity(intent);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
// User chose the "Settings" item, show the app settings UI...
return true;
case R.id.action_logout:
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
FirebaseAuth.getInstance().signOut();
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(new Intent(intent));
return true;
default:
// If we got here, the user's action was not recognized.
// Invoke the superclass to handle it.
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
}
My BookDatabaseEdit.java
public class BookDatabaseEdit {
private FirebaseDatabase mDatabase;
private DatabaseReference mReferenceBooks;
private List<BookActivity> books = new ArrayList<>();
public interface DataStatus{
void DataIsLoaded(List<BookActivity> books, List<String> keys);
void DataIsInserted();
void DataIsUpdated();
void DataIsDeleted();
}
public BookDatabaseEdit() {
mDatabase = FirebaseDatabase.getInstance();
mReferenceBooks = mDatabase.getReference("Booklist");
}
public void readBooks(final DataStatus dataStatus){
mReferenceBooks.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange( DataSnapshot dataSnapshot) {
books.clear();
List<String> keys = new ArrayList<>();
for(DataSnapshot keyNode : dataSnapshot.getChildren()){
keys.add(keyNode.getKey());
BookActivity book = keyNode.getValue(BookActivity.class);
books.add(book);
}
dataStatus.DataIsLoaded(books,keys);
System.out.println(keys);
System.out.println(books);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
I think you should implement a getter and setter for Context and use getter to get context with a null check.
So, I fixed this error and my code is working now. The problem was with the RecyclerView_Config.java . The problem was that, basically, my program was trying to populate data from firebase into the app before creating the app.
It is fixed, thanks everyone.

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

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

i can't make a listener on my navigation drawer, can you tell me where do i wrong?

i create this drawer from empty activity so i don't use fragment
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
private FirebaseAuth.AuthStateListener authListener;
private FirebaseAuth auth;
private Button signOut;
private DrawerLayout nDrawer;
private ActionBarDrawerToggle nToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
when i put this setNavigaionViewListener, this activity will crash on build, do i wrong somewhere ?
//setNavigationViewListner();
//get firebase auth instance
auth = FirebaseAuth.getInstance();
and i don't know why but get current user don't work but i don't get where the error is.
//get current user
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
authListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user == null) {
// user auth state is changed - user is null
// launch login activity
startActivity(new Intent(MainActivity.this, LoginActivity.class));
finish();
}
}
};
signOut = (Button) findViewById(R.id.sign_out);
nDrawer = (DrawerLayout) findViewById(R.id.drawer);
nToggle = new ActionBarDrawerToggle(MainActivity.this,nDrawer,R.string.open,R.string.close);
nDrawer.addDrawerListener(nToggle);
nToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
signOut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signOut();
startActivity(new Intent(MainActivity.this, LoginActivity.class));
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (nToggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
//method to set Listener
private void setNavigationViewListner() {
NavigationView navigationView = (NavigationView) findViewById(R.id.drawer);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.account:{
startActivity(new Intent(MainActivity.this, ProfileActivity.class));
break;
}
case R.id.logout:{
signOut();
startActivity(new Intent(MainActivity.this, LoginActivity.class));
break;
}
}
nDrawer.closeDrawer(GravityCompat.START);
return true;
}
//sign out method
public void signOut() {
auth.signOut();
}
Use this
Toolbar toolbar = (Toolbar) findViewById(R.id.Yourtoolbar);
nToggle = new ActionBarDrawerToggle(
MainActivity.this, nDrawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
instead of this
nToggle = new ActionBarDrawerToggle(MainActivity.this,nDrawer,R.string.open,R.string.close);
and also change this remove DrawerLayout findViewById(R.id.drawer) and put Your NavigationView ID
EXample findViewById(R.id.YournavigationView);
NavigationView navigationView = (NavigationView) findViewById(R.id.YournavigationView);

Application crashes when SetContentView set back to main activity

When I set content view on another layout its works perfectly, but when I set content view back to main layout its crashes.
My Main class and everything on it. Everything happens in public void firstTime().
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private MapFragment mapsFragment;
static MainActivity can;
static FloatingActionButton fab;
static FloatingActionButton show;
private String encoded_string;
private Bitmap bitmap;
private String picturePath;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
private void initializeMapsFragment() {
FragmentTransaction mTransaction = getSupportFragmentManager().beginTransaction();
mapsFragment = new MapFragment();
SupportMapFragment supportMapFragment = mapsFragment;
mTransaction.add(R.id.map, supportMapFragment);
mTransaction.commit();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("--***** MAP ", "::Loading Map");
can = this;
setContentView(R.layout.activity_main);
initializeMapsFragment();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
fab = (FloatingActionButton) findViewById(R.id.fab);
show = (FloatingActionButton) findViewById(R.id.show);
show.hide();
fab.hide();
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
callPopup();
}
});
show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
stats();
}
});
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.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
Button searchButton = (Button) findViewById(R.id.searchButton);
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText searchView = (EditText) findViewById(R.id.searchView1);
String text = searchView.getText().toString();
Geocoder geocoder = new Geocoder(getBaseContext());
List<Address> addresses = null;
try {
// Getting a maximum of 3 Address that matches the input
// text
addresses = geocoder.getFromLocationName(text, 3);
if (addresses != null && !addresses.equals(""))
search(addresses);
} catch (Exception e) {
}
}
});
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
protected void search(List<Address> addresses) {
Address address = (Address) addresses.get(0);
LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
MapFragment.mapView.moveCamera(CameraUpdateFactory.newLatLng(latLng));
MapFragment.mapView.animateCamera(CameraUpdateFactory.zoomTo(15));
}
#Override
public void onBackPressed() {
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) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#RequiresApi(api = Build.VERSION_CODES.HONEYCOMB)
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
FragmentManager fm = getFragmentManager();
android.support.v4.app.FragmentManager sFm = getSupportFragmentManager();
int id = item.getItemId();
if (id == R.id.nav_camera) {
if (!mapsFragment.isAdded())
sFm.beginTransaction().add(R.id.map, mapsFragment).commit();
else
sFm.beginTransaction().show(mapsFragment).commit();
} else if (id == R.id.nav_share) {
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = "Check this app out --> link.kys";
sharingIntent.putExtra(Intent.EXTRA_SUBJECT, "Best Free Parking app");
sharingIntent.putExtra(Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share via"));
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void firstTime() {
setContentView(R.layout.firsttime);
(findViewById(R.id.cancelBut))
.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
setContentView(R.layout.activity_main);
}
});
}
public static void load(){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(can);
if (!prefs.getBoolean("firstTime", false)) {
can.firstTime();
//SharedPreferences.Editor editor = prefs.edit();
//editor.putBoolean("firstTime", true);
//editor.commit();
}
}
private void stats() {
setContentView(R.layout.stats);
RatingBar ratingbar = (RatingBar) findViewById(R.id.ratingBar);
ratingbar.setRating((float) 2.0);
ratingbar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromUser) {
ratingBar.setRating((float) 2.0);
}
});
((Button) findViewById(R.id.cancBut)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setContentView(R.layout.content_main);
}
});
}
private void callPopup() {
final PopupWindow popupWindow;
LayoutInflater layoutInflater = (LayoutInflater) getBaseContext()
.getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.popup, null);
popupWindow = new PopupWindow(popupView,
DrawerLayout.LayoutParams.WRAP_CONTENT, DrawerLayout.LayoutParams.MATCH_PARENT,
true);
popupWindow.setTouchable(true);
popupWindow.setFocusable(true);
popupWindow.showAtLocation(popupView, Gravity.CENTER, 0, 0);
final EditText name = (EditText) popupView.findViewById(R.id.edtimageName);
((Button) popupView.findViewById(R.id.plcBut)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectPhoto();
}
});
((Button) popupView.findViewById(R.id.saveBtn))
.setOnClickListener(new View.OnClickListener() {
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
public void onClick(View arg0) {
new Encode_image().execute();
popupWindow.dismiss();
}
});
((Button) popupView.findViewById(R.id.cancelbtutton))
.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
popupWindow.dismiss();
}
});
}
private void selectPhoto() {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 10);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 10 && resultCode == RESULT_OK) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
cursor.close();
}
}
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
public Action getIndexApiAction() {
Thing object = new Thing.Builder()
.setName("Main Page") // TODO: Define a title for the content shown.
// TODO: Make sure this auto-generated URL is correct.
.setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
.build();
return new Action.Builder(Action.TYPE_VIEW)
.setObject(object)
.setActionStatus(Action.STATUS_TYPE_COMPLETED)
.build();
}
#Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
AppIndex.AppIndexApi.start(client, getIndexApiAction());
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
AppIndex.AppIndexApi.end(client, getIndexApiAction());
client.disconnect();
}
private class Encode_image extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
bitmap = BitmapFactory.decodeFile(picturePath);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
bitmap.recycle();
byte[] array = stream.toByteArray();
encoded_string = Base64.encodeToString(array, 0);
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
makeRequest();
}
}
private void makeRequest() {
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest request = new StringRequest(Request.Method.POST, "http://185.80.129.86/upload.php",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> map = new HashMap<>();
map.put("encoded_string", encoded_string);
map.put("image_name", "testing123.jpg");
return map;
}
};
requestQueue.add(request);
}
}
Error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.robertas.parking.bestfreeparking, PID: 3501
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
at android.view.ViewGroup.addViewInner(ViewGroup.java:3936)
at android.view.ViewGroup.addView(ViewGroup.java:3786)
at android.view.ViewGroup.addView(ViewGroup.java:3758)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:810)
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:916)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:802)
at android.view.LayoutInflater.parseInclude(LayoutInflater.java:916)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:802)
at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:284)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:143)
at com.robertas.parking.bestfreeparking.MainActivity$4.onClick(MainActivity.java:245)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Make changes this
Log.d("--***** MAP ", "::Loading Map");
can = this;
setContentView(R.layout.activity_main);
initializeMapsFragment();

Categories

Resources