在Android应用中无需使用OnClickListener检索Firebase数据

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

Retrieving Firebase data in Android application without an OnClickListener

问题

我正在尝试从我的Firebase数据库中的表格中获取特定列的总和,以生成一个平均值(与当前读数对比),并在我的Android应用程序中显示该值。仅仅作为一个测试,我想要在我的测试应用程序中在一个TextView中显示该总和。当我首次声明addValueEventListener时:

reff.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot snapshot) {
        for (DataSnapshot snapshot2:  snapshot.getChildren()){
            sum = sum + snapshot2.child("age").getValue(Integer.class);
        }
    }

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

    }
});

然后进行数据库的setValue()调用,并在onClick事件中设置textView,这可以按预期工作。

button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        reff.child(String.valueOf(maxid+1)).setValue(member);
        Toast.makeText(MainActivity.this, "数据插入成功", Toast.LENGTH_LONG).show();
        a.setText(String.valueOf(sum));
    }
});

然而,在我的应用程序中,我不想通过按钮点击来触发"sum"值。我希望它一直存在,以便我可以将新数据与数据库中的滚动平均值进行比较。如果我将上述代码从OnClickListener移到我的主要onCreate方法中,sum的值会保持为0。阅读了各种讨论帖子后,我还将addValueEventListener()替换为addListenerForSingleValueEvent(),但这没有任何影响。

是否有人能够建议一种重新格式化此代码的方法,而无需依赖按钮点击来从我的表格中获取总和?

英文:

I'm trying to get a summation of a particular column within a table in my Firebase database to produce an average (to contrast with a current reading) of a value in my Android application. Just as a test, I wanted to show that sum in a TextView in my test application. When I first declare the addValueEventListener:

 reff.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {


            for (DataSnapshot snapshot2:  snapshot.getChildren()){
                sum = sum + snapshot2.child("age").getValue(Integer.class);
            }
        }

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

        }
    });

And then make a database setValue() call and set the textView in an onClickListener, this works as expected.

 button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            reff.child(String.valueOf(maxid+1)).setValue(member);
            Toast.makeText(MainActivity.this, "data inserted successfully", Toast.LENGTH_LONG).show();
            a.setText(String.valueOf(sum));

        }
    });

Ultimately in my application, however, I don't want the "sum" value triggered by a button click. I want this to be present so that I can compare new data with a rolling average from my database. If I move the above code from the OnClickListener into my main onCreate method, the value for sum stays at 0. Reading various threads, I also substituted addValueEventListener() for addListenerForSingleValueEvent() but this had no impact.

Would anyone be able to suggest a way I could reformat this without having to rely on a button being pushed to get the summation from my table?

答案1

得分: 1

调用a.setText()的部分需要放在onDataChange内,因为这是唯一在更新的数据来自数据库时保证执行的代码。

所以:

reff.addValueEventListener(new ValueEventListener() {

    @Override
    public void onDataChange(@NonNull DataSnapshot snapshot) {
        for (DataSnapshot snapshot2 : snapshot.getChildren()) {
            sum = sum + snapshot2.child("age").getValue(Integer.class);
        }
        a.setText(String.valueOf(sum));
    }

    @Override
    public void onCancelled(@NonNull DatabaseError error) {
        throw error.toException();
    }
});

另外:请永远不要onCancelled留空,因为这样会忽略潜在的错误。

另请参阅:https://stackoverflow.com/questions/50434836/getcontactsfromfirebase-method-return-an-empty-list/50435519#50435519,我会将您的问题标记为重复 - 我只是想向您展示代码中相关的解决方案。

英文:

The call to a.setText() needs to be inside onDataChange, as that is the only code that is guaranteed to be executed when the updated data comes from the database.

So:

reff.addValueEventListener(new ValueEventListener() {

    @Override
    public void onDataChange(@NonNull DataSnapshot snapshot) {
        for (DataSnapshot snapshot2:  snapshot.getChildren()){
            sum = sum + snapshot2.child("age").getValue(Integer.class);
        }
        a.setText(String.valueOf(sum));
    }

    @Override
    public void onCancelled(@NonNull DatabaseError error) {
        throw error.toException();
    }
});

Also: please never leave onCancelled empty, as your ignoring potential errors that way,.

Also see: https://stackoverflow.com/questions/50434836/getcontactsfromfirebase-method-return-an-empty-list/50435519#50435519, which I'll close your question as a dupe of - I just wanted to show you the relevant solution in code too.

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

发表评论

匿名网友

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

确定