我有一个包含多个项目的 Listview,每个项目都有 2 个按钮。我想要做的是当我点击一个按钮时,它会通过 HttpPost 向服务器发送一些数据。我在我的 Adapter.getView() 中放置了一个线程,但它不起作用,因为适配器在异步线程中已经存在。你知道我怎样才能让它工作吗?
我的列表视图:
// ... OnCreate ListView ...
// ... new ListAppTask().execute();
// ...
public class ListAppTask extends AsyncTask<Void, Void, List<ProductExtended>> {
protected List<ProductExtended> doInBackground(Void... args) {
Product product = new Product();
List<ProductExtended> products = product.getLastProducts(getApplicationContext());
return products;
}
protected void onPostExecute(List<ProductExtended> result) {
data.addAll(result);
adapter.notifyDataSetChanged();
if (progressDialog != null) {
progressDialog.dismiss();
progressDialog = null;
}
}
}
我的适配器:
public class PackageAdapter extends BaseAdapter {
private List<ProductExtended> data;
private Context context;
public PackageAdapter(Context context, List<ProductExtended> data) {
this.context = context;
this.data = data;
}
@Override
public int getCount() {
return data.size();
}
@Override
public ProductExtended getItem(int position) {
return data.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ProductExtended item = getItem(position);
ViewHolder holder;
if (convertView == null) {
LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = li.inflate(R.layout.package_row, parent, false);
holder = new ViewHolder();
holder.btnBa = (LinearLayout) convertView.findViewById(R.id.idBonneaffaire);
holder.btnJl = (LinearLayout) convertView.findViewById(R.id.idJelai);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.btnBa.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
new Thread() {
@Override
public void run() {
// ---------------- PROBLEM HERE -------------------
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("My URL");
// Execute HTTP Post Request
try {
HttpResponse response = httpclient.execute(httppost);
String reponse = EntityUtils.toString(response.getEntity());
} catch (UnknownHostException e) {
} catch (HttpHostConnectException e) {
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
}
}.start();
}
});
// Same for the second LinearLayout considered as Button
return convertView;
}
static class ViewHolder {
LinearLayout btnBa;
LinearLayout btnJl;
}
并显示错误:
Only the original thread that created a view hierarchy can touch its views. adapter
谢谢,阿克拉姆