英文:
How to get the selected index document from the firestore?
问题
我试图从一个列表中获取所选项目的索引,数据存储在Firestore中,我尝试过的方法是:
db.collection("Musicians").orderBy("DocumentID", Query.Direction.ASCENDING).limit(30).get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
List<DocumentSnapshot> snapshotslist = Objects.requireNonNull(task.getResult()).getDocuments();
for (DocumentSnapshot document : snapshotslist) {
// --- 这种方式不起作用 ----------------------------------//
int index = snapshotslist.indexOf("Flkt8Fb0gWvO9xaUYR0V"); // 这个方法总是返回 -1
// ---- 这种方式有效 --------------------------------//
int index = snapshotslist.indexOf(document); // 这个方法有效,它给出了列表的所有索引
// 但我只需要获取我输入的文档的索引。例如,
}
}
}
});
- Flkt8Fb0gWvO9xaUYR0V
- BpJQAYm7Y49XA2IZMGhE
- LTy4KuRpXTc5e7FK2I9o
- bxzM9drC9DWDieWEbFLl
我想要获取"LTy4KuRpXTc5e7FK2I9o"的索引,输出应该是2。
英文:
I'm trying to get the selected item index from a list and the data have stored in firestore, What I tried is,
db.collection("Musicians").orderBy("DocumentID", Query.Direction.ASCENDING).limit(30).get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()){
List<DocumentSnapshot> snapshotslist= Objects.requireNonNull(task.getResult()).getDocuments();
(DocumentSnapshot document : snapshotslist) {
//--- This way is not working----------------------------------//
int index = snapshotslist.indexOf("Flkt8Fb0gWvO9xaUYR0V");//This method always return -1
//----This way is working--------------------------------//
int index = snapshotslist.indexOf(document);// This method is working and it gives all index of the list
But I only need to get the Index of the document which I entered. For example,
- Flkt8Fb0gWvO9xaUYR0V
- BpJQAYm7Y49XA2IZMGhE
- LTy4KuRpXTc5e7FK2I9o
- bxzM9drC9DWDieWEbFLl
I want to get the index of "LTy4KuRpXTc5e7FK2I9o" which output is 2.
答案1
得分: 1
如果我理解正确,您想要根据文档的ID在列表中找到文档的索引。
在这种情况下,您可以这样做:
List<DocumentSnapshot> snapshotslist = Objects.requireNonNull(task.getResult()).getDocuments();
int index = 0;
for (DocumentSnapshot document : snapshotslist) {
if (document.getId().equals("Flkt8Fb0gWvO9xaUYR0V")) {
break;
}
index++;
}
英文:
If I understand correctly you want to find the index of the document in a list, based on its ID.
In that case, you can do:
List<DocumentSnapshot> snapshotslist= Objects.requireNonNull(task.getResult()).getDocuments();
int index = 0;
for (DocumentSnapshot document : snapshotslist) {
if (document.getId().equals("Flkt8Fb0gWvO9xaUYR0V")) {
break;
}
index++;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论