问题描述
好的,现在我有 Class A
包含一些微调器,这些值将由 Class B
填充,扩展 AsnycTask
抓取微调器来自 Web 服务的值.在 B 类中,我设法检索值,显示在 Toast 中.现在的问题是如何将这些微调器值传递回 A 类?
Ok so now I have Class A
that contains some spinners that values will be populated by Class B
that extends AsnycTask
which grabs the spinner values from a web service. In class B i manage to retrieve the values, showing in a Toast. The problem now is how do I pass those spinner values back to Class A?
我试过了
AsyncTask 中的 OnPostExcecute 方法可以返回值吗?
通过将 Class A
传递给 Class B
并将值存储在 Class A
的公共变量中,如下所示
by passing Class A
to Class B
and store the value in a public variable of Class A
like below
@Override
protected void onPostExecute(String result)
{
classA.classAvariable = result;
}
然而,每当我尝试读取 classAvariable
时,我总是得到一个 NullPointer Exception
.似乎变量从未分配过结果.出于可读性目的,我需要将 Class B
分开,而不是用作内联类.
However whenever I try to read the classAvariable
i always get a NullPointer Exception
.Seems like the variable was never assigned with the result.For readability purpose I needed to seperate Class B
instead of using as an inline class.
我的 Java 程序员同胞有什么想法吗?
Any ideas my fellow Java programmers?
推荐答案
我猜您是在尝试在设置 A 类变量之前读取它..尝试使用回调来做到这一点..在回调函数中传递值并刷新您的微调器..
I guess you are trying to read class A variable before it is being set..Try to do it using callbacks..in the callback function pass the values and refresh your spinners..
您可以创建interface
,将其传递给AsyncTask
(在构造函数中),然后在onPostExecute
You can create interface
, pass it to AsyncTask
(in constructor), and then call method in onPostExecute
例如:
您的界面:
public interface OnTaskCompleted{
void onTaskCompleted(values);
}
您的活动:
public YourActivity implements OnTaskCompleted{
//your Activity
YourTask task = new YourTask(this); // here is the initalization code for your asyncTask
}
还有你的 AsyncTask:
And your AsyncTask:
public YourTask extends AsyncTask<Object,Object,Object>{ //change Object to required type
private OnTaskCompleted listener;
public YourTask(OnTaskCompleted listener){
this.listener=listener;
}
//required methods
protected void onPostExecute(Object o){
//your stuff
listener.onTaskCompleted(values);
}
}
这篇关于从 AsyncTask 类的 onPostExecute 方法返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!