我正在尝试在gridView中显示图像。这些图像来自对ElasticSearch服务器的研究。用户在文本字段中提供关键字,ElasticSearch上的查询结果是字符串列表(图像的网址),图像显示在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的后台进程/线程完成后执行。 我怎样才能做到这一点?
答案 0 :(得分:1)
只需在gridView.setAdapter(imgAdapter);
内的onPostExecute()方法中拨打AsyncTask
,而不是从sendMessage()
调用doInBackground()
。保证仅在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();
}
方法完成后调用,并且将在主线程上调用,因此触摸UI是安全的。
例如:
{{1}}