Java Log.e(“三”,list.get(2)); query1=list.get(0);//在这个变量中,字符串与它们一起存储,然后您可以在Firestore中进行常规查询以获取实际文档 query2=list.get(1); query3=list.get(2); }捕获(例外e){ e、 printStackTrace(); } }
以下是我从Firestore获得的阵列: 我遇到了一个类似的问题(我只需要每24小时获取一个随机文档,或者当用户手动刷新页面时,但您也可以将此解决方案应用到您的案例中),对我有效的方法如下: 技巧Java Log.e(“三”,list.get(2)); query1=list.get(0);//在这个变量中,字符串与它们一起存储,然后您可以在Firestore中进行常规查询以获取实际文档 query2=list.get(1); query3=list.get(2); }捕获(例外e){ e、 printStackTrace(); } },java,android,firebase,google-cloud-firestore,Java,Android,Firebase,Google Cloud Firestore,以下是我从Firestore获得的阵列: 我遇到了一个类似的问题(我只需要每24小时获取一个随机文档,或者当用户手动刷新页面时,但您也可以将此解决方案应用到您的案例中),对我有效的方法如下: 技巧 第一次阅读一小份文档列表,比如1到10个文档(在您的情况下是10到30或50个) 根据文档列表范围内随机生成的数字选择随机文档 在客户端设备上本地保存您选择的文档的最后一个id(可能像我一样在共享首选项中) 如果您想要一个新的随机文档,您将使用保存的文档id在保存的文档id之后再次启动流程(步骤1至3
var documentId=//从共享首选项获取文档id(如果之前未设置,则为空)
getRandomDocument(文档ID)
有趣的getRandomDocument(documentId:String?){
if(documentId==null){
val query=FirebaseFirestore.getInstance()
.集合(集合名称)
.limit(getLimitSize())
loadDataWithQuery(查询)
}否则{
val docRef=FirebaseFirestore.getInstance()
.集合(集合名称).文档(文档ID)
docRef.get().addOnSuccessListener{documentSnapshot->
val query=FirebaseFirestore.getInstance()
.集合(集合名称)
.startAfter(文档快照)
.limit(getLimitSize())
loadDataWithQuery(查询)
}.addOnFailureListener{e->
//处理失败
}
}
}
fun loadDataWithQuery(查询:查询){
query.get().addOnSuccessListener{queryDocumentSnapshots->
val documents=queryDocumentSnapshots.documents
if(documents.isNotEmpty()&&documents[documents.size-1].exists()){
//从加载的列表中选择一个文档(我选择了列表中的最后一个文档)
val快照=文档[documents.size-1]
var documentId=snapshot.id
//在此共享首选项中保存文档id
//在这里处理随机文件
}否则{
//在到达文档列表末尾时进行处理
//所以我们重新开始,因为这是我们第一次得到一个随机文档
//通过调用带有null作为documentId的getRandomDocument()
getRandomDocument(空)
}
}
}
fun getLimitSize():长{
val random=random()
val listLimit=10
return(random.nextInt(listLimit)+1.toLong()
}
基于我为Unity3D写的这篇文章及其对我的作用
FirebaseFirestore db;
void Start()
{
db = FirebaseFirestore.DefaultInstance;
}
public void GetRandomDocument()
{
Query query1 = db.Collection("Sports").WhereGreaterThanOrEqualTo(FieldPath.DocumentId, db.Collection("Sports").Document().Id).Limit(1);
Query query2 = db.Collection("Sports").WhereLessThan(FieldPath.DocumentId, db.Collection("Sports").Document().Id).Limit(1);
query1.GetSnapshotAsync().ContinueWithOnMainThread((querySnapshotTask1) =>
{
if(querySnapshotTask1.Result.Count > 0)
{
foreach (DocumentSnapshot documentSnapshot in querySnapshotTask1.Result.Documents)
{
Debug.Log("Random ID: "+documentSnapshot.Id);
}
} else
{
query2.GetSnapshotAsync().ContinueWithOnMainThread((querySnapshotTask2) =>
{
foreach (DocumentSnapshot documentSnapshot in querySnapshotTask2.Result.Documents)
{
Debug.Log("Random ID: " + documentSnapshot.Id);
}
});
}
});
}
如果学生有身份证号码,难道不可能使用随机生成的号码来选择哪个学生吗?@Geshode我将学生身份证指定为idSo文档,不可能使用随机生成的号码吗?这只是一个想法。你能解释一下你的想法吗?该问题重新打开,因为它与其他问题重复er语言。它没有内存效率。如果我只需要10个文档,为什么它可以检索1000个。使用第一种解决方案,它可以用于小数据集,但第二种方法对于10个随机学生只意味着11次读取。
randomNumber
在for循环中将是相同的,所以我认为相同的文档将被存储10次。@PratikButani很好地抓住了Pratik。刚刚用正确的方法更新了我的答案,感谢你帮助我更正答案。现在没有重复;)也从侧面完成了,因为最终你的答案给了我提示。:)谢谢。视频模型课看起来怎么样?这就是重点。。。从集合中获取所有文档非常昂贵而且效率低下!
FieldValue.arrayUnion("yourArrayProperty")
FieldValue.arrayRemove("yourArrayProperty")
FirebaseFirestore database = FirebaseFirestore.getInstance();
CollectionReference collection = database.collection(VIDEO_PATH);
collection.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
List<VideoModel> videoModelList = new ArrayList<>();
for (DocumentSnapshot document : Objects.requireNonNull(task.getResult())) {
VideoModel student = document.toObject(VideoModel.class);
videoModelList.add(student);
}
/* Get Size of Total Items */
int size = videoModelList.size();
/* Random Array List */
ArrayList<VideoModel> randomVideoModels = new ArrayList<>();
/* for-loop: It will loop all the data if you want
* RANDOM + UNIQUE data.
* */
for (int i = 0; i < size; i++) {
// Getting random number (inside loop just because every time we'll generate new number)
int randomNumber = new Random().nextInt(size);
VideoModel model = videoModelList.get(randomNumber);
// Check with current items whether its same or not
// It will helpful when you want to show related items excepting current item
if (!model.getTitle().equals(mTitle)) {
// Check whether current list is contains same item.
// May random number get similar again then its happens
if (!randomVideoModels.contains(model))
randomVideoModels.add(model);
// How many random items you want
// I want 6 items so It will break loop if size will be 6.
if (randomVideoModels.size() == 6) break;
}
}
// Bind adapter
if (randomVideoModels.size() > 0) {
adapter = new RelatedVideoAdapter(VideoPlayerActivity.this, randomVideoModels, VideoPlayerActivity.this);
binding.recyclerView.setAdapter(adapter);
}
} else {
Log.d("TAG", "Error getting documents: ", task.getException());
}
}
});
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_category_selection, container, false);
btnNavFragCat1 = view.findViewById(R.id.btn_category_1);
btnNavFragCat1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
questionKeyRef.document(tvCat1).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
List<String> questions = (List<String>) document.get("questions"); // This gets the array list from Firestore
List<String> randomList = getRandomElement(questions, 0);
removeDuplicates(randomList);
...
}
}
});
}
});
...
return view;
}
private List<String> getRandomElement(List<String> list, int totalItems) {
int PICK_RANDOM_STRING = 3;
Random rand = new Random();
List<String> newList = new ArrayList<>();
int count = 0;
while (count < PICK_RANDOM_STRING) {
int randomIndex = rand.nextInt(list.size());
String currentValue = list.get(randomIndex);
if (!newList.contains(currentValue)) {
newList.add(currentValue);
count++;
}
}
return newList;
}
private void removeDuplicates(List<String> list) {
try {
Log.e("One", list.get(0));
Log.e("Two", list.get(1));
Log.e("Three", list.get(2));
query1 = list.get(0); // In this vars are the strings stored with them you can then make a normal query in Firestore to get the actual document
query2 = list.get(1);
query3 = list.get(2);
} catch (Exception e) {
e.printStackTrace();
}
}
FirebaseFirestore db;
void Start()
{
db = FirebaseFirestore.DefaultInstance;
}
public void GetRandomDocument()
{
Query query1 = db.Collection("Sports").WhereGreaterThanOrEqualTo(FieldPath.DocumentId, db.Collection("Sports").Document().Id).Limit(1);
Query query2 = db.Collection("Sports").WhereLessThan(FieldPath.DocumentId, db.Collection("Sports").Document().Id).Limit(1);
query1.GetSnapshotAsync().ContinueWithOnMainThread((querySnapshotTask1) =>
{
if(querySnapshotTask1.Result.Count > 0)
{
foreach (DocumentSnapshot documentSnapshot in querySnapshotTask1.Result.Documents)
{
Debug.Log("Random ID: "+documentSnapshot.Id);
}
} else
{
query2.GetSnapshotAsync().ContinueWithOnMainThread((querySnapshotTask2) =>
{
foreach (DocumentSnapshot documentSnapshot in querySnapshotTask2.Result.Documents)
{
Debug.Log("Random ID: " + documentSnapshot.Id);
}
});
}
});
}