我有一个关于字符串中的nullPointerException
的问题。我已经尝试了所有可能的解决方案,但没有任何效果。这是代码:
reference = FirebaseDatabase.getInstance().getReference("Users").child(userid);
reference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
final String type = dataSnapshot.child("status").child("userstate").getValue().toString();
final String Date = dataSnapshot.child("status").child("date").getValue().toString();
final String Time = dataSnapshot.child("status").child("time").getValue().toString();
User user = dataSnapshot.getValue(User.class);
username.setText(user.getUsername());
if(user != null) {
if (user.getImageURL().equals("default")) {
profile_image.setImageResource(R.mipmap.ic_launcher);
} else {
Glide.with(getApplicationContext()).load(user.getImageURL()).into(profile_image);
}
}
readMessages(firebaseUser.getUid(), userid, user.getImageURL());
if (type != null) {
if (type.equals("online")) {
userStatus.setText("online");
} else {
userStatus.setText("last seen: " + Time + " " + Date);
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
这是Logcat:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
at com.androidcoding.messenger.MessageActivity$3.onDataChange(MessageActivity.java:120)
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:754)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:163)
at android.app.ActivityThread.main(ActivityThread.java:6238)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:933)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
最后我使用了 type != null
但它仍然使应用程序崩溃。哪里有问题?我再次询问了一些有关 NullPointerException 的问题,但我无法理解如何在每种情况下解决它......
最佳答案
这里的问题是因为您将 null
转换为 String
。
只需删除.toString()
final String type = dataSnapshot.child("status").child("userstate").getValue();
现在您的类型可能为 null
,因此您可以使用 null
检查它。
关于java - 字符串中的 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61363340/