0

我正在尝试在 gridView 中显示图像。这些图像来自对 ElasticSearch 服务器的研究。用户在文本字段中输入关键字,在 ElasticSearch 上的查询结果是字符串列表(图像的 url),图像显示在 gridView 中。

当我按下按钮进行研究时的动作:

public void sendMessage(View view){

    imgAdapter.clearmThumbIds();  //mThumbs is a list of string (urls image)

    gridView = (GridView) findViewById(R.id.grid_view);
    EditText editText = (EditText) findViewById(R.id.searchBar);
    String message = editText.getText().toString();          
    try {
        eSearchElastic.ESE(imgAdapter,message);
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println("Etape 2");
    gridView.setAdapter(imgAdapter);


}

eSearchElastic.java

public static void ESE (final ImageAdapter imgAdapter,final String keyword)throws ClientProtocolException, IOException {

AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>(){
    @Override
    protected Void doInBackground(Void... params) {

        //Build the query, connect to ElasticServer and receive a list or urls of image as answer
         System.out.println("Etape 1");
        return null;
    }

};
task.execute();}

在 Etape1 之前打印 Etape2 的结果,我希望这一行“gridView.setAdapter(imgAdapter)”仅在 eSearchElastic 的后台进程/线程完成后执行。我怎样才能做到这一点?

4

1 回答 1

1

Just call gridView.setAdapter(imgAdapter); in the onPostExecute() method inside your AsyncTask instead of calling it from sendMessage(). That is guaranteed to be called only after the doInBackground() method finishes, and will be called on the main thread, so it's safe to touch the UI.

eg:

public static void ESE (final GridView gridView, final ImageAdapter imgAdapter, final String keyword) throws ClientProtocolException, IOException {

    AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>(){
        @Override
        protected Void doInBackground(Void... params) {
            // Build the query, connect to ElasticServer and receive a list or urls of image as answer
            System.out.println("Etape 1");
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            gridView.setAdapter(imgAdapter);
        }
    };
    task.execute();
}
于 2012-11-29T00:14:38.080 回答