1

i have a firebase database and im storing a number As an index of items. I access this using my database class

public class IndexCount {
    private String Streaming;
    public IndexCount(String Streaming){
    this.Streaming = Streaming;
}

public void databaseIndexCounter( ){

    FirebaseDatabase db = FirebaseDatabase.getInstance();
    DatabaseReference dbref = db.getReference().child("Apps").child("IndexCount");
    dbref.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Integer Stream = dataSnapshot.child("Streaming").getValue(Integer.class);
            Streaming = Stream.toString();
            Log.i("streamcount: ",Streaming);
        }
    }
}

I want to access the Streaming string outside of this class and use it in my main activity to fill a textview. how can i achive this? I thought calling this from my main activity would do the trick

String streamcounter = new String();
IndexCount indexcount = new IndexCount(streamcounter);
tvstreaming = (TextView)view.findViewById(R.id.streamcount);

indexcount.databaseIndexCounter();
Log.i("stream count: ",streamcounter);
tvstreaming.setText(streamcounter);

but the log does not fire so i assume my code is wrong lol. thanks guys

1 Answer 1

2

onDataChange will be executed in another thread ( not the main thread ) , so you need to wait until it finish its work , then do what you want.

public class IndexCount {
    private String Streaming;
    public IndexCount(String Streaming){
    this.Streaming = Streaming;
}

public void databaseIndexCounter( ){

    FirebaseDatabase db = FirebaseDatabase.getInstance();
    DatabaseReference dbref = db.getReference().child("Apps").child("IndexCount");
    dbref.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Integer Stream = dataSnapshot.child("Streaming").getValue(Integer.class);
            Streaming = Stream.toString();
            Log.i("streamcount: ",Streaming);
            // call it here 
            nextStep();
        }
    }
}
public void nextStep(){
Log.i("stream count: ",streamcounter);
tvstreaming.setText(streamcounter);
}

and from your main activity

String streamcounter = new String();
IndexCount indexcount = new IndexCount(streamcounter);
tvstreaming = (TextView)view.findViewById(R.id.streamcount);

indexcount.databaseIndexCounter();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.