gpt4 book ai didi

java - firebase检索值不正确

转载 作者:太空宇宙 更新时间:2023-11-04 10:09:08 24 4
gpt4 key购买 nike

我在 Firebase 中检索值时遇到问题。我添加了一个 TextView 来查看数据快照内的值,并且我正确地看到了它,但是当我将其添加到我的 ListView 中时,它看起来像这样。顺便说一句,我的 ListView 是绿色的。

enter image description here

在我的 TextView 中,该值是正确的,但在我的 ListView 中它是这样的。这是我用于检索值的代码。

 FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference();
ref.child("Sold").child("Item").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
try {
Iterable<DataSnapshot> children = dataSnapshot.getChildren();
//textView.setText(dataSnapshot.getValue().toString());
for (DataSnapshot child : children) {
Product value = child.getValue(Product.class);
products.add(value);
textView.setText(value.getDescription() + " - " + child.getValue());
}
productAdapter.notifyDataSetChanged();

}catch (Exception e)
{

textView.setText(e.getMessage());
}
}

productAdapter = new ArrayAdapter<Product>(getApplicationContext(),
android.R.layout.simple_list_item_1, products);
listViewProducts.setAdapter(productAdapter);

这是我的产品类别

class Product {
private String Description;
private int Qty;

public String getDescription() {
return Description;
}

public void setDescription(String description) {
Description = description;
}

public int getQty() {
return Qty;
}

public void setQty(int qty) {
Qty = qty;
}

public Product(String description, int qty) {

Description = description;
Qty = qty;
}

public Product(){}

}

最佳答案

您在 LisView 中得到的基本上是 Product 对象的字符串表示形式。所以下面的字符串:

 com.example.mark.mobilethesis.Product@e8e0966

实际上代表内存中Product对象的地址,这当然不是你想要的。要显示数据、描述数量,您有三个选择。

第一个也是最简单的一个是重写 Product 类中的 toString() 方法,正如其他用户所建议的那样。这应该看起来像这样:

@Override
public String toString() {
return description + " / " + qty;
}

第二个选项是将列表类型从 Product 更改为 String,如下所示:

for (DataSnapshot child : children) {
List<String> products = new ArrayList<>();
Product value = child.getValue(Product.class);
products.add(value.getDescription() + " / " + child.getValue());
}

ArrayAdapter<String> productAdapter = new ArrayAdapter<String>(
getApplicationContext(),
android.R.layout.simple_list_item_1,
products
);
listViewProducts.setAdapter(productAdapter);

第三个是创建自定义适配器。因此,即使您将整个 Product 对象传递给适配器,您也只能获取适配器内的 descriptionqty

关于java - firebase检索值不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52549000/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com