【发布时间】:2023-04-03 01:39:01
【问题描述】:
这是我的代码:
public class ChatActivity extends AppCompatActivity {
private String titleString, userID, uploadID, imageURL, userOnlineString;
private Boolean userOnlineBoolean;
private int imageRotation;
private TextView titleCustomBar, lastSeenCustomBar;
private ImageView imageCustomBar;
private DatabaseReference mDatabaseRefUser;
private FirebaseAuth mAuth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
mAuth = FirebaseAuth.getInstance();
mDatabaseRefUser = FirebaseDatabase.getInstance().getReference("Users");
//Log.e("Lol", userOnlineString);
mDatabaseRefUser.child(mAuth.getCurrentUser().getUid()).child("Online").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
userOnlineBoolean = dataSnapshot.getValue(Boolean.class);
Log.e("lol ", ""+userOnlineBoolean);
}
@Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(ChatActivity.this, "some error", Toast.LENGTH_SHORT).show();
}
});
Intent intent = getIntent();
titleString = intent.getStringExtra("TITLE");
userID = intent.getStringExtra("USERID");
uploadID = intent.getStringExtra("UPLOADID");
imageRotation = intent.getIntExtra("IMAGEROTATION", 0);
imageURL = intent.getStringExtra("IMAGEURL");
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowCustomEnabled(true);
LayoutInflater layoutInflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
View customActionBar = layoutInflater.inflate(R.layout.chat_custombar, null);
actionBar.setCustomView(customActionBar);
titleCustomBar = findViewById(R.id.title_textview_id);
lastSeenCustomBar = findViewById(R.id.last_seen_textview_id);
imageCustomBar = findViewById(R.id.custom_image_id);
titleCustomBar.setText(titleString);
//getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Glide.with(this).load(imageURL)
.into(imageCustomBar);
imageCustomBar.setRotation(imageRotation);
if(userOnlineBoolean){
userOnlineString = "Online";
}
lastSeenCustomBar.setText(userOnlineString);
}
@Override
protected void onStart() {
super.onStart();
if(mAuth.getCurrentUser() == null){
Intent mainActivityIntent = new Intent(this, MainActivity.class);
startActivity(mainActivityIntent);
finish();
}
else {
mDatabaseRefUser.child(mAuth.getCurrentUser().getUid()).child("Online").setValue(true);
}
}
}
在日志中,userOnlineBoolean 正在返回 true。再往下,if-statement中的userOnlineBoolean为null,这是为什么呢?
我尝试了很多更改,但没有任何效果。为什么返回true后为null。
我已经尝试解决这个问题几个小时,但我没有找到问题,或者没有看到问题。如果您知道我的代码有什么问题,请随时与您分享。
【问题讨论】:
-
只是一个快速的猜测,您在匿名侦听器中打印变量,该侦听器通常以异步方式执行。可能是 if 子句中的代码被调用 before 它被记录在
onDataChange方法中?此外,您看到日志输出的时间可能比实际发生的时间要晚很多。 -
我该如何解决这个问题?
-
我已经发布了答案
标签: java nullpointerexception boolean