使用MVP做一个登录注册

使用MVP做一个登录注册_第1张图片


使用MVP做一个登录注册_第2张图片



首先第一步先导入依赖

implementation files('libs/gson-2.3.1.jar')
compile 'com.squareup.okhttp3:okhttp:3.3.0'
compile 'com.github.bumptech.glide:glide:3.7.0'
compile 'com.android.support:recyclerview-v7:26.0.0-alpha1'

-----------------------------------------------布局-------------------------------------------------------

activity_main

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="登录"
        android:textColor="#000"
        android:textSize="20sp" />
    <View
        android:layout_width="match_parent"
        android:layout_height="0.75dp"
        android:layout_marginTop="10dp"
        android:background="#999999" />
    <EditText
        android:id="@+id/login_mobile"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入手机号" />
    <EditText
        android:id="@+id/login_password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:hint="请输入密码" />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dp"
        android:orientation="horizontal">
        <Button
            android:id="@+id/login"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="登录" />
        <Button
            android:id="@+id/reg"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="注册" />
    LinearLayout>

LinearLayout>


activity_reg

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="登录"
        android:textColor="#000"
        android:textSize="20sp" />
    <View
        android:layout_width="match_parent"
        android:layout_height="0.75dp"
        android:layout_marginTop="10dp"
        android:background="#999999" />
    <EditText
        android:id="@+id/login_mobile"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入手机号" />
    <EditText
        android:id="@+id/login_password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:hint="请输入密码" />
    <Button
        android:id="@+id/reg_but"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="50dp"
        android:text="注册" />
LinearLayout>

activity_title

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="212dp"
    android:textSize="30dp"
    android:textColor="#f00"
    android:text="登录成功" />
RelativeLayout>

---------------------------------------------------------------代码和MVP分包-------------------------------------------------------------------

首先我们先创建好MVP的三个包以及要用的bean包和网络请求Http包


Http包下的HttpConfig类

public class HttpConfig {
    //登录的接口  请求参数:mobile手机号  必传参数  password密码  必传参数
    public static String login_url = "https://www.zhaoapi.cn/user/login";
    //注册的接口  请求参数:mobile手机号  必传参数  password密码  必传参数
    public static String reg_url = "https://www.zhaoapi.cn/user/reg";
}

Http包下的HttpUtils类

public class HttpUtils {
    //单例模式
    private static HttpUtils httpUtils = null;
    private MyHandler myHandler = new MyHandler();
    //请求成功
    public static final int SUCCESS = 0;
    //请求失败
    public static final int ERROR = 1;
    private OKHttpListener fromHttpListener;

    public static HttpUtils getHttputils() {
        if (httpUtils == null) {
            httpUtils = new HttpUtils();
        }
        return httpUtils;
    }
    //get请求方式
    public void getOkHttp(String url) {
        //获取ok实例
        OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
        Request request = new Request.Builder().url(url).build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            //请求失败
            @Override
            public void onFailure(Call call, IOException e) {
                //得到Message
                Message message = myHandler.obtainMessage();
                message.what = ERROR;
                message.obj = e.getMessage();//请求失败
                //向Handler发送消息
                myHandler.handleMessage(message);
            }
            //请求成功
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String json = response.body().string();
                //得到Message
                Message message = myHandler.obtainMessage();
                message.what = SUCCESS;
                message.obj = json;//请求成功
                //向Handler发送消息
                myHandler.handleMessage(message);
            }
        });
    }
    //post请求方式
    public void postOkHttp(String url, Map map) {
        //获取ok实例
        OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
        //创建请求体
        FormBody.Builder builder = new FormBody.Builder();
        //得到map集合中的key的集合
        Set keySet = map.keySet();
        //便利集合
        for (String key : keySet
                ) {
            //根据key找到值
            String value = map.get(key);
            builder.add(key,value);
        }
        FormBody formBody = builder.build();
        Request request = new Request.Builder().url(url).post(formBody).build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            //请求失败
            @Override
            public void onFailure(Call call, IOException e) {
                //得到Message
                Message message = myHandler.obtainMessage();
                message.what = ERROR;
                message.obj = e.getMessage();//请求失败
                //向Handler发送消息
                myHandler.sendMessage(message);
            }
            //请求成功
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String json = response.body().string();
                //得到Message
                Message message = myHandler.obtainMessage();
                message.what = SUCCESS;
                message.obj = json;//请求成功
                //向Handler发送消息
                myHandler.sendMessage(message);
            }
        });
    }
    //创建Handler向主线程发送json字符串
    class MyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            //监听是否获取数据成功或者失败
            switch (msg.what) {
                case SUCCESS:
                    //获取成功
                    String json = (String) msg.obj;
                    fromHttpListener.fromJosnSuccess(json);
                    break;
                case ERROR:
                    //获取失败
                    String error = (String) msg.obj;
                    fromHttpListener.fromJsonError(error);
                    break;
            }
        }
    }
    //向外提供获取数据的监听 向外发送数据
    public void setFromHttpListener(OKHttpListener fromHttpListener) {
        this.fromHttpListener = fromHttpListener;
    }
}

Http包下的OKHttpListener

public interface OKHttpListener {
    //获取数据成功时回调
    void fromJosnSuccess(String json);

    //获取数据失败时回调
    void fromJsonError(String error);
}

Model包下的Loginlisttnter

public interface Loginlisttnter {
    //获取数据成功
    void showLoginJsonSuccess(String json);
    //获取数据失败
    void showLoginJsonError(String error);
}

Model包下的LoginModel

public interface LoginModel {
    void showLogin(String url, Map map, Loginlisttnter iLoginlisttnter);
}

Model包下的LoginModelIpml

public class LoginModelIpml implements LoginModel{
    @Override
    public void showLogin(String url, Map map, final Loginlisttnter iLoginlisttnter) {
        //在Model层进行网络请求
        HttpUtils httputils = HttpUtils.getHttputils();
        //使用POST方式进行请求
        httputils.postOkHttp(url, map);
        httputils.setFromHttpListener(new OKHttpListener() {
            @Override
            public void fromJosnSuccess(String json) {
                //请求成功
                //进行解析
                Gson gson = new Gson();
                LoginBean loginBean = gson.fromJson(json, LoginBean.class);
                String code = loginBean.getCode();
                if (code.equals("0")) {//判断当code等于0时为登录成功 否则为登录失败
                    iLoginlisttnter.showLoginJsonSuccess(loginBean.getMsg());
                }else {
                    //请求失败  code不为0
                    iLoginlisttnter.showLoginJsonError(loginBean.getMsg());
                }
            }
            @Override
            public void fromJsonError(String error) {
                //请求失败
                iLoginlisttnter.showLoginJsonError(error);
            }
        });
    }
}

Model包下的Model
public interface Model {

}
 
  
Model包下的ModelImpl
public class ModelImpl {

}

Model包下的Reglisttnter

public interface Reglisttnter {
    //获取数据成功
    void showRegJsonSuccess(String json);
    //获取数据失败
    void showRegJsonError(String error);
}

Model包下的RegModel
public abstract class RegModel {
    public abstract void showReg(String url, Map map, Reglisttnter iReglisttnter);
}

Model包下的RegModelIpml

public class RegModelIpml extends RegModel {
    @Override
    public void showReg(String url, Map map, final Reglisttnter iReglisttnter) {
        //在Model层进行网络请求
        HttpUtils httputils = HttpUtils.getHttputils();
        //使用POST方式进行请求
        httputils.postOkHttp(url, map);
        httputils.setFromHttpListener(new OKHttpListener() {
            @Override
            public void fromJosnSuccess(String json) {
                //请求成功
                //进行解析
                Gson gson = new Gson();
                LoginBean loginBean = gson.fromJson(json, LoginBean.class);
                String code = loginBean.getCode();
                if (code.equals("0")) {
                    //判断当code等于0时为登录成功 否则为登录失败
                    iReglisttnter.showRegJsonSuccess(loginBean.getMsg());
                }else {
                    //请求失败  code不为0
                    iReglisttnter.showRegJsonError(loginBean.getMsg());
                }
            }
            @Override
            public void fromJsonError(String error) {
                //请求失败
                iReglisttnter.showRegJsonError(error);
            }
        });
    }
}

Presenter包下的Presenter

public interface Presenter {
    //登录的回调方法
    void getLoginJson(LoginModel iLoginModel, LoginView iLoginView);
    //注册的回调方法
    void getRegJson(RegModel iRegModel, RegView iRegView);
}

Presenter包下的PresenterImpl

public class PresenterImpl implements Presenter{
    @Override
    public void getLoginJson(LoginModel iLoginModel, final LoginView iLoginView) {
        //创建Map集合
        Map map = new HashMap<>();
        map.put("mobile", iLoginView.getMobile());
        map.put("password", iLoginView.getPassword());
        iLoginModel.showLogin(HttpConfig.login_url, map, new Loginlisttnter() {
            @Override
            public void showLoginJsonSuccess(String json) {
                //登录成功
                iLoginView.showLoginSuccess();
            }
            @Override
            public void showLoginJsonError(String error) {
                iLoginView.showLoginError(error);//登录失败
            }
        });
    }
    @Override
    public void getRegJson(RegModel iRegModel, final RegView iRegView) {
        //创建Map集合
        Map map = new HashMap<>();
        map.put("mobile", iRegView.getMobile());
        map.put("password", iRegView.getPassword());
        iRegModel.showReg(HttpConfig.login_url, map, new Reglisttnter() {
            @Override
            public void showRegJsonSuccess(String json) {
                iRegView.showLoginSuccess(json);
            }
            @Override
            public void showRegJsonError(String error) {
                iRegView.showLoginError(error);
            }
        });
    }
}

View包下的LoginView

public interface LoginView {
    //登录成功的回调
    void showLoginSuccess();
    //登录失败的回调
    void showLoginError(String error);
    //获取输入的手机号
    String getMobile();
    //获取输入的密码
    String getPassword();
}

View包下的MainView

public interface MainView {

}

View包下的RegView

public interface RegView {
    //登录成功的回调
    void showLoginSuccess(String json);
    //登录失败的回调
    void showLoginError(String error);
    //获取输入的手机号
    String getMobile();
    //获取输入的密码
    String getPassword();
}

Activity包下的MainActivity

public class MainActivity extends AppCompatActivity implements View.OnClickListener ,LoginView {

    private EditText login_mobile;
    private EditText login_password;
    private Button login;
    private Button reg;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }
    private void initView() {
        login_mobile = (EditText) findViewById(R.id.login_mobile);
        login_password = (EditText) findViewById(R.id.login_password);
        login = (Button) findViewById(R.id.login);
        login.setOnClickListener(this);
        reg = (Button) findViewById(R.id.reg);
        reg.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.login:
                PresenterImpl presenter = new PresenterImpl();
                presenter.getLoginJson(new LoginModelIpml(),MainActivity.this);
                break;
            case R.id.reg:
                Intent intent = new Intent(MainActivity.this, RegActivity.class);
                startActivity(intent);
                break;
            default:
                break;
        }
    }
    @Override
    public void showLoginSuccess() {
        Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(MainActivity.this,Title.class);
        startActivity(intent);
    }
    @Override
    public void showLoginError(String error) {
        Toast.makeText(this, "登录失败:"+error, Toast.LENGTH_SHORT).show();
    }
    @Override
    public String getMobile() {
        return login_mobile.getText().toString();
    }
    @Override
    public String getPassword() {
        return login_password.getText().toString();
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }
}

Activity包下的RegActivity

public class RegActivity extends AppCompatActivity implements View.OnClickListener,RegView {

    private EditText login_mobile;
    private EditText login_password;
    private Button mButReg;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reg);
        initView();
    }
    private void initView() {
        login_mobile = (EditText) findViewById(R.id.login_mobile);
        login_password = (EditText) findViewById(R.id.login_password);
        mButReg = (Button) findViewById(R.id.reg_but);
        mButReg.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.reg_but:
                Toast.makeText(this, "注册成功", Toast.LENGTH_SHORT).show();
                PresenterImpl presenter = new PresenterImpl();
                presenter.getRegJson(new RegModelIpml(),this);
                break;
            default:
                break;
        }
    }
    @Override
    public void showLoginSuccess(String json) {
        Toast.makeText(this, "注册成功,请前往登录", Toast.LENGTH_SHORT).show();
    }
    @Override
    public void showLoginError(String error) {
        Toast.makeText(this, "注册失败"+error, Toast.LENGTH_SHORT).show();
    }
    @Override
    public String getMobile() {
        return login_mobile.getText().toString();
    }
    @Override
    public String getPassword() {
        return login_password.getText().toString();
    }
}

Activity包下的Title

public class Title extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_title);
    }
}

Bean包下LoginBean

public class LoginBean {
    /**
     * msg : 登录成功
     * code : 0
     * data : {"age":null,"appkey":"1da9c47d431c043b","appsecret":"A804850E463E7E282E09E1AD112D9808","createtime":"2018-04-23T09:41:36","email":null,"fans":null,"follow":null,"gender":null,"icon":null,"latitude":null,"longitude":null,"mobile":"18611112222","money":null,"nickname":null,"password":"8F669074CAF5513351A2DE5CC22AC04C","praiseNum":null,"token":"A4A74B21D1D9E47AA217D6CDAB9A0CE5","uid":11196,"userId":null,"username":"18611112222"}
     */

    private String msg;
    private String code;
    private DataBean data;

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public DataBean getData() {
        return data;
    }

    public void setData(DataBean data) {
        this.data = data;
    }

    public static class DataBean {
        /**
         * age : null
         * appkey : 1da9c47d431c043b
         * appsecret : A804850E463E7E282E09E1AD112D9808
         * createtime : 2018-04-23T09:41:36
         * email : null
         * fans : null
         * follow : null
         * gender : null
         * icon : null
         * latitude : null
         * longitude : null
         * mobile : 18611112222
         * money : null
         * nickname : null
         * password : 8F669074CAF5513351A2DE5CC22AC04C
         * praiseNum : null
         * token : A4A74B21D1D9E47AA217D6CDAB9A0CE5
         * uid : 11196
         * userId : null
         * username : 18611112222
         */

        private Object age;
        private String appkey;
        private String appsecret;
        private String createtime;
        private Object email;
        private Object fans;
        private Object follow;
        private Object gender;
        private Object icon;
        private Object latitude;
        private Object longitude;
        private String mobile;
        private Object money;
        private Object nickname;
        private String password;
        private Object praiseNum;
        private String token;
        private int uid;
        private Object userId;
        private String username;

        public Object getAge() {
            return age;
        }

        public void setAge(Object age) {
            this.age = age;
        }

        public String getAppkey() {
            return appkey;
        }

        public void setAppkey(String appkey) {
            this.appkey = appkey;
        }

        public String getAppsecret() {
            return appsecret;
        }

        public void setAppsecret(String appsecret) {
            this.appsecret = appsecret;
        }

        public String getCreatetime() {
            return createtime;
        }

        public void setCreatetime(String createtime) {
            this.createtime = createtime;
        }

        public Object getEmail() {
            return email;
        }

        public void setEmail(Object email) {
            this.email = email;
        }

        public Object getFans() {
            return fans;
        }

        public void setFans(Object fans) {
            this.fans = fans;
        }

        public Object getFollow() {
            return follow;
        }

        public void setFollow(Object follow) {
            this.follow = follow;
        }

        public Object getGender() {
            return gender;
        }

        public void setGender(Object gender) {
            this.gender = gender;
        }

        public Object getIcon() {
            return icon;
        }

        public void setIcon(Object icon) {
            this.icon = icon;
        }

        public Object getLatitude() {
            return latitude;
        }

        public void setLatitude(Object latitude) {
            this.latitude = latitude;
        }

        public Object getLongitude() {
            return longitude;
        }

        public void setLongitude(Object longitude) {
            this.longitude = longitude;
        }

        public String getMobile() {
            return mobile;
        }

        public void setMobile(String mobile) {
            this.mobile = mobile;
        }

        public Object getMoney() {
            return money;
        }

        public void setMoney(Object money) {
            this.money = money;
        }

        public Object getNickname() {
            return nickname;
        }

        public void setNickname(Object nickname) {
            this.nickname = nickname;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }

        public Object getPraiseNum() {
            return praiseNum;
        }

        public void setPraiseNum(Object praiseNum) {
            this.praiseNum = praiseNum;
        }

        public String getToken() {
            return token;
        }

        public void setToken(String token) {
            this.token = token;
        }

        public int getUid() {
            return uid;
        }

        public void setUid(int uid) {
            this.uid = uid;
        }

        public Object getUserId() {
            return userId;
        }

        public void setUserId(Object userId) {
            this.userId = userId;
        }

        public String getUsername() {
            return username;
        }

        public void setUsername(String username) {
            this.username = username;
        }
    }
}

Bean包下的RegBean

public class RegBean {
    /**
     * msg : 天呢!用户名或密码不能为空
     * code : 1
     * data : {}
     */

    private String msg;
    private String code;
    private String data;

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }
}

















你可能感兴趣的:(使用MVP做一个登录注册)