Android Rapid Development appbase--(5). Use of Basepresenter

Source: Internet
Author: User

Android Rapid Development appbase--(5). Use of Basepresenter
Presenter是来自MVP中的概念,是用来处理与用户交互的逻辑。在这里更加简单化,Presenter中的方法是根据业务来定义,比如获取消息列表,那么业务常常会这样:先去请求网络,网络正常请求到数据返回并展示在UI层,网络错误没有拿到数据,看看缓存中有没有,然后从缓存中拿到数据并返回并展示在UI层;突然,有一天业务需求发生变化,只允许获取网络,网络错误UI上显示没有消息。如果之前在UI层已经做过数据为空的处理,那么UI层就不用修改任何代码,仅仅只需要修改presenter层,这样就将UI层和业务层区分,并且耦合降低了。
1. Overview

Basepresenter is just a concept of extraction, there are many ways to implement, here I use the callback mechanism, presenter and callback methods are corresponding to the existence, such as presenter in Getproductsbytype ( int type), then this method topic asynchronously processes the data and passes the data back to Setproductsbytype (Object result) after processing is complete.

class or interface presenter Callback
Method Getproductsbytype (int type) Setproductsbytype (Object result)
Execute the Thread Non-UI threads UI thread
2. Code
 PackageCom.snicesoft.presenter;ImportAndroid.content.Context;ImportCom.snicesoft.util.NetworkUtil; Public  class basepresenter<C extends basepresenter. Callback> {     Public  interface Callback {}PrivateContext context;protectedC callback; Public void Setcallback(C callback) { This. callback = callback; } Public Basepresenter(Context context) { This. Context = Context; } Public Boolean Isnetconnect() {returnNetworkutil.isconnect (GetContext ()); } PublicContextGetContext() {returnContext }}
    • The code uses the internal interface definition, in order to reduce the overall style of code is not so bloated. Of course, you can also customize it according to your own coding style.
    • Field Description: The context is just to facilitate the operation of some common business, such as the above mentioned network connection judgment. Fields can be added according to their own needs, such as the need for network requests in this presenter, you can add Httpreq modules, and then Apicloud Cloud API request, you can add APICLOUDSDK module.
3. Scope of Use
常用范围
    • Activity: Implements the callback interface, which defines the object field where the callback is located presenter, initialized in OnCreate.
    • Fragment: Implements the callback interface, defines the object field where the callback is presenter, and initializes it in OnCreate.

In principle, write where you need it.

4. Example

Wgoupresenter.java

 PackageCom.haier.rrmaker.ui.home.fragment.presenter;ImportAndroid.app.ProgressDialog;ImportAndroid.content.Context;ImportCom.alibaba.fastjson.JSON;ImportCOM.HAIER.RRMAKER.R;ImportCom.haier.rrmaker.http.HttpParams;ImportCom.haier.rrmaker.http.HttpResult;ImportCom.haier.rrmaker.http.response.IndexResponse;ImportCom.lidroid.xutils.exception.HttpException;ImportCom.lidroid.xutils.http.ResponseInfo;ImportCom.lidroid.xutils.http.callback.RequestCallBack;ImportCom.snicesoft.http.HttpReq;ImportCom.snicesoft.presenter.BasePresenter;ImportCom.snicesoft.util.CommonUtils;ImportCom.snicesoft.util.DialogUtil; Public  class wgoupresenter extends basepresenter<wgoupresenter. Callback> {     Public  interface Callback extends basepresenter. Callback {        voidIndex (indexresponse response); } httpreq Httpreq; Public void Sethttpreq(Httpreq httpreq) { This. httpreq = Httpreq; } ProgressDialog ProgressDialog; Public Wgoupresenter(Context context) {Super(context);    ProgressDialog = Dialogutil.getprogressdialog (context); }protected void ShowDialog(Charsequence message,Boolean... flag) {if(Flag! =NULL) {if(Flag.length >0) Progressdialog.setcancelable (flag[0]);if(Flag.length >1) Progressdialog.setcanceledontouchoutside (flag[1]);        } progressdialog.setmessage (message);    Progressdialog.show (); }protected void Closedialog() {if(Progressdialog.isshowing ()) Progressdialog.dismiss (); } Public void Index() {if(Httpreq = =NULL)return;if(Isnetconnect ()) {ShowDialog ("Loading"); Httpreq.post (HttpParams.Wgou.Index,NULL,NewRequestcallback<string> () {@Override                         Public void onfailure(HttpException arg0, String arg1)                            {Closedialog ();                        Commonutils.showtoast (GetContext (), r.string.net_error_retry); }@Override                         Public void onsuccess(responseinfo<string> arg0)                            {Closedialog (); Indexresponse response = Json.parseobject (Arg0.result, Indexresponse.class);if(httpresult.issuccess (response))                            {Callback.index (response); }Else{Commonutils.showtoast (GetContext (),"Data returned error");        }                        }                    }); }Else{Commonutils.showtoast (GetContext (), r.string.net_error); }    }}

Wgoufragment.java

 Public  class wgoufragment extendsavfragment<wgouholder, wgoudata , homeactivity> implementsWgoupresenter. Callback {                Wgoupresenter Wgouservice;@Override     Public void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Wgouservice =NewWgoupresenter (FA ());        Wgouservice.sethttpreq (FA (). Getapp (). Httpreq ()); Wgouservice.setcallback ( This); }@Override     Public void onactivitycreated(Bundle savedinstancestate) {Super. onactivitycreated (Savedinstancestate);    Wgouservice.index (); }@Override     Public void Index(Indexresponse response)        {_holder.index (response);    _holder.scrollbottom (); }}

Here is a simple example of the use of fragment:
1. First define presenter and callback

class or interface Wgoupresenter Wgoupresenter.callback Description
Method Index () Index (indexresponse response) Get home Information
Execute the Thread Non-UI threads UI thread

2, Wgoufragment realize Wgoupresenter.callback
Implement the index (Indexresponse response) method to bind the returned data to the corresponding UI again. If the business is fully communicated prior to development, this piece can be tested with simulated data and tested on the test environment later on-line.
The definition for Wgoupresenter is initialized in OnCreate. The Onactivitycreated method makes an index () request, which is just a demo. However, the order of requests must not be error: the wgoupresenter initialization is complete and the view initialization is complete (that is, holder initialization is complete)

5. Finally
一定要注意规范,否则会导致代码混乱。对于这套规范我写了个简单的代码生成器,生成activity和fragment的时候会将holder、data、presenter全部生成好,省去了自己创建的麻烦。由于编译环境不同,故不提供jar包,直接上源码。

Android Rapid Development appbase--(5). Use of Basepresenter

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.