1
我在下面的例子中使用了countdownlatch。這裏BackgroundDataPopulator創建一個AyncTask,它依次調用PackagePopulator中的displayData。但它從來沒有發生過,活動卡住了。我在這裏做錯了什麼。在android中的CountDownLatch問題
public class PackagePopulator implements ServerDataProcessor {
private CountDownLatch counter=new CountDownLatch(1);
String[] packages;
public void getPagesFromServer() {
new BackgroundDataPopulator(IMgrApplication.getAppContext().getString(R.string.list),new PData(),this).execute();
}
public String[] getPages() {
try {
counter.await();
} catch (InterruptedException e) {
packages=new String[0];
}
return packages;
}
@Override
public void displayData(ServerOutput output) {
Page[] pgArray = new Page[((PageData)output).getPages().size()];
pages=new String[pgArray.length];
pgArray = ((PageData)output).getPages().toArray(pgArray);
for(int i=0;i<pgArray.length;i++){
pages[i]=pgArray[i].getName();
}
counter.countDown();
}
}
public class BackgroundDataPopulator extends AsyncTask<Void, String, ServerOutput> {
// connector=new JSONConnector();
Connector connector;
String curUrl;
ServerOutput curServerOutput;
ServerDataProcessor processor;
public BackgroundDataPopulator(String url, ServerOutput serverOutput,ServerDataProcessor curProcessor) {
//connector = new UnitTestConnector();
connector = new JSONConnector();
curUrl = url;
curServerOutput = serverOutput;
processor=curProcessor;
}
@Override
protected ServerOutput doInBackground(Void... params) {
return connector.getData(URLUtils.getFormattedUrl(curUrl),curServerOutput);
}
@Override
protected void onPostExecute(ServerOutput output) {
processor.displayData(output);
//Toast.makeText(BaseFragmentActivity.this, "Done!",Toast.LENGTH_SHORT).show();
}
}
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
pagePopulator=new PagePopulator();
pagePopulator.getPagesFromServer();
super.onCreate(savedInstanceState);
}
public ArrayAdapter<CharSequence> getSpinnerDataArray(String item) {
return new ArrayAdapter<CharSequence>(this,android.R.layout.simple_spinner_item,pagePopulator.getPages());
}
我修改了一些代碼來爲backgroundtask添加執行。但要回答你的問題,displayData正在通過onCreate方法創建的AsyncTask線程調用 – sab
誰和何時調用'PackagePopulator.getPages()'? –
這是由使用PackagePopulator從服務器獲取數據的活動調用的,我編輯了上面的代碼 – sab