Multithreading 使用线程和异步任务
我是android新手,在异步任务和线程方面有问题。 如何在此代码中使用AsyncTask? 当我像这样使用productIdList时,它是空的。这就是为什么我要使用AsyncTask。我认为使用AsyncTask可以工作 提前谢谢Multithreading 使用线程和异步任务,multithreading,android-asynctask,Multithreading,Android Asynctask,我是android新手,在异步任务和线程方面有问题。 如何在此代码中使用AsyncTask? 当我像这样使用productIdList时,它是空的。这就是为什么我要使用AsyncTask。我认为使用AsyncTask可以工作 提前谢谢 public ArrayList<String> getProductData() { final ArrayList<String> productIdList = new ArrayList<String>();
public ArrayList<String> getProductData() {
final ArrayList<String> productIdList = new ArrayList<String>();
new Thread(new Runnable() {
public void run() {
HttpClient httpclient= new DefaultHttpClient();
GeneralConstans GC = new GeneralConstans();
// Products will be stated in memory
HttpPost httpget = new HttpPost(GC.UrlConstants);
HttpResponse response;
String result = null;
try {
HttpContext ctx = new BasicHttpContext();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
2);
httpget.setEntity(new UrlEncodedFormEntity(nameValuePairs,
"UTF-8"));
response = httpclient.execute(httpget, ctx);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
result = EntityUtils.toString(resEntity);
JSONArray arr = new JSONArray(result);
Gson gson = new Gson();
if (arr.length() > 0) {
for (int j = 0; j < arr.length(); j++) {
Product p = gson.fromJson(arr.getString(j),
Product.class);
productIdList.add(p.toString());
}
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (SocketException e) {
/*if (checkAbortStatus(e.getMessage()) == true) {
handler.sendEmptyMessage(0);
}*/
} catch (IOException e) {
/*if (checkAbortStatus(e.getMessage()) == true) {
handler.sendEmptyMessage(0);
}*/
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
}
};
}).start();
return productIdList;
public ArrayList getProductData(){
最终ArrayList productIdList=新ArrayList();
新线程(newrunnable()){
公开募捐{
HttpClient HttpClient=新的DefaultHttpClient();
GeneralConstans GC=新的GeneralConstans();
//产品将在内存中声明
HttpPost httpget=新的HttpPost(GC.urlstants);
HttpResponse响应;
字符串结果=null;
试一试{
HttpContext ctx=新的BasicHttpContext();
List name valuepairs=new ArrayList(
2);
httpget.setEntity(新的UrlEncodedFormEntity(nameValuePairs,
“UTF-8”);
response=httpclient.execute(httpget,ctx);
HttpEntity当前性=response.getEntity();
if(最近性!=null){
结果=EntityUtils.toString(最近性);
JSONArray arr=新JSONArray(结果);
Gson Gson=新的Gson();
如果(阵列长度()>0){
对于(int j=0;j
异步任务隐式地将方法和命令从主线程移开,因为主线程应该运行所有任务
创建一个新类
public class <NAME OF CLASS> extends AsyncTask<Void, String, String>
public类扩展异步任务
extends部分基本上扩展(在c#中继承)了一些参数,这些参数与您将要使用的3个重写方法相关