嗨,朋友们,我正在从Firebase获取值并将其保存到edittext(已完成)。但是我要检查是否存在firebase值,而不是将其放在edittext上,否则要从用户在同一edittext上输入,因为我将此值发送到另一个活动,并且如果firebase中没有值,则会出现null值的错误>
我正在尝试的代码是
String str= etext.getText().toString();
if(str.equals("")) {
final FirebaseDatabase database = FirebaseDatabase.getInstance();
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String userId = user.getUid();
DatabaseReference dbref = FirebaseDatabase.getInstance().getReference("Users/Clients").child(userId);
dbref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
Paper.book().write(Common.channel, etext.getText().toString());
names = dataSnapshot.child("channel_id").getValue().toString();
// Toast.makeText(getBaseContext(),names,Toast.LENGTH_LONG).show();
etext.setText(names);
SharedPreferences settings = getSharedPreferences("userInput", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("username", names);
editor.commit();
Intent i = new Intent(Men.this, Main2Activity.class);
startActivity(i);
finish();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
答案 0 :(得分:1)
尝试以下
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChild("channel_id") && dataSnapshot.child("channel_id").getValue() != null) {
names = dataSnapshot.child("channel_id").getValue().toString();
Paper.book().write(Common.channel, names);
etext.setText(names);
SharedPreferences settings = getSharedPreferences("userInput", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("username", names);
editor.commit();
Intent i = new Intent(Men.this, Main2Activity.class);
startActivity(i);
finish();
}
}