In my app the user should be able to choose from 3 different categories (out of 8) which are randomly generated. For this I used the approach described here.
I don't know how to use this approach to use the retrieved documents to insert them into the TextViews in my Category Activity. I created a category class to store the retrieved documents from Firestore but I also don't know if that is even the right approach. I would very much appreciate every tip!
Here is my Category Activity where the 3 documents get retrieved and in the end should be displayed in the TextViews:
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_category_selection, container, false);
tvCategory1 = view.findViewById(R.id.text_view_category_1);
tvCategory2 = view.findViewById(R.id.text_view_category_2);
tvCategory3 = view.findViewById(R.id.text_view_category_3);
textViewCategoryRound = view.findViewById(R.id.text_view_category_round);
imageCategory1 = view.findViewById(R.id.image_category_1);
imageCategory2 = view.findViewById(R.id.image_category_2);
imageCategory3 = view.findViewById(R.id.image_category_3);
categoryCollectionRef.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
List<Category> categoryList = new ArrayList<>();
for (DocumentSnapshot document : task.getResult()) {
Category category = document.toObject(Category.class);
categoryList.add(category);
}
int categoryListSize = categoryList.size();
List<Category> randomCategoryList = new ArrayList<>();
for (int i = 0; i < categoryListSize; i++) {
Category randomCategory = categoryList.get(new Random().nextInt(categoryListSize));
if (!randomCategoryList.contains(randomCategory)) {
randomCategoryList.add(randomCategory);
if (randomCategoryList.size() == 3) {
break;
}
} else {
Log.d(TAG, "Error getting documents: ", task.getException());
}
}
}
}
});
return view;
}
}
Here is the category class where I hope I store the documents correctly:
public class Category {
public String category_name;
public String picture_id;
public Category (){
}
public String getPicture_id() {
return picture_id;
}
public void setPicture_id(String picture_id) {
this.picture_id = picture_id;
}
public String getCategory_name() {
return category_name;
}
public void setCategory_name(String category_name) {
this.category_name = category_name;
}
public Category(String category_name){
this.category_name = category_name;
}
}
Here is the way I structured my Category collection (there are 8 documents/categories):