Firebase查询在片段视图返回后执行

huangapple go评论70阅读模式
英文:

Firebase query executing after fragment view has been returned

问题

我有一个扩展Fragment类的类,其中在其onCreateView方法中包含对Firebase的查询。在使用调试器分析程序后,我意识到该查询直到视图返回后才会执行。

该查询返回将加载到RecyclerView中的信息。我还为数据本身创建了一个适配器。代码没有产生任何错误,但其功能不符合预期。理想情况下,查询应该首先执行,这样我就可以在这个RecyclerView上显示数据。您知道这是为什么吗?

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable final ViewGroup container, @Nullable Bundle savedInstanceState)
{
    final View view = inflater.inflate(R.layout.frag_events, container, false);
    eventIds = new ArrayList<String>();

    // 在视图返回后执行
    ValueEventListener eventIdValListener = new ValueEventListener()
    {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot)
        {
            eventIds.clear();
            if (snapshot.exists())
            {
                for (DataSnapshot e : snapshot.getChildren())
                {
                    String event = e.getValue(String.class);
                    eventIds.add(event);
                }
            }
        }

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

        }
    };
    // 为当前用户返回数据
    Query query = FirebaseDbSingleton.getInstance().dbRef.child("User").child(FirebaseDbSingleton.getInstance().user.getUid().toString()).child("events");
    query.addValueEventListener(eventIdValListener);
    
    return view;
}

我在这里省略了一些用于RecyclerView和适配器的行,以保持代码的简洁。我有一种感觉这可能是由于eventIdValListener中的内部类导致的,但我不完全确定。

英文:

I have a class that extends Fragment and that contains a query to Firebase in its onCreateView method. After analyzing the program with the debugger, I realized that this query isn't executing until after the view has been returned.

The query returns information that will be loaded into a recyclerview. I also have created an adapter for the data itself. The code does not produce any errors but it's not functioning the way it should. Ideally, the query should execute first that way I can show the data on this recyclerview. Any idea why this is happening?

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable final ViewGroup container, @Nullable Bundle savedInstanceState)
{
    final View view=inflater.inflate(R.layout.frag_events, container, false);
    eventIds =new ArrayList&lt;String&gt;();

    //executes after view has been returned
    ValueEventListener eventIdValListener=new ValueEventListener()
    {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot)
        {
            eventIds.clear();
            if(snapshot.exists())
            {
                for (DataSnapshot e : snapshot.getChildren())
                {
                    String event = e.getValue(String.class);
                    eventIds.add(event);
                }
            }
        }

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

        }
    };
    //returns data for current user 
    Query query=FirebaseDbSingleton.getInstance().dbRef.child(&quot;User&quot;).child(FirebaseDbSingleton.getInstance().user.getUid().toString()).child(&quot;events&quot;);
    query.addValueEventListener(eventIdValListener);
    
    return view;
}

I left out some lines for the recycler and adapter just to keep this code short. I have a feeling this might be due to the innerclass in eventIdValListener but I am not entirely sure.

答案1

得分: 1

所有查询数据库的 Firebase API 都是异步的,并在调用后的某个时间完成。你无法在 onCreateView 返回之前使其真正完成 - 它必须立即返回一个 View 实例。

由于你不知道查询何时会完成,也无法保证需要多长时间,所以你需要添加逻辑,在查询完成之前显示某些内容(比如等待指示器)。这对于执行网络或数据库操作的任何应用程序都是标准做法。

英文:

All Firebase APIs that query the database are asynchronous and complete some time later after they're invoked. You can't realistically make it finish before onCreateView returns - it must return immediately with a View instance.

Since you don't know how long it will take for the query to complete, and there is no guarantee how long, you will need to add logic to show something before the query is complete (such as a waiting indicator). This is standard for any app that performs network or database operations.

huangapple
  • 本文由 发表于 2020年10月11日 09:33:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/64299860.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定