我在Firebase中存储了以下数据:
id(document id)
- carName: BMW
- carModel: 318
- carProductionYear: 2011
- carFuel: petrol
- carColor: white
- ...
在应用程序中的某个时候,我只想显示一定数量的数据。这就是为什么我要准备这个课:
class CarBasic{
private String carName;
private String carModel;
private String carFuel;
}
但是在键入此代码时,会出现一条消息:“更改Carbasic的签名”
carsRef.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if(task.isSuccessful()){
List<CarBasic> list = new ArrayList<>();
for(QueryDocumentSnapshot document : task.getResult()){
list.add(new CarBasic(document.get("carName"),document.get("carModel"),document.get("carFuel")));
}
} else {
Toast.makeText(CarBasicInfoActivity.this, "Error while loading the data", Toast.LENGTH_SHORT).show();
}
}
});
我想要实现的是仅采用此类对象(CarBasic),并将其作为源传递给RecyclerView。但是,如何在Firebase和我的实际对象之间进行解析?
已编辑
错误消息:
Required type Provided
carName: String Object
carModel: String Object
carFuel: Stirng Object
答案 0 :(得分:1)
我知道了。因此,基本上,Firebase会将文档数据解析为我们提供的任何类,只要该类的属性与文档的键匹配即可。 (我虽然该类必须始终匹配所有文档属性,但这不是必需的)
在我的情况下,该类是CarBasic(简单的POJO),并以这种方式定义:
class CarBasic{
private String carName;
private String carModel;
private String carFuel;
//Empty constructor
//Constructor with all attributes
//Getters
}
在我的具体示例中,典型的文档键值对:
id(document id)
- carName: BMW
- carModel: 318
- carProductionYear: 2011
- carFuel: petrol
- carColor: white
- carKm: 198000
- carMotor: 2.0
- carType: convertible
- carDoorsNumber: 5
所以对我的收藏的引用是:
CollectionReference carsRef = FirebaseFireStore.getInstance().collection("vehicles").document(user.getUid()).collection("availableCars");
(user.getUid()来自Auth部分。将其替换为您想要的任何名称)
并初始化RecyclerView如下:
Query query = carsRef.orderBy("carName", Query.Direction.DESCENDING);
FirestoreRecyclerOptions<CarBasic> options = new FirestoreRecyclerOptions.Builder<CarBasic>()
.setQuery(query,CarBasic.class)
.build();
CarsAdapter carsAdapter = new CarsAdapter(options);
RecyclerView recyclerViewCars = findViewById(R.id.carsRecyclerView);
recyclerViewCars.setHasFixedSize(true);
recyclerViewCars.setLayoutManager(new LinearLayoutManager(this));
recyclerViewCars.setAdapter(carsAdapter);
希望,这对在将特定文档字段传递给RecyclerView
时遇到问题的所有人有所帮助。