我使用Firebase在数据库中保存一些用户控件文本。我通常会得到一个nullpointer异常,因为最初没有触发onDataChange。 (我使用ValueEventListener)
我该如何解决这个问题?
这里是电话:
sharedPref = FirebaseDatabase.getInstance().getReference().child("abc").child("ddd");
ValueEventListener clubSettingsListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
firebaseClubSettingsModel = dataSnapshot.getValue(FirebaseClubSettingsModel.class);
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.w("ClubSettingsService", "loadPost:onCancelled", databaseError.toException());
}
};
sharedPref.addValueEventListener(clubSettingsListener);
if (firebaseClubSettingsModel == null) {
firebaseClubSettingsModel = new FirebaseClubSettingsModel();
//sharedPref.setValue(firebaseClubSettingsModel);
}
答案 0 :(得分:2)
您无法在onDataChange事件之外操作数据,因为从firebase获取数据是一个异步过程,因此无法保证在检查其值时将结束调用。
您必须在onDataChange
侦听器中进行验证和其他逻辑,因为只要数据可用就会触发它。
sharedPref = FirebaseDatabase.getInstance().getReference().child("abc").child("ddd");
ValueEventListener clubSettingsListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
firebaseClubSettingsModel = dataSnapshot.getValue(FirebaseClubSettingsModel.class);
if (firebaseClubSettingsModel == null) {
firebaseClubSettingsModel = new FirebaseClubSettingsModel();
sharedPref.setValue(firebaseClubSettingsModel);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.w("ClubSettingsService", "loadPost:onCancelled", databaseError.toException());
}
};
sharedPref.addValueEventListener(clubSettingsListener);