gpt4 book ai didi

java - 为什么我得到的是 null 而不是 Map 对象?如何解决这个问题?

转载 作者:行者123 更新时间:2023-11-29 05:47:38 24 4
gpt4 key购买 nike

我正在编写一个 Android 应用程序,但遇到了一个问题:我得到了一个 null 而不是 ImmutableMap 对象。看来我的 map 正在被垃圾收集。但是我创建了对它的引用。所以这里是我所有的源代码,并在评论中详细描述了问题:

//I have a BaseActivity class in which i defined nested class
//which incapsulates some REST operations
public class BaseActivity extends Activity
{
//Here is this ImmutableMap to which I want save the result
private ImmutableMap<String, Object> serverData_;

//Here is this nested class which is AsyncTask
class RestfulNetworkTasks extends AsyncTask
<Pair<String,LinkedHashMap<String, Object>>, Void, LinkedHashMap<String, Object>>
{
NetworkOperation LowLevelRestOperations_ = new NetworkOperation();
@Override
protected LinkedHashMap<String, Object> doInBackground(Pair<String,LinkedHashMap<String, Object>>... params)
{
return LowLevelRestOperations_.executeServerCommand
(params[0].getValue0(), params[0].getValue1());
}
protected void onPostExecute(LinkedHashMap<String, Object> result)
{
//Here i created a reference to the result(in order
//to save it in my data structure)
serverData_ = copyOf(result);
UpdateCurrentActivityAfterNetworkOperation();
//Here I made a test output to check if i got the result
//All is good - I got a correct result saved to serverData_
android.util.Log.d("TEST RESPONSE", "ON POST" + serverData_);
}
}//End of nested class declaration
//Here is my method in which i want to call AsyncTask and got a problem
public void Login(LinkedHashMap<String,Object> parameters)
{
//Here I create an instance of that nested AsyncTask class
RestfulNetworkTasks serverOperation_ = new RestfulNetworkTasks();
Pair<String, LinkedHashMap<String, Object>> params_ =
new Pair<String,LinkedHashMap<String,Object>>(LOGIN_COMMAND, parameters);
//Here I call AsyncTask operation - i got a correct ON POST output
//with correct data
serverOperation_.execute(params_);

//But from this point my serverData_ is null!
//And I got null in AFTER POST output!Why?serverData_ is a member of BaseActivity so
//it have to keep the result.
android.util.Log.d("TEST RESPONSE", "AFTER POST" + serverData_);
}

那么如何解决这个问题呢?为什么我的 serverData_ 在调用 execute 后为空?

我真的需要帮助 - 我对 Java 和 Android 很陌生,这个问题让我抓狂。提前致谢。

最佳答案

my serverData_ is null after calling execute?

因为 AsyncTasks 是在单个后台线程上连续执行的,而不会在 UI 线程(如线程)上等待直到线程执行未完成。

如果您想在主 ui 线程上等待,直到 AsyncTasks 计算未完成并返回结果,然后使用 AsyncTask.get() .

例子:

serverOperation_.execute(params_).get();  //<<<< 

// now u get latest value in serverData_
android.util.Log.d("TEST RESPONSE", "AFTER POST" + serverData_);

关于java - 为什么我得到的是 null 而不是 Map 对象?如何解决这个问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15246870/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com