Arjun Ram
Arjun Ram

Reputation: 369

How to store a value from firebase in a global variable?

I am trying to read a value from my Firebase Database and assign it to a global variable. However, the variable always seems to be null. I checked many forums and they all say that I need to attach a 'callback' as this is an asynchronous task. Can someone help me out with the exact code?

getServerTime.setValue(ServerValue.TIMESTAMP).addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {

                    system_time = System.currentTimeMillis();
                    getServerTime.addListenerForSingleValueEvent(new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {
                            server_time_long = dataSnapshot.getValue(Long.class);




                        }

                        @Override
                        public void onCancelled(DatabaseError databaseError) {

                        }
                    });

          t1.setText(String.valueOf(server_time_long));
                }
            });

Upvotes: 2

Views: 2880

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 138824

There is no way in which you can store a value that you get from a Firebase database in global variable because the onDataChange() method is called asynchronous. This means that setText() method is called before you are trying to get the data from the database and that's why is always null.

To solve this problem, you need to move this line of code:

t1.setText(String.valueOf(server_time_long));

inside onDataChange() method. This can be done like this:

getServerTime.setValue(ServerValue.TIMESTAMP).addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {

                system_time = System.currentTimeMillis();
                getServerTime.addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        long server_time_long = dataSnapshot.getValue(Long.class);
                        t1.setText(String.valueOf(server_time_long));
                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {}
                });
            }
        });

If you want to use that value outside that method, i suggest you see my answer from this post.

Upvotes: 2

Related Questions