我从Firebase实时数据库检索数据,然后将其存储到列表中,以便显示数据。
我的问题是,显示的数据没有显示其属性的存储对象,而是所谓的名称/标签或类似的东西。
显示的内容:
com.example.husiapp2.Homework@1abbfc6
应显示的内容(带有属性的对象):
Homework
-Title,
-Class
我的代码:
public class Homework {
public String Title;
public String Class;
public String ExpireDate;
public Homework(){}
public Homework(String title, String aClass,String expireDate) {
Title = title;
Class = aClass;
ExpireDate = expireDate;
}
}
DatabaseReference ref;
Homework homework;
final List<Homework> hw = new ArrayList<>();
ListView hwlist;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_hw);
Log.d("HWAC122",hw.toString());
hwlist = findViewById(R.id.hwlist);
ref = FirebaseDatabase.getInstance().getReference("User").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("Homework");
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot ds:dataSnapshot.getChildren()){
homework = new Homework();
homework.Title = ds.getValue(Homework.class).Title;
homework.Class = ds.getValue(Homework.class).Class;
homework.ExpireDate = ds.getValue(Homework.class).ExpireDate;
Log.d("test123",homework.toString());
hw.add(homework);
}
SetAdapter();
}
});
}
public void SetAdapter(){
ArrayAdapter adapter = new ArrayAdapter<Homework>(this,android.R.layout.simple_list_item_1,hw);
hwlist.setAdapter(adapter);
}
答案 0 :(得分:2)
com.example.husiapp2.Homework@1abbfc6
是不覆盖toString()
的对象的标准字符串格式。它由对象的类及其在JVM内存中的位置组成。如果要toString()
生成其他内容,则必须覆盖它并使它返回要打印的内容。
public class Homework {
public String Title;
public String Class;
public String ExpireDate;
public Homework(){}
public Homework(String title, String aClass,String expireDate) {
Title = title;
Class = aClass;
ExpireDate = expireDate;
}
// Override toString
@Override
public String toString() {
return "Whatever you want it to be";
}
}
并非总是最好覆盖toString()
。很多时候,最好编写其他函数,将其传递给对象,然后让其返回格式化的字符串。无论哪种方式,您都必须编写生成字符串的代码。
答案 1 :(得分:0)
在您创建的java类中实现getter和setter方法。按alt + insert,然后为所有已声明的变量选择实现getter和setter。通过此操作,您可以将数据插入Firebase并从Firebase检索数据