草庐IT

android - 从 Firebase 中的嵌套查询填充回收器 View

coder 2023-11-25 原文

我正在尝试使用嵌套查询填充回收器 View 。第一个查询转到 groups_list 节点并获取节点中的数据和唯一键。然后它转到具有该键的组节点并获取该键下的数据。这两个查询的结果都需要在回收站 View 中更新。

简而言之,第一个查询得到一些数据和一个键,这个键用于进行第二个查询。这两个查询的结果都需要在回收站 View 中更新。为此,我正在使用模型类和回收器 View 适配器。

但是我在下面收到一个错误。

我的 fragment 如下:

// Firebase
    fbDatabaseRootNode = FirebaseDatabase.getInstance().getReference();
    fbDatabaseRefGroupList = fbDatabaseRootNode.child("groups_list").child(current_user_id);
    fbDatabaseRefGroups = fbDatabaseRootNode.child("groups");

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

            // Array to Get Group List
            lGroupsList = new ArrayList<>();

            if (dataSnapshot.exists()) {

                // Clear Array to Get Group List
                lGroupsList.clear();

                for (DataSnapshot glSnapshot : dataSnapshot.getChildren()) {

                    // Use The Model To Format Array List and Pass It Into It
                    GroupsListModel g = glSnapshot.getValue(GroupsListModel.class);

                    // Array to Get Group List
                    lGroupsList.add(g);

                    String groupID = String.valueOf(glSnapshot.getKey());

                    fbDatabaseRefGroups.child(groupID).addValueEventListener(new ValueEventListener() {
                        @Override
                        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                            if (dataSnapshot.exists()) {

                                for (DataSnapshot gSnapshot : dataSnapshot.getChildren()) {

                                    // Use The Model To Format Array List and Pass It Into It
                                    GroupsListModel g = gSnapshot.getValue(GroupsListModel.class);

                                    // Array to Get Group List
                                    lGroupsList.add(g);

                                }

                            }

                        }

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

                        }
                    });

                }

                aGroupList = new GroupsListAdapter(getContext(), lGroupsList);
                rvGroupList.setAdapter(aGroupList);

            }

        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            System.out.println("The read failed: " + databaseError.getCode());

        }
    });

我的 Firebase 数据库结构看起来像

  "groups" : {
    "-LaPfENd0G4pHlejrcd6" : {
      "group_creation_date" : 1553078221782,
      "group_logo" : "0",
      "group_member_count" : "0",
      "group_name" : "dog lovers",
      "group_tagline" : "we love dogs..."
    },
    "-LaPhG0YHnF3FG0Czxom" : {
      "group_creation_date" : 1553078751686,
      "group_logo" : "0",
      "group_member_count" : "0",
      "group_name" : "hi",
      "group_tagline" : "hello"
    }
  },
  "groups_list" : {
    "F81wvGx9a7fXRrfVPQMhQtkM0wv2" : {
      "-LaPfENd0G4pHlejrcd6" : {
        "block_status" : "0",
        "hide_status" : "0",
        "notification_status" : "0",
        "pin_sequence" : "0",
        "report_status" : "0"
      },
      "-LaPhG0YHnF3FG0Czxom" : {
        "block_status" : "0",
        "hide_status" : "0",
        "notification_status" : "0",
        "pin_sequence" : "0",
        "report_status" : "0"
      }
    }
  },

模型类是

public class GroupsListModel {

    private String block_status;
    private String hide_status;
    private String notification_status;
    private String pin_sequence;
    private String report_status;

    private String group_name;
    private Long group_creation_date;
    private String group_logo;
    private String group_member_count;
    private String group_tagline;

    public GroupsListModel() {
    }

    public GroupsListModel(String block_status, String hide_status, String notification_status, String pin_sequence, String report_status, String group_name, Long group_creation_date, String group_logo, String group_member_count, String group_tagline) {
        this.block_status = block_status;
        this.hide_status = hide_status;
        this.notification_status = notification_status;
        this.pin_sequence = pin_sequence;
        this.report_status = report_status;
        this.group_name = group_name;
        this.group_creation_date = group_creation_date;
        this.group_logo = group_logo;
        this.group_member_count = group_member_count;
        this.group_tagline = group_tagline;
    }

    public String getBlock_status() {
        return block_status;
    }

    public void setBlock_status(String block_status) {
        this.block_status = block_status;
    }

    public String getHide_status() {
        return hide_status;
    }

    public void setHide_status(String hide_status) {
        this.hide_status = hide_status;
    }

    public String getNotification_status() {
        return notification_status;
    }

    public void setNotification_status(String notification_status) {
        this.notification_status = notification_status;
    }

    public String getPin_sequence() {
        return pin_sequence;
    }

    public void setPin_sequence(String pin_sequence) {
        this.pin_sequence = pin_sequence;
    }

    public String getReport_status() {
        return report_status;
    }

    public void setReport_status(String report_status) {
        this.report_status = report_status;
    }

    public String getGroup_name() {
        return group_name;
    }

    public void setGroup_name(String group_name) {
        this.group_name = group_name;
    }

    public Long getGroup_creation_date() {
        return group_creation_date;
    }

    public void setGroup_creation_date(Long group_creation_date) {
        this.group_creation_date = group_creation_date;
    }

    public String getGroup_logo() {
        return group_logo;
    }

    public void setGroup_logo(String group_logo) {
        this.group_logo = group_logo;
    }

    public String getGroup_member_count() {
        return group_member_count;
    }

    public void setGroup_member_count(String group_member_count) {
        this.group_member_count = group_member_count;
    }

    public String getGroup_tagline() {
        return group_tagline;
    }

    public void setGroup_tagline(String group_tagline) {
        this.group_tagline = group_tagline;
    }
}

错误是

Can't convert object of type java.lang.Long to type com.example.myproject

来自 datasnapshots 的日志如下...第一个...

第二个的日志...

可能的解决方案 1(传递给回收商查看问题,否则有效)

这似乎是以正确的顺序获取数据,现在只需将其传递到模型数组列表并设置适配器

// Get The Data
fbDatabaseRefGroupList.addChildEventListener(new ChildEventListener() {
    @Override
    public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

        if (dataSnapshot.exists()) {

            final String groupID = dataSnapshot.getKey();

            final String blockStatus = (String) dataSnapshot.child("block_status").getValue();
            final String hideStatus = (String) dataSnapshot.child("hide_status").getValue();
            final String notificationStatus = (String) dataSnapshot.child("notification_status").getValue();
            final String pinSequence = (String) dataSnapshot.child("pin_sequence").getValue();
            final String reportStatus = (String) dataSnapshot.child("report_status").getValue();

            fbDatabaseRefGroups.child(groupID).addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                    String groupName = (String) dataSnapshot.child("group_name").getValue();
                    String groupTagLine = (String) dataSnapshot.child("group_name").getValue();
                    String groupMemberCount = (String) dataSnapshot.child("group_name").getValue();


                }

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

                }
            });

        }

    }

    @Override
    public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

    }

    @Override
    public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {

    }

    @Override
    public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

    }

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

    }
});

可能的解决方案 2(列表合并是一个问题 - 否则工作)

  // Firebase
    fbDatabaseRootNode = FirebaseDatabase.getInstance().getReference();
    fbDatabaseRefGroupList = fbDatabaseRootNode.child("groups_list").child(current_user_id);
    fbDatabaseRefGroups = fbDatabaseRootNode.child("groups");

    // Array to Get Group List
    lGroupsListList = new ArrayList<>();
    lGroupsList = new ArrayList<>();
    lCombinedList = new ArrayList<>();

    // Clear Array to Get Group List
    lGroupsList.clear();
    // Clear Array to Get Group List
    lGroupsListList.clear();
    // Clear Array to Get Group List
    lCombinedList.clear();

    ValueEventListener valueEventListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            for (DataSnapshot ds : dataSnapshot.getChildren()) {

                // Use The Model To Format Array List and Pass It Into It
                GroupsListModel g = ds.getValue(GroupsListModel.class);

                // Array to Get Group List
                lGroupsListList.add(g);

                final String key = ds.getKey();

                final String blockStatus = (String) ds.child("block_status").getValue();

                DatabaseReference keyRef = fbDatabaseRootNode.child("groups").child(key);

                ValueEventListener eventListener = new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {

                        // Use The Model To Format Array List and Pass It Into It
                        GroupsListModel g = dataSnapshot.getValue(GroupsListModel.class);

                        // Array to Get Group List
                        lGroupsList.add(g);

                        String groupName = (String) dataSnapshot.child("group_name").getValue();

                        Log.d(TAG, "groupdetails: " + key + "--" + groupName + "--" + blockStatus);

                    }

                    @Override
                    public void onCancelled(@NonNull DatabaseError databaseError) {
                        Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
                    }
                };

                keyRef.addListenerForSingleValueEvent(eventListener);

            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
        }
    };

    aGroupList = new GroupsListAdapter(getContext(), lGroupsList);
    rvGroupList.setAdapter(aGroupList);

    fbDatabaseRefGroupList.addListenerForSingleValueEvent(valueEventListener);

@Prateek Jain 你的回答有误请看下面的截图:

可行的解决方案基于 Prateek Jains 的输入

public class GroupsListFragment extends Fragment {

    private static final String TAG = "GroupsListFragment";

    // Recycler View
    private RecyclerView rvGroupList;
    private GroupsListAdapter aGroupList;

    private List<GroupsListModel> lGroupsListList;
    private List<GroupsListModel> lGroupsList;
    private List<GroupsListModel> lCombinedList;

    // Firebase
    private FirebaseAuth mAuth;
    private DatabaseReference fbDatabaseRootNode;
    private DatabaseReference fbDatabaseRefGroupList;
    private DatabaseReference fbDatabaseRefGroups;
    private String current_user_id;

    private String groupID;
    private List<String> lgroupIDs;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_groups_list, container, false);

        mAuth = FirebaseAuth.getInstance();
        current_user_id = mAuth.getCurrentUser().getUid();

        // Init Recycler View
        rvGroupList = view.findViewById(R.id.f_groups_list_groups_list);
        rvGroupList.setHasFixedSize(true);
        rvGroupList.setLayoutManager(new LinearLayoutManager(getActivity()));

        // Firebase
        fbDatabaseRootNode = FirebaseDatabase.getInstance().getReference();
        fbDatabaseRefGroupList = fbDatabaseRootNode.child("groups_list").child(current_user_id);
        fbDatabaseRefGroups = fbDatabaseRootNode.child("groups");

        // Get The Data
        fbDatabaseRefGroupList.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

                // Array to Get Group List
                lGroupsList = new ArrayList<>();

                if (dataSnapshot.exists()) {

                    // Clear Array to Get Group List
                    lGroupsList.clear();

                    final String groupID = dataSnapshot.getKey();

                    final String blockStatus = (String) dataSnapshot.child("block_status").getValue();
                    final String hideStatus = (String) dataSnapshot.child("hide_status").getValue();
                    final String notificationStatus = (String) dataSnapshot.child("notification_status").getValue();
                    final String pinSequence = (String) dataSnapshot.child("pin_sequence").getValue();
                    final String reportStatus = (String) dataSnapshot.child("report_status").getValue();

                    fbDatabaseRefGroups.child(groupID).addListenerForSingleValueEvent(new ValueEventListener() {
                        @Override
                        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                            Long groupCreationDate = (Long) dataSnapshot.child("group_creation_date").getValue();
                            String groupLogo = (String) dataSnapshot.child("group_logo").getValue();
                            String groupMemberCount = (String) dataSnapshot.child("group_member_count").getValue();
                            String groupName = (String) dataSnapshot.child("group_name").getValue();
                            String groupTagLine = (String) dataSnapshot.child("group_tagline").getValue();

                            lGroupsList.add(new GroupsListModel(blockStatus, hideStatus, notificationStatus, pinSequence,
                                    reportStatus, groupName, groupCreationDate, groupLogo, groupMemberCount, groupTagLine));

                            aGroupList.notifyDataSetChanged();
                        }

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

                        }
                    });

                    aGroupList = new GroupsListAdapter(getContext(), lGroupsList);
                    rvGroupList.setAdapter(aGroupList);

                }

            }

            @Override
            public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

            }

            @Override
            public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

            }

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

            }
        });

        return view;

    }
}

最佳答案

您必须将所需的数据添加到您的适配器用来呈现 View 的列表中。完成后,您必须调用 notifyDataSetChanged , 这样适配器就可以从更新的列表中重新加载它的数据。

fbDatabaseRefGroups.child(groupID).addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

        String groupName = (String) dataSnapshot.child("group_name").getValue();
        String groupTagLine = (String) dataSnapshot.child("group_name").getValue();
        String groupMemberCount = (String) dataSnapshot.child("group_name").getValue();
        lGroupsList.add(new GroupsListModel(groupName, groupMemberCount, groupTagLine));
        aGroupList.notifyDataSetChanged();
        }

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

        }
   });

关于android - 从 Firebase 中的嵌套查询填充回收器 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55252138/

有关android - 从 Firebase 中的嵌套查询填充回收器 View的更多相关文章

  1. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  2. ruby - 其他文件中的 Rake 任务 - 2

    我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时

  3. ruby-on-rails - Ruby net/ldap 模块中的内存泄漏 - 2

    作为我的Rails应用程序的一部分,我编写了一个小导入程序,它从我们的LDAP系统中吸取数据并将其塞入一个用户表中。不幸的是,与LDAP相关的代码在遍历我们的32K用户时泄漏了大量内存,我一直无法弄清楚如何解决这个问题。这个问题似乎在某种程度上与LDAP库有关,因为当我删除对LDAP内容的调用时,内存使用情况会很好地稳定下来。此外,不断增加的对象是Net::BER::BerIdentifiedString和Net::BER::BerIdentifiedArray,它们都是LDAP库的一部分。当我运行导入时,内存使用量最终达到超过1GB的峰值。如果问题存在,我需要找到一些方法来更正我的代

  4. ruby-on-rails - Rails 3 中的多个路由文件 - 2

    Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题

  5. ruby - ECONNRESET (Whois::ConnectionError) - 尝试在 Ruby 中查询 Whois 时出错 - 2

    我正在用Ruby编写一个简单的程序来检查域列表是否被占用。基本上它循环遍历列表,并使用以下函数进行检查。require'rubygems'require'whois'defcheck_domain(domain)c=Whois::Client.newc.query("google.com").available?end程序不断出错(即使我在google.com中进行硬编码),并打印以下消息。鉴于该程序非常简单,我已经没有什么想法了-有什么建议吗?/Library/Ruby/Gems/1.8/gems/whois-2.0.2/lib/whois/server/adapters/base.

  6. ruby-on-rails - Rails 编辑表单不显示嵌套项 - 2

    我得到了一个包含嵌套链接的表单。编辑时链接字段为空的问题。这是我的表格:Editingkategori{:action=>'update',:id=>@konkurrancer.id})do|f|%>'Trackingurl',:style=>'width:500;'%>'Editkonkurrence'%>|我的konkurrencer模型:has_one:link我的链接模型:classLink我的konkurrancer编辑操作:defedit@konkurrancer=Konkurrancer.find(params[:id])@konkurrancer.link_attrib

  7. ruby - 什么是填充的 Base64 编码字符串以及如何在 ruby​​ 中生成它们? - 2

    我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%

  8. ruby-on-rails - Rails - 一个 View 中的多个模型 - 2

    我需要从一个View访问多个模型。以前,我的links_controller仅用于提供以不同方式排序的链接资源。现在我想包括一个部分(我假设)显示按分数排序的顶级用户(@users=User.all.sort_by(&:score))我知道我可以将此代码插入每个链接操作并从View访问它,但这似乎不是“ruby方式”,我将需要在不久的将来访问更多模型。这可能会变得很脏,是否有针对这种情况的任何技术?注意事项:我认为我的应用程序正朝着单一格式和动态页面内容的方向发展,本质上是一个典型的网络应用程序。我知道before_filter但考虑到我希望应用程序进入的方向,这似乎很麻烦。最终从任何

  9. ruby-on-rails - 渲染另一个 Controller 的 View - 2

    我想要做的是有2个不同的Controller,client和test_client。客户端Controller已经构建,我想创建一个test_clientController,我可以使用它来玩弄客户端的UI并根据需要进行调整。我主要是想绕过我在客户端中内置的验证及其对加载数据的管理Controller的依赖。所以我希望test_clientController加载示例数据集,然后呈现客户端Controller的索引View,以便我可以调整客户端UI。就是这样。我在test_clients索引方法中试过这个:classTestClientdefindexrender:template=>

  10. ruby - 将散列转换为嵌套散列 - 2

    这道题是thisquestion的逆题.给定一个散列,每个键都有一个数组,例如{[:a,:b,:c]=>1,[:a,:b,:d]=>2,[:a,:e]=>3,[:f]=>4,}将其转换为嵌套哈希的最佳方法是什么{:a=>{:b=>{:c=>1,:d=>2},:e=>3,},:f=>4,} 最佳答案 这是一个迭代的解决方案,递归的解决方案留给读者作为练习:defconvert(h={})ret={}h.eachdo|k,v|node=retk[0..-2].each{|x|node[x]||={};node=node[x]}node[

随机推荐