简体   繁体   English

从Firebase获取数据时需要单击多个按钮才能显示

[英]Fetching data from firebase taking more than one button click to display

I want to display data which is fetched from firebase whenever user clicks a button. 我想显示每当用户单击按钮时从firebase提取的数据。 This is the code which I am using currently 这是我目前正在使用的代码

todayPoem = (TextView) findViewById(R.id.todpoem);

/*Firebase related code*/
        myFirebaseRef = new Firebase("https://firebase url");

        myFirebaseRef.child("poem").addValueEventListener(new ValueEventListener() {

            @Override
            public void onDataChange(DataSnapshot snapshot) {
                System.out.println(snapshot.getValue());
                s1 = (String) snapshot.getValue();
            }

            @Override
            public void onCancelled(FirebaseError error) {
            }


        });



    }

    public void onClickPoem(View v) {
        todayPoem.setTextSize(20);
        todayPoem.setText(s1);
    }

And the xml file contains a textview and a button to fetch data from the firebase. xml文件包含一个textview和一个从Firebase中获取数据的按钮。 But the problem is whenever I click the button the data is not displayed instantly, usually it takes almost 5-6 button clicks for the data to be displayed. 但是问题是,每当我单击按钮时,数据都不会立即显示,通常需要将近5-6次按钮单击才能显示数据。 What am I doing wrong here? 我在这里做错了什么?

I had this problem before... I would advice you doing it like this example: 我之前遇到过这个问题...我建议您像下面的示例那样做:

mrf.setAndroidContext(this);
mrf = new Firebase('Firebase url');


final Firebase myData = mrf.child("info");
    myData.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(final DataSnapshot dataSnapshot) {

            x1 = dataSnapshot.getValue(String.class);
            x2 = x1; // Global variable


        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {

        }
    });

use variable 'x2' to do what you want. 使用变量“ x2”执行您想要的操作。 I don't why but there is some problem with using the same variable that was used to receive Data from Firebase. 我不为什么,但是使用用于从Firebase接收数据的相同变量存在一些问题。

Hope it work with you... 希望它与您合作...

Also if you would like the user to know that data are being retrieve you can use progressBar with Handler. 另外,如果您希望用户知道正在检索数据,则可以将proc与Bar一起使用。 After a button is clicked and 'x1' equals null do something like this: progressBar.setVisibility(View.VISIBLE); 单击一个按钮并且'x1'等于null后,请执行以下操作: progressBar.setVisibility(View.VISIBLE);

then 然后

handler.postDelayed(new Runnable() {
       public void run() {

            progressBar.setVisibility(View.GONE);
            t.setText(x2);

     }
}, 800);

Good luck.. 祝好运..

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

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