我为Android MVP模式评论 [英] Comments on my MVP pattern for Android

查看:107
本文介绍了我为Android MVP模式评论的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我打算使用MVP模式为我的新的Andr​​oid项目。我做了一些样品code,我想知道,我有没有正确执行呢?请给于code的意见,并发表你的建议。

我的活动课,我从我的基本视角类扩展它,我实现一个接口。本次活动只需调用一个新的线程的互联网服务和更新TextView的价值。

 公共类CougarTestView扩展基本视角实现ICougarView,
        OnClickListener {
    CougarTest presenter _ presenter;
    公共字符串activityName =CougarHome;

    / **第一次创建活动时调用。 * /`输入code here`
    @覆盖
    公共无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState,activityName);
        的setContentView(R.layout.main);
        _ presenter =新CougarTest presenter(本);
        getSubmitBtn()setOnClickListener(本)。
        getCallInfoBtn()setOnClickListener(本)。

    }

    私人按钮getCallInfoBtn(){
        返回(按钮)findViewById(R.id.btn_callinfo);
    }

    公共无效setServiceValue(字符串retVal的){
        // TODO自动生成方法存根
        。getResultLabel()的setText(retVal的);
        setPbar(假);
        // toastMsg(retVal的);
    }

    公共无效ResetPbar(){
        getProgressBtn()setProgress(0)。
    }

    公共无效setProcessProgress(INT进度){

        如果(getProgressBtn()getProgress()< 100){
            。getProgressBtn()incrementProgressBy(进度);
        } 其他 {
            setPbar(假);
        }
    }

    私人TextView的getResultLabel(){
        返回(TextView中)findViewById(R.id.result);
    }

    私人按钮getSubmitBtn(){
        返回(按钮)findViewById(R.id.btn_triptype);
    }

    私人进度getProgressBtn(){
        返回(进度)findViewById(R.id.pgs_br);
    }

    公共无效setPbar(布尔可见){
        如果(!可见){
            。getProgressBtn()setVisibility(View.GONE);
        } 其他
            。getProgressBtn()setVisibility(View.VISIBLE);
    }

    @覆盖
    公共无效setHtt presult(字符串retVal的){
        // TODO自动生成方法存根
        setServiceValue(retVal的);
    }

    私人无效toastMsg(弦乐味精){
        Toast.makeText(这一点,味精,Toast.LENGTH_LONG).show();
    }

    公共无效的onClick(视图v){
        // TODO自动生成方法存根
        开关(v.getId()){
        案例R.id.btn_triptype:{
            尝试 {
                _ presenter.valueFromService(RequestType.CallInfo,0);
            }赶上(例外五){
                // TODO自动生成的catch块
                e.printStackTrace();
            }
            打破;
        }

        默认:
            setServiceValue(默认);
        }
    }


}
 

我的活动类:在我的活动课我有一个TextView和一个按钮。当我preSS的按钮,它调用Web服务来获取数据在presenter类。在presenter类调用Web服务解析响应,并设置在活动的TextView的价值。

 我的presenter类


公共类CougarTest presenter {
    ICougarView密刺;
    请求类型mRtype;
    公共字符串结果=thisi小号导致我;
    处理器mHandle;


    公共CougarTest presenter(ICougarView ICI){
        密刺= ICI;

    }
    公共无效valueFromService(请求类型类型,INT X)抛出异常{
        字符串URL = getURLByType(类型);

        // GetServiceresult服务=新GetServiceresult();
        // service.execute(URL);
        处理程序句柄=新的处理程序(){
            公共无效的handleMessage(信息MSG){
                开关(msg.what){

                案例Globals.IO_EXPECTION:{
                    Toast.makeText(mIci.getContext(),msg.toString(),
                            Toast.LENGTH_LONG).show();
                    NetworkConnectivityListener connectivityListener = NetworkConnectivityListener
                            .getInstace();
                    mHandle = CustomHandler.getInstance(mIci.getContext(),
                            connectivityListener,密刺);
                    connectivityListener.registerHandler(mHandle,
                            Globals.CONNECTIVITY_MSG);
                    connectivityListener.startListening(mIci.getContext());
                    mIci.setPbar(假);
                }
                    打破;
                案例Globals.RHAPSODY_EXCEPTION:{
                    ExceptionInfo exInfo = NULL;
                        尝试 {
                            exInfo = Utility.ParseExceptionData(msg.obj.toString());

                        }赶上(JSONException E){
                            // TODO自动生成的catch块
                            e.printStackTrace();
                        }赶上(例外五){
                            // TODO自动生成的catch块
                            e.printStackTrace();
                        }
                        mIci.setServiceValue(exInfo.Message + exInfo.Type + exInfo.Detail);

                //新HandleRhapsodyException(MISA,exInfo);
                }
                打破;
                默认: {
                    Toast.makeText(mIci.getContext(),msg.toString(),
                            Toast.LENGTH_LONG).show();
                    mIci.setServiceValue(msg.obj.toString());
                }
                }

            }
        };

        ServiceResult线程=新ServiceResult(手柄,URL);
        mIci.setPbar(真正的);
        thread.start();

    }

    公共字符串getURLByType(请求类型类型){
        // TODO自动生成方法存根
        开关(类型){
        案例CallInfo:{
            返回(www.gmail.com);
        }
        案例TRIPTYPE:{
            返回(www.google.com);
        }
        默认:
            返回(www.cnet.com);

        }
    }

    私有类ServiceResult继承Thread {
        处理程序处理;
        字符串URL;

        公共ServiceResult(处理程序处理,字符串URL){
            this.handle =手柄;
            this.url =网址;
        }

        公共无效的run(){
            sendExceptionLog(手柄);

        }
    }

    公共无效sendExceptionLog(处理程序处理){

        DebugHttpClient的HttpClient =新DebugHttpClient();

        HTTPGET GET =新HTTPGET(
                https://192.168.194.141/TripService/service1/);
        尝试 {
            HTT presponse响应= httpClient.execute(获得);

            HttpEntity r_entity = response.getEntity();
            字符串的xmlString = EntityUtils.toString(r_entity);
            // setdvrid.setText(的xmlString +
            // + response.getStatusLine()的getStatus code());

            。httpClient.getConnectionManager()关闭();

            如果(response.getStatusLine()的getStatus code()!= 200){
                handle.sendMessage(Message.obtain(手柄,Globals.RHAPSODY_EXCEPTION,
                        的xmlString));
            结果= Utility.ParseExceptionData(的xmlString).Message;
            }
            其他
            {
                handle.sendMessage(Message.obtain(手柄,Globals.SERVICE_REPONSE,
                        response.getStatusLine()的getStatus code()
                                + response.getStatusLine()。getReasonPhrase()
                                +的xmlString));
            }

        }赶上(ClientProtocolException E){
            // TODO自动生成的catch块
            handle.sendMessage(Message.obtain(手柄,Globals.OTHER_EXPECTION,
                    。e.getMessage()的toString()+她));
        }赶上(IOException异常E){
            // TODO自动生成的catch块
            handle.sendMessage(Message.obtain(手柄,Globals.IO_EXPECTION,E
                    .getMessage()的toString()+他))。
        }赶上(例外五){
            handle.sendMessage(Message.obtain(手柄,Globals.OTHER_EXPECTION,
                    。e.getMessage()的toString()+它));
        }

    }
 

下面的接口在活动课实施,活动类的实例被作为接口对象以presenter类的构造函数。

 我的观点接口

公共接口ICougarView {
公共无效setServiceValue(字符串retVal的);
公共无效setProcessProgress(INT进度);
公共无效setPbar(布尔B);
公共无效ResetPbar();
公共语境的getContext();
}
 

解决方案

对不起,我迟到:) 我已经使用MVP在Android这样。

活动是presenters。每presenter有一个链接模式(S)(有时是服务,有时没有,这取决于从任务),以及查看(S)。我创建自定义视图,并将其设置为活动的内容视图。

请参阅:

 公共类ExampleModel {
   私人为ExampleActivity presenter;

   公共ExampleModel(为ExampleActivity presenter){
       这presenter = presenter。
   }
   //域逻辑等
}

公共类为ExampleActivity延伸活动{
   私人ExampleModel模型;
   私人ExampleView视图;

   @覆盖
   保护无效的onCreate(包savedInstanceState){
       super.onCreate(savedInstanceState);
       模型=新ExampleModel(本);
       鉴于=新ExampleView(本);
       的setContentView(视图);
   }
   //不同的presenter方法
}

公共类ExampleView扩展的LinearLayout {

    公共ExampleView(上下文的背景下){
        超(上下文);
    }
}
 

另外,我已经讨论过这个话题<一个href="http://androidforums.com/application-development/386207-what-design-patterns-do-you-use.html">here.

我要提醒你,该活动不应该被视为视图。我们有非常糟糕的expirience有了它,当我们与PureMVC的会议审议活动作为视图组件写道。活动是合控制器/ presenter /视图模型(我试过所有的人,我喜欢MVP最),它具有优异的仪器管理的意见(查看,对话框等),而它不是一个查看本身。

I am planning to use MVP pattern for my new Android project. I have done some sample code and I would like to know, have I implemented it correctly? Please give comments on the code and also post your suggestions.

my activity class I am extending it from my BaseView class and I am implementing an interface. this activity simply calls an webservice in a new thread and updates the value in the textview.

public class CougarTestView extends BaseView implements ICougarView,
        OnClickListener {
    CougarTestPresenter _presenter;
    public String activityName = "CougarHome";

    /** Called when the activity is first created. */`enter code here`
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState, activityName);
        setContentView(R.layout.main);
        _presenter = new CougarTestPresenter(this);
        getSubmitBtn().setOnClickListener(this);
        getCallInfoBtn().setOnClickListener(this);

    }

    private Button getCallInfoBtn() {
        return (Button) findViewById(R.id.btn_callinfo);
    }

    public void setServiceValue(String retVal) {
        // TODO Auto-generated method stub
        getResultLabel().setText(retVal);
        setPbar(false);
        // toastMsg(retVal);
    }

    public void ResetPbar() {
        getProgressBtn().setProgress(0);
    }

    public void setProcessProgress(int progress) {

        if (getProgressBtn().getProgress() < 100) {
            getProgressBtn().incrementProgressBy(progress);
        } else {
            setPbar(false);
        }
    }

    private TextView getResultLabel() {
        return (TextView) findViewById(R.id.result);
    }

    private Button getSubmitBtn() {
        return (Button) findViewById(R.id.btn_triptype);
    }

    private ProgressBar getProgressBtn() {
        return (ProgressBar) findViewById(R.id.pgs_br);
    }

    public void setPbar(boolean visible) {
        if (!visible) {
            getProgressBtn().setVisibility(View.GONE);
        } else
            getProgressBtn().setVisibility(View.VISIBLE);
    }

    @Override
    public void setHttpResult(String retVal) {
        // TODO Auto-generated method stub
        setServiceValue(retVal);
    }

    private void toastMsg(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
    }

    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
        case R.id.btn_triptype: {           
            try {
                _presenter.valueFromService(RequestType.CallInfo, 0);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            break;
        }

        default:
            setServiceValue("default");
        }
    }


}

My activity class: in my activity class i am having a textview and a button. when i press the button , it call the webservice to get the data in the presenter class. the presenter class calls the webservice parses the response and sets the value in the textview of the activity.

My presenter class


public class CougarTestPresenter {
    ICougarView mIci;
    RequestType mRtype;
    public String result= "thisi s result i";
    Handler mHandle;


    public CougarTestPresenter(ICougarView ici) {
        mIci = ici; 

    }
    public void valueFromService(RequestType type, int x) throws Exception{
        String url = getURLByType(type);

        // GetServiceresult service = new GetServiceresult();
        // service.execute(url);
        Handler handle = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {

                case Globals.IO_EXPECTION: {
                    Toast.makeText(mIci.getContext(), msg.toString(),
                            Toast.LENGTH_LONG).show();
                    NetworkConnectivityListener connectivityListener = NetworkConnectivityListener
                            .getInstace();
                    mHandle = CustomHandler.getInstance(mIci.getContext(),
                            connectivityListener, mIci);
                    connectivityListener.registerHandler(mHandle,
                            Globals.CONNECTIVITY_MSG);
                    connectivityListener.startListening(mIci.getContext());
                    mIci.setPbar(false);
                }
                    break;
                case Globals.RHAPSODY_EXCEPTION:{   
                    ExceptionInfo exInfo =null;
                        try {
                            exInfo = Utility.ParseExceptionData(msg.obj.toString());

                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }                       
                        mIci.setServiceValue(exInfo.Message + exInfo.Type +exInfo.Detail);

                //      new HandleRhapsodyException(mIsa, exInfo);
                }
                break;
                default: {
                    Toast.makeText(mIci.getContext(), msg.toString(),
                            Toast.LENGTH_LONG).show();
                    mIci.setServiceValue(msg.obj.toString());
                }
                }

            }
        };

        ServiceResult thread = new ServiceResult(handle, url);
        mIci.setPbar(true);
        thread.start();

    }

    public String getURLByType(RequestType type) {
        // TODO Auto-generated method stub
        switch (type) {
        case CallInfo: {
            return ("www.gmail.com");
        }
        case TripType: {
            return ("www.google.com");
        }
        default:
            return ("www.cnet.com");

        }
    }

    private class ServiceResult extends Thread {
        Handler handle;
        String url;

        public ServiceResult(Handler handle, String url) {
            this.handle = handle;
            this.url = url;
        }

        public void run() {
            sendExceptionLog(handle);

        }
    }

    public void sendExceptionLog(Handler handle) {

        DebugHttpClient httpClient = new DebugHttpClient();

        HttpGet get = new HttpGet(
                "https://192.168.194.141/TripService/service1/");
        try {
            HttpResponse response = httpClient.execute(get);

            HttpEntity r_entity = response.getEntity();
            String xmlString = EntityUtils.toString(r_entity);
            // setdvrid.setText(xmlString + " "
            // + response.getStatusLine().getStatusCode());

            httpClient.getConnectionManager().shutdown();

            if (response.getStatusLine().getStatusCode() != 200) {
                handle.sendMessage(Message.obtain(handle, Globals.RHAPSODY_EXCEPTION,
                        xmlString));
            result= Utility.ParseExceptionData(xmlString).Message;
            }
            else
            {
                handle.sendMessage(Message.obtain(handle, Globals.SERVICE_REPONSE,
                        response.getStatusLine().getStatusCode()
                                + response.getStatusLine().getReasonPhrase()
                                + xmlString));
            }

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            handle.sendMessage(Message.obtain(handle, Globals.OTHER_EXPECTION,
                    e.getMessage().toString() + "she"));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            handle.sendMessage(Message.obtain(handle, Globals.IO_EXPECTION, e
                    .getMessage().toString() + "he"));
        } catch (Exception e) {
            handle.sendMessage(Message.obtain(handle, Globals.OTHER_EXPECTION,
                    e.getMessage().toString() + "it"));
        }

    }

the below interface is implemented in the activity class and the instance of the activity class is sent as interface object to the constructor of the presenter class.

my view interface

public interface ICougarView {
public void setServiceValue(String retVal);
public void setProcessProgress(int progress);
public void setPbar(boolean b);
public void ResetPbar();
public Context getContext();
}

解决方案

Sorry for the late :) I've use MVP on Android this way.

Activities are presenters. Every presenter has a link to model(s) (sometimes it is services, sometimes not, depending from the task) and to view(s). I create custom view and set it as the content view for activity.

See:

public class ExampleModel {
   private ExampleActivity presenter;

   public ExampleModel(ExampleActivity presenter) {
       this.presenter = presenter;
   }
   //domain logic and so on
}

public class ExampleActivity extends Activity {
   private ExampleModel model;
   private ExampleView view;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       model = new ExampleModel(this);
       view = new ExampleView(this);
       setContentView(view);
   }
   // different presenter methods
}

public class ExampleView extends LinearLayout {

    public ExampleView(Context context) {
        super(context);
    }
}

Also, I've discussed this topic here.

I should warn you, that Activity shouldn't be considered as the view. We had very bad expirience with it, when we wrote with PureMVC which considered Activity as view component. Activity is excellently suitable for controller/presenter/view model (I've tried all of them, I like MVP the most), it has excellent instrumentation for managing the views (View, Dialog and so on) while it's not a view itself.

这篇关于我为Android MVP模式评论的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆