-2

im getting a string from callback and storing in a variable call channel. it's fine now but when accessing the value outside the callback method it returns null why? it's not accessable outside of that method. callback is working fine while inside of callback method but i please help me enter image description here

  ch = new Channel(fuser.getUid(),userid);
       ch.getChann();
      ch.Back(new Channel.MyCallback() {
          @Override
          public void onCallback(String value) {
              channel = value;
              Log.e("Channel",channel);
          }
      });
        channel+="1";
        Log.e("Channel1",channel);
  • I'm surprised this even compiles. Because to use a variable defined outside an anonymous class inside an anonymous class [it must be final or effectively final](https://stackoverflow.com/questions/4732544/why-are-only-final-variables-accessible-in-anonymous-class). Reassigning your channel variable inside your anonymous class should therefor throw a compile time error. The only possible explanation i have is that you `Channel.MyCallback` itself has a accessable field called `channel` and that `channel = value` refers to that local field instead. – OH GOD SPIDERS Nov 10 '21 at 16:37

1 Answers1

0

unfortunately, there's not all text visible on your screenshot. On Stackoverflow, it's generally preferred if you paste the source code directly into your question rather than sharing a screenshot. It's a bit more effort, at the same time, please consider that the people answering your question also take effort to help you - and by posting the source code as text, you make it easier for everyone to help you.

For your question, there's a couple of things that might happen:

  • the callback is never called - and therefore there's nothing written into that variable
  • the callback is not called immediately, but later (maybe by another thread). Therefore, you will find that the variable will not be set immediately after you pass that callback to the Back method, but maybe a few seconds or milliseconds later. That's a long time for a computer, so when you access the variable later, you might just be too early.
  • if there's threads involved, your code is not thread save. That means - it might also happen that channel=value and channel+="1" might happen at the same time, which could give you unpredictable results.

To solv the problem, you will need to trigger whatever action should happen after your callback at a time when you know that the callback has been called. I am no expert on Android; there might be listeners available for that. If not, then the simplest way would be to call the code that should happen after the callback was called from the callback itself (be aware, that this is most likely a bad practise in android as it might make the UI become unresponsive. To solve that, you will need to execute your code on a different thread than the UI thread)

Matthias
  • 2,622
  • 1
  • 18
  • 29