【发布时间】:2020-04-22 10:53:02
【问题描述】:
我对 Strings 中的 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 的问题,但我不明白在每种情况下如何解决它......
【问题讨论】:
标签: java android nullpointerexception