1

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;





        }
    }
}
Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
Jagdeesh
  • 119
  • 2
  • 14

2 Answers2

4

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
}
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • Caused by: java.lang.NullPointerException: Can't pass null for argument 'pathString' in child() at com.google.firebase.database.DatabaseReference.child(Unknown Source) at com.example.akhilkumar.chitchat.MainActivity.onCreate(MainActivity.java:87) – Jagdeesh Jul 16 '18 at 16:48
  • error pointing to userRef.child(currentUserID).addValueEventListener(new ValueEventListener() { – Jagdeesh Jul 16 '18 at 16:51
  • If you are getting another error, it means the initial problem was solved. As a personal hint, your `currentUserID` object is null but this is basically another question. In order to follow the rules of this comunity, please post another fresh question, so me and other users can help you. – Alex Mamo Jul 16 '18 at 16:58
2

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();
    }
}
Raj
  • 2,997
  • 2
  • 12
  • 30