0

How do I get the data from firebase and then store in a global variable, or in any case store it to use in different functions.

public GarbageItems(int itemNum) {
    String itemId = String.valueOf(itemNum);

    database = FirebaseDatabase.getInstance();
    gameObjectRef = database.getReference().child("gameObjects");

    itemInformationGrabber(gameObjectRef, itemId);

  }//GarbageItems(Constructor)


private void itemInformationGrabber(DatabaseReference gameObjectRef, String itemId) {
    DatabaseReference dataReference = gameObjectRef.child(itemId);

    DatabaseReference itemColor = dataReference.child("Color");
    itemColor.addValueEventListener(new ValueEventListener() {
      @Override
      public void onDataChange( DataSnapshot dataSnapshot) {
        String color = dataSnapshot.getValue(String.class);
        setColor(color);
      }

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

      }
    });
  }

This is in a different classes that calls GarbageItem

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_game);
    colorTextView = findViewById(R.id.ColorTextView);
    itemTextView = findViewById(R.id.ItemNameTextView);

    GarbageItems garbageItems = new GarbageItems(1);
    Color =  garbageItems.getColor(); //this value returns null

  }

Here is my database schema enter image description here

Terry
  • 63,248
  • 15
  • 96
  • 118
  • maybe [this](https://stackoverflow.com/questions/57330766/how-to-get-data-from-any-asynchronous-operation-in-android) – a_local_nobody Jan 13 '20 at 06:58
  • Please check the duplicate to see why do you have this behavior and how can you solve this using a custom callback. – Alex Mamo Jan 13 '20 at 10:08

1 Answers1

0

You can store it in shared preferences or database

Ilia Kuzmin
  • 165
  • 8