简体   繁体   中英

Accessing the value outside of method after initializing returning nulll in java

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? please help me在此处输入图片说明

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM