android – Firebase null object reference "long java.lang.Long.longValue()"-ThrowExceptions

Exception or error:

I’m creating an app that has different user levels (e.g admin, general user). Depending on the level of the user, a different activity will be launched. 1 is admin and 2 is a general user. The AdminMenuActivity launches by the MenuActivity won’t.
The error I’m getting is as follows.

java.lang.NullPointerException: Attempt to invoke virtual method 'long java.lang.Long.longValue()' on a null object reference at com.example.login.MainActivity$1.onDataChange(MainActivity.java:63)

I’ve been working on this for the past few days and I can’t solve the problem. The code and database are as follows.

Code

public void selectUser(){

    String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
    DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
    DatabaseReference uidRef = rootRef.child("Users").child(uid);
    ValueEventListener valueEventListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {


                if (dataSnapshot.child("role").getValue(Long.class) == 1) {
                    startActivity(new Intent(MainActivity.this , AdminMenuActivity.class));
                }
                else if (dataSnapshot.child("role").getValue(Long.class) == 2) {
                    startActivity(new Intent(MainActivity.this , MenuActivity.class));
                }



        }


        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            throw databaseError.toException();


        }
    };
    uidRef.addListenerForSingleValueEvent(valueEventListener);

}

Updated Database

{     "Users" : {
    "H7BKqKwLGTP0qTlL1p2JqFezjWu2" : {
      "email" : "hello@hotmail.com",
      "preference" : "rugby",
      "role" : 2
    },
    "WSBNdlu7ngbyMo2jILR2qE1ZUR32" : {
      "email" : "1234@gmail.com",
      "preference" : "rugby",
      "role" : 1
    }
  },
  "roles" : {
    "uid1" : "admin",
    "uid2" : "general"
  }
}
How to solve:

getValue(Long.class) is returning null, which means there is no data at the location of the database that you’re looking for. You’re going to have to check for this case and decide what to do when your query doesn’t find what you’re looking for.

Leave a Reply

Your email address will not be published. Required fields are marked *