我正在使用countdownlatch,如下例所示。这里BackgroundDataPopulator创建一个AyncTask,它又在PackagePopulator中调用displayData。但它永远不会发生,活动也会被卡住。我在这里做错了什么。
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());
}
答案 0 :(得分:1)
目前尚不清楚您到底在做什么以及AscynTask的启动位置。看起来您在同一个线程上调用await()
和countDown()
,这就是您被阻止的原因。发布更多详细信息和/或调试代码。