[英]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.