Interface callback encapsulation and callback Encapsulation

Source: Internet
Author: User

Interface callback encapsulation and callback Encapsulation

  

 

During the development process, I found two problems regarding the processing of request callback data and message prompts:

1. I don't know what others do, but I have seen that many people directly write or directly use a third-party network framework when writing network requests, when you get the data, you usually use the agreed key in the returned data to parse the data you need and directly use or convert the data to a javaBean or array. In other words, this is very troublesome, isn't it? Every time the request data is parsed, how much code should be repeatedly written on different pages, and it looks messy.

2. In many cases, if a Data Request succeeds or fails, a brief prompt is always given to the user. It is also a very troublesome question to prompt what kind of text and under what circumstances it should be prompted.

To this end, I have encapsulated the request callback, and the code structure is much clearer and easy to use. It mainly implements the following functions:

1. if the returned data is a javaBean or Array, you only need to pass the corresponding data type and JavaBean in the CallBack at the request. class. After successful data callback, you can directly convert the returned Object to the corresponding JavaBean. class Object or Array object. Of course, if only a simple data type is returned, you do not need to set anything. You can directly use the returned String data.

2. no matter whether the CallBack succeeds or fails, if a prompt is displayed, a Context object is directly transmitted in the CallBack at the request. If you do not need a prompt, do not upload it. If you want to customize the prompt content, do not upload it, in the onSuccess and onFailure methods corresponding to CallBack, the desired content is displayed.

 

  If you don't talk much about it, go to the Code directly ~

 

1. The message is not prompted. I will use the interface for obtaining the verification code as an example.

1. the prompt message is not displayed.

A. Initiate a request

ApiClient.getVerificationCode(phone,new VerificationCodeCallback());

B. Data callback

// Get verification code callback public class VerificationCodeCallback extends ApiUiCallback {@ Override public void onFailure (HttpException e, String s) {super. onFailure (e, s) ;}@ Override public void onSuccess (String data, int resultCode, String resultInfo, Object outDo) {super. onSuccess (data, resultCode, resultInfo, outDo); if (resultCode = 0) {// TODO }}}

You can customize the prompt content by yourself. In the onSuccess and onFailure methods corresponding to CallBack, the content you want is displayed.

 

2. A message is displayed.

A. Initiate a request

ApiClient.getVerificationCode(phone,new VerificationCodeCallback(this));

B. Data callback

// Get verification code callback public class VerificationCodeCallback extends ApiUiCallback {public VerificationCodeCallback (Context context) {super (context) ;}@ Override public void onFailure (HttpException e, String s) {super. onFailure (e, s) ;}@ Override public void onSuccess (String data, int resultCode, String resultInfo, Object outDo) {super. onSuccess (data, resultCode, resultInfo, outDo); if (resultCode = 0) {// TODO }}}

 

If it is automatically popped up, implement the constructor VerificationCodeCallback (Context context) in the callback class and pass a Context when using it.

 

2. Array or single JavaBean returned data

Method description:

SetOutClass () is passed as the data entity class in the array.
In setResponseTypeEnum (), whether the data type is a single JavaBean or Array

1. Return Array

A. Initiate a request

        ApiClient.openCityList(new OpenCityListCallback().setOutClass(String.class).setResponseTypeEnum(ResponseTypeEnum.JSON_ORIGINAL_RESULT_ARRAY));
 

B. Data callback

public class OpenCityListCallback extends ApiUiCallback {        @Override        public void onFailure(HttpException e, String s) {            super.onFailure(e, s);            showToast(R.string.network_anomaly);        }        @Override        public void onSuccess(String data, int resultCode, String resultInfo, Object outDo) {            super.onSuccess(data, resultCode, resultInfo, outDo);            if (outDo instanceof List) {                List<String> list = (List<String>) outDo;                // TODO            } else {                showToast(resultInfo);            }        }    }

 

2. Returns a singleJavaBean

A. Initiate a request

        ApiClient.checkNewVersion(new CheckNewVersionCallback().setResponseTypeEnum(ResponseTypeEnum.JSON_ORIGINAL_RESULT_BEAN).setOutClass(UpdateInfo.class));

 

B. Data callback

 

public class CheckNewVersionCallback extends ApiUiCallback {        @Override        public void onFailure(HttpException e, String s) {            super.onFailure(e, s);        }        @Override        public void onSuccess(String data, int resultCode, String resultInfo, Object outDo) {            super.onSuccess(data, resultCode, resultInfo, outDo);            if (resultCode == 0) {                if (outDo instanceof UpdateInfo) {                    updateInfo = (UpdateInfo) outDo;                    // TODO                }            }        }    }

 

Let alone the source code !!!!

1. Main directory structure

 

2. ApiConstant. class

/*** Created by ding on 2016/9/26 */public class ApiConstant {/*** Character Set: UTF-8 */public static final String CHARSET_UTF8 = "UTF-8 "; /*** default Character Set */public static final String DEFUALT_CHARSET = CHARSET_UTF8 ;}

3. ResponseTypeEnum. class

/*** Return the data type constant * Created by ding on 2016/9/26. */public enum ResponseTypeEnum {/*** JSON format string; * The basic type is output in JSON format as is; * The data content is encapsulated into the data attribute of the Result object, and then the JSON Format String is output; * data is a common JavaBean; */JSON_ORIGINAL_RESULT_BEAN ("json_orig_result", true, false),/*** JSON format string; * Basic types are output in JSON format as is; * data is encapsulated into the data attribute of the Result object, and a JSON string is output. * data is a JsonArray set. */JSON_ORIGINAL_RESULT_ARRAY ("json_orig_result", true, true ), /*** native STRING; */string ("String", false, false); private STRING rtType; // The returned data type is private boolean isJson; // whether the returned data is in the JSON format private boolean isArray; // whether the returned data is in the JSON set private ResponseTypeEnum (String rtType, boolean isJson, boolean isArray) {this. rtType = rtType; this. isJson = isJson; this. isArray = isArray;} public String getRtType () {return rtType;} public boolean isArray () {return isArray;} public boolean isJson () {return isJson ;}}

 

4. ApiConvert. class

/*** Created by ding on 2016/9/26 * convert layer Conversion Tool class * provides the conversion methods for jsonData and outputDo */public class ApiConvert {private static final String TAG = "api. apiConvert "; /*** convert byte array data in json format to a business JavaBean Instance Object ** @ param jsonData JSON format String * @ param outClass business JavaBean class information * @ return Object business JavaBean instance Object corresponding to outClass */public static Object jsonToOutputDO (String jsonData, responseTypeEnum responseType, linoleic Ss <?> OutClass) {if (outClass = null) | TextUtils. isEmpty (jsonData) {LogUtil. logE (ApiConvert. class, "outClass is null or jsonData is blank. "); return null;} try {if (responseType! = Null) & responseType. isJson () {if (responseType. isArray () {return JSON. parseArray (jsonData, outClass);} else {return JSON. parseObject (jsonData, outClass) ;}} else {return jsonData ;}} catch (Throwable e) {LogUtil. logE (ApiConvert. class, "[jsonToOutputDO] invoke JSON. parseObject error. ") ;}return null ;}}

 

5. ApiUiCallback. class

 

/*** Created by ding on 2016/9/26. */public abstract class ApiUiCallback extends RequestCallBack <String> {protected Context mContext = null; private ResponseTypeEnum responseTypeEnum = null; private Class <?> OutClass = null; private String reqContent; // public ApiUiCallback () {this. mContext = null;} public ApiUiCallback (Context context) {this. mContext = context;} public ApiUiCallback (int rate) {super (rate); this. mContext = null;} public ApiUiCallback (Object userTag) {super (userTag); this. mContext = null;} public ApiUiCallback (int rate, Object userTag) {super (rate, userTag); this. mContext = nu Ll;} public ApiUiCallback setResponseTypeEnum (ResponseTypeEnum responseTypeEnum) {this. responseTypeEnum = responseTypeEnum; return this;} public ApiUiCallback setOutClass (Class <?> OutClass) {this. outClass = outClass; return this;} public ApiUiCallback setReqContent (String reqContent) {this. reqContent = reqContent; return this;} public String getReqContent () {return reqContent;} @ Override public void onSuccess (ResponseInfo <String> responseInfo) {String json = CommonUtil. fromtoJson (responseInfo. result); LogUtil. logE (ApiUiCallback. class, "ApiUiCallback ---> onSuccess"); I F (null! = Json) {JSONObject object = JSON. parseObject (json, JSONObject. class); int resultCode = object. getInteger ("resultCode"); String resultInfo = object. getString ("resultInfo"); String jsonData = object. getString ("data"); if (mContext! = Null) {ToastTools. showToast (mContext, resultInfo);} Object outDO = ApiConvert. extends (jsonData, responseTypeEnum, outClass); onSuccess (jsonData, resultCode, resultInfo, outDO) ;}} public void onSuccess (String data, int resultCode, String resultInfo, Object outDo) {}@ Override public void onFailure (HttpException e, String s) {LogUtil. logE (ApiUiCallback. class, "ApiUiCallback ---> onFailur E "); if (mContext! = Null) {ToastTools. showToast (mContext, "request failed ");}}}

 

 

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.