简体   繁体   English

从 Firebase 获取项目的位置

[英]Get the position of item from Firebase

I have found the code that runs trough my list of leader board and returns the corresponding value.我找到了通过我的排行榜列表运行并返回相应值的代码。 But I would need to return the position of the item in the list.但我需要返回列表中项目的位置。 How should I modify the code so it would return the position (index) of the item.我应该如何修改代码以便它返回项目的位置(索引)。

Thanks.谢谢。

//query for sorting by score
    score = FirebaseDatabase.getInstance().getReference().child("Leaders");
    final Query query = score.orderByChild("uID").equalTo(mCurrentUser.getUid());

    query.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            Iterator<DataSnapshot> iterator = dataSnapshot.getChildren().iterator();

            int length = (int) dataSnapshot.getChildrenCount();

            String[] sampleString = new String[length];

            while(i < length) {
                sampleString[i] = iterator.next().getValue().toString();
                //Log.d(Integer.toString(i), sampleString[i]);

                //print the value of current score
                Toast.makeText(LeaderBoardActivity.this,sampleString[i],Toast.LENGTH_LONG).show();
                i++;
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

在此处输入图片说明

I've edited the code based on your comments.我已经根据您的评论编辑了代码。 Since you only care about the position and score...既然你只关心位置和分数...

// you will need to query the database based on scores
score = FirebaseDatabase.getInstance().getReference().child("Leaders");
final Query query = score.orderByChild("Score");
query.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        // get total leaders. Let's say total leader is 5 persons
        int total = (int) dataSnapshot.getChildrenCount();
        // let's say userB is actually 2nd in the list
        int i = 0;
        // loop through dataSnapshot
        for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
            String uID = childSnapshot.child("uID").getValue();
            if (uID.equals(mCurrentUser.getUid()) {
                // the list is ascending, when finally reach userB, i = 3
                int userPlace = total - i;    // gives 2
                int score = childSnapshot.child("Score").getValue(Interger.class);
                break;
            } else {
                i++;
            }
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});

Note that this can be very bandwidth consuming.请注意,这可能非常消耗带宽。 As you get more and more users, you will need to download all the user data for each query.随着用户越来越多,您将需要下载每个查询的所有用户数据。 It might be better if you just show the top 5 leaders etc.如果你只展示前 5 名领导者等可能会更好。

I use following method to change child value by position, hope this can give you some helps:我使用以下方法按位置更改子值,希望这可以给您一些帮助:

DataSnapshot targetData;

@Override
protected void onStart() {
    super.onStart();

    targetReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshots) {
            targetData = dataSnapshots;        //save in global variable
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
        }
    });
}

private void yourMethod() {
    int index = 0;

    for (DataSnapshot childSnapshot : targetData.getChildren()) {
        if (index == 1) {        //your target index
            DatabaseReference currentReference = childSnapshot.getRef();

            currentReference.setValue("xxx");
        }

        index++;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM