本文介绍了如何在Android中以编程方式调用Firebase的ValueEventListener的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

student_edit.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) 
    {
        noof_placed=0;
        placpercent=0.0;
        enrolled=0;

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

            StudentDetail std = 
            postSnapshot.getValue(StudentDetail.class);
            std.setRollno(postSnapshot.getKey());
            studentlist.add(std);
            enrolled++;


            if (!std.getPlacementcompany().toString().trim().equals("0")) 
            {

                noof_placed++;

            }
        }
        placpercent=(noof_placed / total_students) * 100;
        start_progressbar(noof_placed,placpercent);
   }
    @Override
    public void onCancelled(DatabaseError databaseError) 
    {
    }
});

这是我从Firebase检索数据的侦听器,它将在Firebase中的数据更改时触发.如何以编程方式调用此侦听器

This is my listener for retrieving data from firebase it will be triggered when data changes in firebase. how can I invoke this listener programmatically

推荐答案

要触发您的侦听器,您可以写入数据库 student_edit 位置,也可以隔离侦听器然后调用该侦听器.我认为写入数据库是不言自明的.要隔离侦听器,您可以在类中添加一个成员字段:

To trigger your listener, you can either write to the database student_edit location, or isolate the listener and then call that. I assume that writing to the database is self-explanatory. To isolate the listener, you could add a member field to your class:

ValueEventListener studentListener;

然后初始化该字段并基于该字段设置侦听器:

Then initialize that field and set the listener based on it:

studentListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) 
    {
        noof_placed=0;
        placpercent=0.0;
        enrolled=0;

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

            StudentDetail std = 
            postSnapshot.getValue(StudentDetail.class);
            std.setRollno(postSnapshot.getKey());
            studentlist.add(std);
            enrolled++;


            if (!std.getPlacementcompany().toString().trim().equals("0")) 
            {

                noof_placed++;

            }
        }
        placpercent=(noof_placed / total_students) * 100;
        start_progressbar(noof_placed,placpercent);
   }
    @Override
    public void onCancelled(DatabaseError databaseError) 
    {
    }
});
student_edit.addValueEventListener(studentListener);

然后您可以使用以下任何一种方式调用它:

And then you can call it anywhere with:

studentListener.onDataChange(YOUR_SNAPSHOT);

当然,问题在于您随后需要保留快照.

Of course the problem becomes that you then need to keep the snapshot around.

这篇关于如何在Android中以编程方式调用Firebase的ValueEventListener的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 23:44