简体   繁体   中英

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. 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. 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. 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. I don't why but there is some problem with using the same variable that was used to receive Data from 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. After a button is clicked and 'x1' equals null do something like this: progressBar.setVisibility(View.VISIBLE);

then

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

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

     }
}, 800);

Good luck..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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