[英]How to assign global variables with AsyncTask
在这里,我给出了一个有关全局变量和AsyncTasks所面临问题的小示例。 我已经从文件中读取数据并将数据分配给字符串,然后在onPostExecute()方法中将该字符串分配给了全局变量。 但是,当我为TextView分配“ aString”变量时,输出仍然是“无”。
我知道,如果您在onPostExecute()方法中执行TextView分配,那么它可以工作,但是如果我想在AsyncTask之外的方法中使用数据该怎么办。
有人可以帮忙吗,我想我没有得到什么?
public class GoodAsync extends Activity{
TextView tv;
String aString = "nothing";
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.asynctasks);
new AsyncTasker().execute();
tv = (TextView) findViewById(R.id.async_view);
tv.setText(aString);
}
private class AsyncTasker extends AsyncTask<String, Integer, String>{
@Override
protected String doInBackground(String... arg0) {
AssetManager am = GoodAsync.this.getAssets();
String string = "";
try {
// Code that reads a file and stores it in the string variable
return string;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
aString = result;
}
}
}
也许您想这样做:
public class GoodAsync extends Activity{
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.asynctasks);
tv = (TextView) findViewById(R.id.async_view);
new AsyncTasker().execute();
}
public void setTextView (String text) {
tv.setText(text);
}
private class AsyncTasker extends AsyncTask<String, Integer, String>{
....
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
setTextView(result);
}
}
}
您确定您的AsyncTask及时执行吗?
例如,您正在这样做:
new AsyncTasker().execute();
tv = (TextView) findViewById(R.id.async_view);
tv.setText(aString);
这使任务继续进行,但随后立即将TextView的值设置为aString变量。
此时AsyncTask最有可能仍在执行,因此在代码执行后,aString仅获得“ nothing”以外的值。
您不必等待异步任务完成..您可以这样做。
new AsyncTasker().execute().get();
tv = (TextView) findViewById(R.id.async_view);
tv.setText(aString);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.