我在Firebase数据库中有一个节点想要检索并将其放入微调器中,我制作了数组列表,然后遍历了数据快照,但仍然给出nullPointerException我使用push方法将子级的值存储在Firebase中
我尝试了一切,但是没有用
模型类
public class Purpose {
private String name;
public Purpose(){
}
public Purpose(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
添加数据类
puposedRef = FirebaseDatabase.getInstance().getReference().child("Purposes");
saveBtn = findViewById(R.id.add_purpose_save_btn);
saveBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String name = addNameEd.getText().toString();
Map<String , String> purposeMap = new HashMap<>();
purposeMap.put("name" , name);
puposedRef.push().setValue(purposeMap).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(AddPurposeActivity.this, "Added to database", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(AddPurposeActivity.this,
task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
});
检索课程
puposedRef = FirebaseDatabase.getInstance().getReference().child("Purposes");
textView = findViewById(R.id.show_purpose);
puposedRef.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
for(DataSnapshot ds : dataSnapshot.getChildren()){
String key = puposedRef.push().getKey();
String name = ds.child(key).getValue(Purpose.class).getName();
textView.setText(name);
}
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
for(DataSnapshot ds : dataSnapshot.getChildren()){
String key = puposedRef.push().getKey();
String name = ds.child(key).getValue(Purpose.class).getName();
textView.setText(name);
}
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
logcat
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.best.karem.mycareassociatesadmin.Model.Purpose.getName()' on a null object reference
at com.best.karem.mycareassociatesadmin.AddPurposeActivity$1.onChildAdded(AddPurposeActivity.java:52)
答案 0 :(得分:0)
您要在ChildEventListener
上附加一个Purposes
。这意味着将使用onChildAdded
的子节点的onChildChanged
调用其回调方法(DataSnapshot
,Purposes
等)。
在您的onChildAdded
中,您正在循环访问该快照的子节点,这意味着ds
是单个属性name
的快照。
要解决此问题,请不要在onChild*
方法中循环遍历子节点:
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildKey) {
String name = dataSnapshot.getValue(Purpose.class).getName();
textView.setText(name);
}