无法从从Firebase Realtime数据库检索数据以在以下代码行中使用的方法获取返回值 [英] Can't get the return value from a method that retrieves data from Firebase Realtime database to use it in following line of code

查看:53
本文介绍了无法从从Firebase Realtime数据库检索数据以在以下代码行中使用的方法获取返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Firebase Realtime数据库很陌生.我正在开发一个需要从Firebase Realtime DB检索数据的android应用程序.在大多数情况下,我已经能够使用Firebase侦听器方法检索数据,但有一次,我发现它无法以我想要的方式获得值(我认为是由于异步的性质).

I'm quite new to Firebase Realtime database. I'm working on an android app which requires data to be retrieved from Firebase Realtime DB. I've been able to retrieve data using the Firebase listener methods in most occasions but on one occasion, I've found it unable to get a value in the way that I want (I think because of the asynchronous nature).

场景:-

我在Firebase实时数据库中具有如下数据结构:

I have a data structure in Firebase Realtime Database as follows:

关于评分:

对于用户:

我有一个单独的Java类(Suggest.java),该类具有一个简单的方法来获取用户列表(此处未显示,因为它是基本的实现),下面定义的方法是从上述评级节点中检索数据,以列表:

I have a separate java class (Suggest.java) that has one simple method to get a list of users (not shown here since it is the basic implementation) and the method defined below to retrieve data from the above ratings node to a list:

public List<String> getMyUnratedPosts(final String currentUserId){
    final List<String> currentUserUnratedPosts = new ArrayList<>();
    DBRCurrentUnratedList = FirebaseDatabase.getInstance().getReference().child("adRat").child(currentUserId);
    DBRCurrentUnratedList.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                AdRat adr = snapshot.getValue(AdRat.class);
                int vr = adr.getViewRating();
                if(vr < 1) {
                    currentUserUnratedPosts.add(adr.getAdId());
                }
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }

    });
    return currentUserUnratedPosts;
}

上面定义的AdRat类只是具有与上面给出的数据库节点匹配的属性(以及getter和setter)的类.

The AdRat class defined above is just a class with attributes (and getters and setters) which matches the database node given above.

我正在我的活动的onCreate()方法中创建此类(Suggest.java)的实例.然后,首先调用一种仅获取用户列表的方法(与上述获得评分的方法非常相似).然后,在我的活动的下一行代码中,我使用一个for循环从所获得的列表中获取每个用户,并将该userId用于上面显示的方法.例如,如下所示:

I'm creating an instance of this class (Suggest.java) in the onCreate() method of my activity. Then first I'm calling a method in which I'm simply getting a list of users (very similar to above method in which I get the ratings). Then the next line of code in my activity I use a for loop to get each user from the list I got and use that userId for the method shown above. For example, it would be as follows:

Suggest sj = new Suggest();
List<String> users = sj.getUsers();
for (final String mUser: users) {                 
    //Just trying to use the user from above here
    List<String> myUnratedItems = sj.getMyUnratedPosts(mUser);
    Log.d(TAG, "list contains : " + myUnratedItems.toString());
}

问题:-

运行此命令时,我没有从代码中得到预期的结果.当我调试它时,用户列表将为空.我认为由于firebase方法是异步的,因此它们不会在下一行代码(正是我需要的地方)中给出准确的结果,而是稍后给出结果(但随后程序已在代码行中运行)我需要这些数据.)

I do not get the intended result from the code when I run this. When I debug it, I will get null for the list of users. I think since the firebase methods are asynchronous they do not give the result exactly at the next line of code (that is the place where I need it) but gives the result a bit later (but then the program has run over the line of code in which I need that data).

我的整体需求:-

获取要在下一行代码中使用的用户列表(用于下一个方法).

Get the list of users to use it in the next line of code (for the next method).

我已经在Stackoverflow中解决了几个问题,但是找不到确切的答案.

I've gone through several questions in Stackoverflow in regard to this, but couldn't find an exact answer for this.

请亲切说明为什么会发生这种情况,以及解决此问题的任何解决方法.

Please kindly explain as to why this happens and any workaround for this....

P.S. :-我是stackoverflow的新手,所以请承担在编写问题时犯下的任何错误.谢谢.

P.S. : - I'm new to stackoverflow, so please bear with me any mistakes done in composing the question. Thanks.

推荐答案

您完全正确,因为它是由Firebase调用的异步性引起的.您最可能希望使用的系统类型是您订阅"以知道呼叫何时完成的系统.您可以使用回调函数或其他方法,例如将一个字段/数据添加到列表中,并让另一个数据结构定期检查列表中的更新,以了解异步调用何时完成.

You're exactly right in that it is caused by the asynchronicity of the Firebase calls. The kind of system you'll most likely want to employ is one in which you "subscribe" to know when calls have completed. You can use a callback function, or some other method, such as adding a field/piece of data to a list, and having another data structure periodically check the list for updates, in order to know when the async call has completed.

您的流量可能是这样的:

Your flow will probably be something like this:

  1. 订阅"到异步数据结构
  2. 执行异步数据结构
  3. 异步调用完成后,执行一些操作.

我建议您查看以下有关Geeksforgeeks中Java异步回调的链接: https://www.geeksforgeeks.org/asynchronous-synchronous-callbacks-java/

I'd recommend looking at the following link on Asynchronous callbacks in Java from Geeksforgeeks: https://www.geeksforgeeks.org/asynchronous-synchronous-callbacks-java/

这篇关于无法从从Firebase Realtime数据库检索数据以在以下代码行中使用的方法获取返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆