如何从Firestore获取随机文档并在不同的TextView中显示它们?

huangapple go评论80阅读模式
英文:

How to get random documents from Firestore and display them in different TextViews?

问题

你的应用程序中,用户应该能够从8个选项中随机选择3个不同的类别。你已经采用了这里描述的方法。但是,你不知道如何使用这个方法来将检索到的文档插入到Category Activity中的TextView中。你创建了一个Category类来存储从Firestore检索到的文档,但你也不确定这是否是正确的方法。你会很感激任何提示!

以下是你的Category Activity,其中3个文档被检索出来,最终应该显示在TextView中:

@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) {
                            // 这里你可以将数据插入到TextView中
                            // 例如:tvCategory1.setText(randomCategoryList.get(0).getCategory_name());
                            // 然后继续设置其他TextView的文本
                            break;
                        }
                    } else {
                        Log.d(TAG, "Error getting documents: ", task.getException());
                    }
                }

            }
        }
    });

    return view;
}

这是你的Category类,你希望正确存储文档的地方:

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;
    }
}

这是你结构化Category集合的方式(共有8个文档/类别):如何从Firestore获取随机文档并在不同的TextView中显示它们?

英文:

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&lt;QuerySnapshot&gt;() {
@Override
public void onComplete(@NonNull Task&lt;QuerySnapshot&gt; task) {
if (task.isSuccessful()) {
List&lt;Category&gt; categoryList = new ArrayList&lt;&gt;();
for (DocumentSnapshot document : task.getResult()) {
Category category = document.toObject(Category.class);
categoryList.add(category);
}
int categoryListSize = categoryList.size();
List&lt;Category&gt; randomCategoryList = new ArrayList&lt;&gt;();
for (int i = 0; i &lt; 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, &quot;Error getting documents: &quot;, 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):
如何从Firestore获取随机文档并在不同的TextView中显示它们?

答案1

得分: 1

你好,我可以提供一个简单的建议。

List<Category> categoryList = null;

categoryCollectionRef.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
        if (task.isSuccessful()) {
            categoryList = new ArrayList<>();
            for (DocumentSnapshot document : task.getResult()) {
                Category category = document.toObject(Category.class);
                categoryList.add(category);
            }
        }
    }
});

testButtonClickListener....{
    Collections.shuffle(categoryList);
    showShuffledList();
}

public void showShuffledList() {
    textView1.setText(categoryList.get(0).getCategoryName());
    textView2.setText(categoryList.get(1).getCategoryName());
    textView3.setText(categoryList.get(2).getCategoryName());
}

// 当然,你应该在所有步骤中添加空值检查,并进行更多的配置。

希望这对你有所帮助。

英文:

Hi i can suggest easy way.

 List&lt;Category&gt; categoryList =null;
categoryCollectionRef.get().addOnCompleteListener(new 
OnCompleteListener&lt;QuerySnapshot&gt;() {
@Override
public void onComplete(@NonNull Task&lt;QuerySnapshot&gt; task) {
if (task.isSuccessful()) {
categoryList = new ArrayList&lt;&gt;();
for (DocumentSnapshot document : task.getResult()) {
Category category = document.toObject(Category.class);
categoryList.add(category);
}
}
}
}
});
testButtonClickListener....{
Collections.shuffle(categoryList);
showShuffledList();
}
public void showShuffledList(){
textView1.setText(categoryList.get(0).getCategoryName())
textView2.setText(categoryList.get(1).getCategoryName())
textView3.setText(categoryList.get(2).getCategoryName())
}

> Of course you should add null check all steps and configure more way.

答案2

得分: 0

  1. 当保存文档时,在名称末尾加上递增的数字,然后生成3个在范围内的随机数字,并获取以这些数字结尾的文档。

  2. 在所有文档中添加一个包含唯一数字的字段,并采用类似上述方法,但在这些字段上使用查询。

  3. 创建一个特殊文档,其中包含所有其他文档的名称数组。然后根据生成的随机数字从数组中获取3个文档名称。

还可能有其他方法,但这些是我首先想到的方法。

英文:

You can do 3 things:

  1. when saving the docs name them with an incremental number at the end, then generate 3 random numbers in range and fetch the docs ending in those numbers.

  2. add a field in all docs that holds a unique number and follow similar approach to the above but using a query on those fields.

  3. create a special doc that has the names of all other docs in an array. Then fetch 3 doc names from the array based on the generated random numbers.

There might be other ways too, but those are the approaches that first come to my mind.

huangapple
  • 本文由 发表于 2020年1月6日 21:54:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/59613364.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定