简体   繁体   English

在java中初始化返回nulll后访问方法外的值

[英]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?现在很好,但是当访问回调方法之外的值时,它返回 null 为什么? 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.在 Stackoverflow 上,如果您将源代码直接粘贴到您的问题中而不是共享屏幕截图,则通常是首选。 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.因此,您会发现在将该回调传递给 Back 方法后不会立即设置该变量,而是可能在几秒钟或几毫秒后设置。 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.这意味着 - channel=valuechannel+="1"也可能同时发生,这可能会给您带来不可预测的结果。

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;我不是 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)如果没有,那么最简单的方法是在从回调本身调用回调之后调用应该发生的代码(请注意,这很可能是 android 中的一种不好的做法,因为它可能会使 UI 变得无响应。要解决也就是说,您需要在与 UI 线程不同的线程上执行代码)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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