请求的回调示例


GetCityListByProvinceTask getCityTask = new GetCityListByProvinceTask( context, province_id, isNoAny, isNolyShowStore, new GetCityListResultListener() { @Override public void showResult(boolean isSucc, String errorMsg, BaseModel baseModel) { //请求返回相应处理 ... } @Override public void onPreExecute() { // TODO Auto-generated method stub } }); getCityTask.execute();

参数可自行约定

package cn.car273.task;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.AsyncTask;
import cn.car273.BuildConfig;
import cn.car273.R;
import cn.car273.exception.Car273Exception;
import cn.car273.http.HttpToolkit;
import cn.car273.manager.OtherCarDataMgr;
import cn.car273.model.BaseModel;
import cn.car273.model.City;
import cn.car273.util.Utils;
import cn.car273.util.log.Log;

/**
 * 获取城市信息列表接口
 * 
 * @author hquspring@gmail.com
 */
public class GetCityListByProvinceTask extends AsyncTask<Void, Void, Boolean> {

    /** 返回的错误消息 */
    private String error = "";

    /** 请求是否成功 */
    private boolean isSucc = false;

    /** 任务执行回调 */
    private GetCityListResultListener listener;

    /** 关联上下文 */
    private Context context;

    /** 提交的数据 */
    private ArrayList<NameValuePair> postParams;

    /** 返回的数据模型 */
    private BaseModel baseModel;

    /**
     * 上传数据实体类
     */
    private int province_id;

    private boolean mInterrupt = false;

    private ProgressDialog mProgressDlg = null;

    /** 不显示 “不限” item ,true不显示“不限” */
    private boolean isNoAny = false;

    /** 是否只显示有门店的城市 */
    private boolean storeCity = false;

    /**
     * @param context
     * @param province_id 省份id
     * @param isNoAny 不显示 “不限” item ,true不显示“不限”
     * @param storeCity 是否只显示有门店的城市 ,true只显示有门店的城市
     * @param listener 回调监听
     */

    public GetCityListByProvinceTask(Context context, int province_id, boolean isNoAny,
            boolean storeCity, GetCityListResultListener listener) {
        this.context = context;
        this.listener = listener;
        this.province_id = province_id;
        this.isNoAny = isNoAny;
        this.storeCity = storeCity;
        postParams = new ArrayList<NameValuePair>();
    }

    @Override
    protected Boolean doInBackground(Void... params) {
        // 网络判断
        // 网络判断

        try {
            postParams.add(new BasicNameValuePair("p_id", province_id + ""));

            String data = null;
            if (!Utils.CheckNetworkConnection(context)) {
                data = context.getString(R.string.networkerror);
                return false;
            }

//请求数据结果 data
= OtherCarDataMgr.getCityList(context, postParams); BaseModel baseModel = parserJson(data); Log.out("请求城市列表结果=========:" + data); if (data.equals(HttpToolkit.TIMEOUT)) { isSucc = false; return isSucc; } // if(new JSONObject(data).has("errorCode") && (!new // JSONObject(data).optString("errorCode").equals("0") && !new // JSONObject(data).optString("errorCode").equals("1"))){ // isSucc = false; // if(new JSONObject(data).has("errorMessge")){ // error = new JSONObject(data).optString("errorMessge"); // } // return isSucc; // } // evModel = new PriceEvaluateRequest().parse(new JSONObject(data)); // 信息处理正常,说明提交正常 isSucc = true; } catch (Car273Exception e) { e.printStackTrace(); error = e.getMessage(); } catch (Exception e) { e.printStackTrace(); error = context.getString(R.string.accident); } return isSucc; } public interface GetCityListResultListener { /** * 结果展示 * * @param isSucc true表示成功,false表示失败 * @param errorMsg 需要显示的错误信息 * @param priceAssessModel 评估结果 */ public void showResult(boolean isSucc, String errorMsg, BaseModel baseModel); /** * 线程执行前的操作 */ public void onPreExecute(); } public void onCancel() { mInterrupt = true; cancel(true); dismissProgressDlg(); } @Override protected void onCancelled() { mInterrupt = true; dismissProgressDlg(); super.onCancelled(); } @SuppressLint("NewApi") @Override protected void onCancelled(Boolean result) { mInterrupt = true; dismissProgressDlg(); super.onCancelled(result); } @SuppressLint("NewApi") @Override protected void onPostExecute(Boolean result) { dismissProgressDlg(); if (!mInterrupt && listener != null) { listener.showResult(isSucc, error, baseModel); } } @Override protected void onPreExecute() { String message = context.getString(R.string.loading_getcityList); mProgressDlg = ProgressDialog.show(context, null, message); mProgressDlg.setCancelable(true); mProgressDlg.setCanceledOnTouchOutside(false); mProgressDlg.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { mInterrupt = true; cancel(true); } }); listener.onPreExecute(); } private void dismissProgressDlg() { if (mProgressDlg != null) { mProgressDlg.dismiss(); } }
//数据解析
public BaseModel parserJson(String paramString) throws Car273Exception { baseModel = new BaseModel(); ArrayList<City> cityList = new ArrayList<City>(); Comparator<City> comparator = new Comparator<City>() { @Override public int compare(City s1, City s2) { return s1.getSpell().compareTo(s2.getSpell()); } }; try { JSONObject jsonObj = new JSONObject(paramString); if (jsonObj.has("errorCode")) { baseModel.setErrorCode(jsonObj.optString("errorCode")); } if (jsonObj.has("errorMessge")) { baseModel.setErrorMessge(jsonObj.optString("errorMessge")); } if (jsonObj.has("data")) { JSONArray infoArray = jsonObj.getJSONArray("data"); System.out.println("infoArray======" + infoArray.toString()); if (BuildConfig.DEBUG) { Log.out("一共有:" + infoArray.length()); } for (int i = 0; i < infoArray.length(); i++) { City city = new City(); JSONObject json = infoArray.getJSONObject(i); if (json.has("id")) { city.setId(Integer.parseInt(json.getString("id"))); } if (json.has("name")) { city.setName(json.getString("name")); } if (json.has("dept_num")) { city.setDept_num(Integer.parseInt(json.getString("dept_num"))); } if (json.has("full_spell")) { city.setSpell(json.getString("full_spell")); } if (storeCity) { if (city.getDept_num() > 0) {// 只显示有门店的市 cityList.add(city); } } else { cityList.add(city); } } } Collections.sort(cityList, comparator); if (!isNoAny) { cityList.add(0, new City(0, "不限", null)); } } catch (JSONException e) { System.out.println("解析城市列表信息出错啦!!!"); Car273Exception ce = new Car273Exception(e); throw ce; } // 按首字母排序 baseModel.setData(cityList); return baseModel; } }

留个笔记,仅作笔记。

posted @ 2015-02-12 10:45  寡蛋  阅读(253)  评论(0)    收藏  举报