我创建了一个RecyclerView,其中使用标准模型和适配器方法在本地加载数据,RecyclerView回收的视图包含图像和3个文本视图。我想使用Firebase数据库中的数据填充这些视图。我在Firebase上创建了数据,如下所示:
if(isset($_POST['username'])){
我已经添加了依赖项并让Firebase Auth设置并正常运行。用户永远不会更改数据,但可能会在后端手动更改数据。图像是单个白色png,颜色根据颜色值而改变。
我所看到的一切看起来都非常复杂,我确信它不需要,但不能减少我将这些数据输入RecyclerView所需的内容。
任何指针?感谢。
编辑 - 已从数据中删除所有特殊字符。
ItemAdapter
{
"items" : {
"item 1" : {
"colour-value" : "000000",
"manufacturer" : "Manufacturer 1",
"name" : "Name 1",
"type" : "Type 1"
},
"item 2" : {
"colour-value" : "ffff00",
"manufacturer" : "Manufacturer 2",
"name" : "Name 2",
"type" : "Type 2"
},
"item 3" : {
"colour-value" : "ff0000",
"manufacturer" : "Manufacturer 3",
"name" : "Name 3",
"type" : "Type 3"
}
}
}
}
答案 0 :(得分:0)
你的JSON中的第一个问题是,你的密钥中没有连字符或空格,因为firebase将根据POJO成员变量和java的键进行映射,不允许在namings中使用特殊字符。 因此,如果您更改密钥,请执行此操作 制作POJO
public class SampleModel {
private int colorValue;
private String manufacturer;
private String name;
private String type;
public int getColorValue() {
return colorValue;
}
public void setColorValue(int colorValue) {
this.colorValue = colorValue;
}
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
然后创建数据库引用并获取数据并更新列表
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DatabaseReference myRef = FirebaseDatabase.getInstance().getReference("items");
myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
//you have data now traverse
for (DataSnapshot child: dataSnapshot.getChildren()){
//your data may come up in map so handle here
HashMap<String,SampleModel> hashMap = (HashMap<String,SampleModel>)child.getValue();
//if everything is okay then just iterate over the map and create a list
List<SampleModel> sampleModels = new ArrayList<>()
for (HashMap.Entry<String,SampleModel> modelEntry:hashMap.entrySet()){
sampleModels.add(modelEntry.getValue());
}
mainList.addAll(sampleModels);
adapter.notifyDataSetChanged();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
//for some reason data did't show up
}
});
编辑:已添加
HashMap<String,SampleModel> hashMap = (HashMap<String,SampleModel>)child.getValue();