简体   繁体   English

如何主动获取firebase到android的数据

[英]how to proactively get data from firebase to android

I don't want to automatically receive data from firebase on change but receive it only when pressing a button.我不想在更改时自动接收来自 firebase 的数据,而是仅在按下按钮时接收数据。 Any ideas on how to adapt the code below?关于如何调整下面的代码的任何想法?

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        name = (EditText) findViewById(R.id.editTextTextPersonName);
        butt = (Button) findViewById(R.id.button);
        viet = (TextView) findViewById(R.id.textView_viet);
        butt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String var = name.getText().toString();
                getdataUser();
            }
        });
        }
    private void getdataUser(){
        data_user1.child(var).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot data) {
                String yy = data.getValue().toString();
                viet.setText(yy)
            }

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

            }
        });
    }

Any ideas are appreciated!任何想法表示赞赏!

If you want to read data a single time and be done with that, you shouldn't use addValueEventListener() .如果你想一次读取数据并完成它,你不应该使用addValueEventListener() Instead use addListenerForSingleValueEvent() as described in the documentation .而是按照文档中的描述使用addListenerForSingleValueEvent() You still have to process the results asynchronous in a callback, but it will be invoked only once with the snapshot of data at the location of your query.您仍然必须在回调中异步处理结果,但它只会在查询位置使用数据快照调用一次。

If you are trying to query the database synchronously to return the data immediately, there is no API for that - you have to process the data asynchronously with a callback.如果您尝试同步查询数据库以立即返回数据,则没有 API - 您必须使用回调异步处理数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM