用户在Firebase中不存在?

时间:2019-07-07 13:49:14

标签: android firebase firebase-realtime-database

当我输入数据库中已经存在的用户名和用户名时,我对firebase进行了身份验证,然后它成功登录,但是当我输入的不是我的firebase错误密码时,则apk崩溃

private DatabaseReference ref;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        userID = (EditText) findViewById(R.id.Username);
        ref = FirebaseDatabase.getInstance().getReference().child("muhamadgamerstrings");
    }

     public void btnlogin_Click(View view) {
        final String usrID = userID.getText().toString();

         try {
        ref.child(usrID).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                muhamadgamerstrings Userr = dataSnapshot.getValue(muhamadgamerstrings.class);
                if(usrID.equals(Userr.getUserID()))
                {
                    Toast.makeText(MainActivity.this,
                            "login Succesful",Toast.LENGTH_SHORT).show();
                    Intent start = new Intent(MainActivity.this,start.class);
                    startActivity(start);
                }else {
                    Toast.makeText(MainActivity.this,
                            "Wrong Key",Toast.LENGTH_SHORT).show();
                }

            }
     @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
        }catch (Exception xe){
            Toast.makeText(MainActivity.this,
                    "login false",Toast.LENGTH_SHORT).show();
        }

    }

}

`
    That is my mainactivity
The error is from logcat shows here
    if(usrID.equals(Userr.getUserID()))`  java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.yuhamadgamer.loginwithfire.muhamadgamerstrings.getUserID()' on a null object reference`

1 个答案:

答案 0 :(得分:0)

Firebase实时数据库 muhamadgamerstrings 中的值为空。

因为

  

当我键入错误的密钥不是我的Firebase时,则apk   崩溃

当您键入不在数据库中的ID时,数据库将发送一个空快照。这就是 NullPointerException 的原因。

因此您需要在操作前将其检查为空

public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                muhamadgamerstrings Userr = dataSnapshot.getValue(muhamadgamerstrings.class);
                if(Userr != null && usrID.equals(Userr.getUserID()))
                {
                    Toast.makeText(MainActivity.this,
                            "login Succesful",Toast.LENGTH_SHORT).show();
                    Intent start = new Intent(MainActivity.this,start.class);
                    startActivity(start);
                }else {
                    Toast.makeText(MainActivity.this,
                            "Wrong Key",Toast.LENGTH_SHORT).show();
                }

            }