我已经制作了很多项目,并且对于每个web-serve,我都会创建一个AsyncTask类。如果我想从20个web-serve获取数据,那么我必须制作20个AsyncTask类。所以这不是使用能力代码。任何人都帮我创建一个Generic AsyncTask类,所以在整个项目中我只有一个AsyncTask类,我使用该类。
public class HTTPAsyncTask extends AsyncTask<String, Void, String> {
private CallBack mCb;
HashMap<String, String> mData = null;
List<NameValuePair> mParams= new ArrayList<NameValuePair>();
String mTypeOfRequest;
String mStrToBeAppended = "";
boolean isPostDataInJSONFormat = false;
JSONObject mJSONPostData = null;
public HTTPAsyncTask(CallBack c, HashMap<String, String> data, JSONObject jsonObj, String request) {
mCb = c;
mTypeOfRequest = request;
mJSONPostData = jsonObj;
if((data != null) && (jsonObj == null)){
mData = data;
if(mTypeOfRequest.equalsIgnoreCase("GET")){
Iterator<String> it = mData.keySet().iterator();
while(it.hasNext()){
String key = it.next();
mParams.add(new BasicNameValuePair(key, mData.get(key)));
}
for (int i = 0; i<mParams.size()-1; i++){
mStrToBeAppended+= "?" + mParams.get(i).getName() + "=" + mParams.get(i).getValue() + "&";
}
//add the last parameter without the "&"
mStrToBeAppended+= "?" + mParams.get(mParams.size()-1).getName() + "=" + mParams.get(mParams.size()-1).getValue();
}
if(mTypeOfRequest.equalsIgnoreCase("POST")){
Iterator<String> it = mData.keySet().iterator();
while(it.hasNext()){
String key = it.next();
mParams.add(new BasicNameValuePair(key, mData.get(key)));
}
}
}
if ((mData == null) && (jsonObj != null)){
isPostDataInJSONFormat = true;
}
}
@Override
protected String doInBackground(String... baseUrls) {
publishProgress(null);
if(mTypeOfRequest.equalsIgnoreCase("GET")){
String finalURL = baseUrls[0]+ mStrToBeAppended;
return HttpUtility.GET(finalURL);
}
if (mTypeOfRequest.equalsIgnoreCase("POST")){
if(isPostDataInJSONFormat == false){
return HttpUtility.POST(baseUrls[0],mParams );
}
else {
return HttpUtility.POST(baseUrls[0], mJSONPostData);
}
}
return null;
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(String result) {
mCb.onResult(result);
}
@Override
protected void onProgressUpdate(Void...voids ) {
mCb.onProgress();
}