FirebaseListAdapter排序异常:仅能正确排序rank≤999的条目
FirebaseListAdapter按rank排序异常:数值超过999的条目置顶问题解决
我在使用FirebaseListAdapter展示玩家列表时遇到了一个奇怪的排序问题:我通过orderByChild("rank")对列表进行排序,rank的取值范围是0到10000的整数。当rank值≤999时,列表排序完全正常,但一旦rank超过999,对应的条目就会直接被添加到列表顶部,而不是按数值大小排在正确的位置(截图右侧显示的是rank值)。
相关代码片段
数据库查询与适配器初始化
Query query = FirebaseDatabase.getInstance().getReference().child("PlayerList").orderByChild("rank"); FirebaseListOptions<Usertag> retrieveMax = new FirebaseListOptions.Builder<Usertag>() .setLayout(R.layout.user_tag_model_fullscreen) .setQuery(query, Usertag.class) .build();
适配器类实现
public class FbAdapterFullScreen extends FirebaseListAdapter<Usertag> { Context c; public FbAdapterFullScreen(Context c, @NonNull FirebaseListOptions<Usertag> retrieveMax) { super(retrieveMax); this.c =c; } @Override protected void populateView(@NonNull View view, @NonNull Usertag model, int position) { TextView TagTxt= (TextView) view.findViewById(R.id.userTagtvfs); TextView TroopsTxt= (TextView) view.findViewById(R.id.userTroopstvfs); TextView SpellTxt= (TextView) view.findViewById(R.id.userSpelltvfs); TextView RankTxt= (TextView) view.findViewById(R.id.userRanktvfs); TextView StatusTxt= (TextView) view.findViewById(R.id.userStatustvfs); Button RankUP = (Button) view.findViewById(R.id.rankupBtnfs); CardView cardforitems = view.findViewById(R.id.cardforitemsfs); TagTxt.setText(model.getPlayerTag()); TroopsTxt.setText(model.getTroops()); SpellTxt.setText(model.getSpell()); RankTxt.setText(model.getRank()); StatusTxt.setText(model.getStatus()); String[] favorites = MyUserTag.getFavoriteListt(c); //Toast.makeText(c, ""+Arrays.toString(favorites), Toast.LENGTH_SHORT).show(); if (model.getCocPlayerTag()!=null) { if (Arrays.toString(favorites).contains(model.getPlayerTag())) { TagTxt.setTextColor(c.getResources().getColor(R.color.green)); cardforitems.setCardBackgroundColor(c.getResources().getColor(R.color.dullgreen)); } else { TagTxt.setTextColor(c.getResources().getColor(R.color.darkblue)); cardforitems.setCardBackgroundColor(c.getResources().getColor(R.color.light_white)); } } } }
问题排查与解决
我尝试了各种排查手段都没找到问题所在,后来在Amitabh Das的提示下,我发现了核心问题:
问题根源
我的Usertag模型类中,rank字段被定义成了String类型,而Firebase对字符串类型的数字是按字典序排序的,不是数值大小。比如字符串"1000"在字典序里会排在"999"前面,因为第一个字符"1"的ASCII码比"9"小,这就导致rank超过999的条目被错误置顶。
解决方法
把模型类中的String rank修改为Long rank(或Integer类型,根据数值范围选择),同时确保Firebase数据库中存储的rank值是数字类型(而非字符串)。修改后,Firebase就会按数值大小对rank进行排序,问题完美解决。
内容的提问来源于stack exchange,提问作者Genie
相关产品推荐
相关产品推荐

