There is a problem with the list inside the “if” it doesn’t work I get an error this:java.lang.ClassCastException: java.lang.String cannot be cast to java.util.List
private FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
private DocumentReference productSearchRef = rootRef.collection("products").document("qQIJ9oGjlwwqNObfVV6U");
private CollectionReference productsRef = rootRef.collection("products");
MutableLiveData<List<String>> getProductNameListMutableLiveData() {
MutableLiveData<List<String>> productNameListMutableLiveData = new MutableLiveData<>();
productSearchRef.get().addOnCompleteListener(productNameListTask -> {
if (productNameListTask.isSuccessful()) {
DocumentSnapshot document = productNameListTask.getResult();
if (document.exists()) {
List<String> productNameList = (List<String>) document.get("name");
productNameListMutableLiveData.setValue(productNameList);
}
} else {
Log.d(Constants.TAG, productNameListTask.getException().getMessage());
}
});
return productNameListMutableLiveData;
}
Advertisement
Answer
You are getting the following error:
java.lang.ClassCastException: java.lang.String cannot be cast to java.util.List”
In the second if statement, because the type of the “name” field in the database is String and not a List, hence that error. There is no way in Java in which you can convert a String into a List. To solve this, you should get the value of the “name” field according to its data type. So please change the following line of code:
List<String> productNameList = (List<String>) document.get("name");
Into:
String productNameList = document.getString("name");
So something like this will do the trick:
private FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
private DocumentReference productSearchRef = rootRef.collection("products").document("qQIJ9oGjlwwqNObfVV6U");
private CollectionReference productsRef = rootRef.collection("products");
MutableLiveData<List<String>> getProductNameListMutableLiveData() {
MutableLiveData<List<String>> productNameListMutableLiveData = new MutableLiveData<>();
productsRef.get().addOnCompleteListener(productNameListTask -> {
if (productNameListTask.isSuccessful()) {
DocumentSnapshot snapshot = productNameListTask.getResult();
for (QueryDocumentSnapshot document : snapshot) {
if (document.exists()) {
String name = document.getString("name");
productNameList.add(name);
}
}
productNameListMutableLiveData.setValue(productNameList);
} else {
Log.d(Constants.TAG, productNameListTask.getException().getMessage());
}
});
return productNameListMutableLiveData;