0

Hi everyone I need help with this part of my java code

public void getMydata() {
    
    String B;
    databaseAds= FirebaseDatabase.getInstance().getReference().child("AdmbAd");
    databaseAds.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            String myBannerID = snapshot.child("bannerId").getValue().toString();
            

        }

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

        }
    });
}

the question is how can modify this code to be able affect the value of myBannerID that I get from the server ( in onDataChange Method) to the String B located out of this method?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807

2 Answers2

0

Since the call you are making is asynchronous you could set a callback function in your getMyData method with the java.lang.reflect.Method

public void getMydata(Method method) {
    
    String B;
    databaseAds= FirebaseDatabase.getInstance().getReference().child("AdmbAd");
    databaseAds.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            String myBannerID = snapshot.child("bannerId").getValue().toString();
            method(myBannedId);
        }

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

        }
    });
}

The way you invoke a Method Object is

Method callbackMethod = Main.class.getMethod("callback", parameterTypes[0]);
Dharman
  • 30,962
  • 25
  • 85
  • 135
0

You will not be able to modify a local variable from a callback

Whatever you're doing with your B string, you'll need to do it inside the onDataChange method

Beware, also, that addValueEventListener is an async process so if you write something like

public void getMydata() {
    
    System.out.println("1");
    databaseAds= FirebaseDatabase.getInstance().getReference().child("AdmbAd");
    databaseAds.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            System.out.println("2");
        }

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

        }
    });
    System.out.println("3");
}

it's quite likely to happen that the output is

1
3
2
Alberto S.
  • 7,409
  • 6
  • 27
  • 46