1

我正在使用 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());
}
4

1 回答 1

1

目前尚不清楚您到底在做什么以及 AscynTask 的启动位置。看起来您正在调用await()并且countDown()在同一个线程上,这就是您被阻止的原因。发布更多详细信息和/或调试您的代码。

于 2012-05-21T03:02:55.073 回答