MVP登录

//导入依赖
compile 'com.google.code.gson:gson:2.8.2'
compile 'com.squareup.okhttp3:okhttp:3.9.1'
//联网设置
<uses-permission android:name="android.permission.INTERNET"></uses-permission>

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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"
    >

    <EditText
        android:id="@+id/etAccount"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入账号"
        />

    <EditText
        android:id="@+id/etPwd"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入密码"
        />

    <Button
        android:id="@+id/btLogin"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="登录"/>

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</LinearLayout>
view
MainActivity
package com.example.mvp.view;

import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.mvp.R;
import com.example.mvp.presenter.LoginPresenterImp;


/**
 * 以MVP的角度来看,Actiivty对应的就是V(view)
 */
public class MainActivity extends AppCompatActivity implements View.OnClickListener,LoginView {
    Handler handler = new Handler();
    private LoginPresenterImp loginPresenterImp;
    /**
     * 请输入账号
     */
    private EditText mEtAccount;
    /**
     * 请输入密码
     */
    private EditText mEtPwd;
    /**
     * 登录
     */
    private Button mBtLogin;
    private TextView mTv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        loginPresenterImp = new LoginPresenterImp(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        loginPresenterImp.detach();
    }

    private void initView() {
        mEtAccount = (EditText) findViewById(R.id.etAccount);
        mEtPwd = (EditText) findViewById(R.id.etPwd);
        mBtLogin = (Button) findViewById(R.id.btLogin);
        mBtLogin.setOnClickListener(this);
        mTv = (TextView) findViewById(R.id.tv);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.btLogin:
                //登录
                loginPresenterImp.login();
                break;
        }
    }

    @Override
    public String getAccout() {
        return mEtAccount.getText().toString();
    }

    @Override
    public String getPwd() {
        return mEtPwd.getText().toString();
    }

    @Override
    public void showLoading() {
        //进度显示
        Toast.makeText(MainActivity.this,"加载中...", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void dismissLoading() {
        //关闭进度显示
        Toast.makeText(MainActivity.this,"加载完成", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showData(final String phone) {
        //显示号码
       /* runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mTv.setText(phone);
            }
        });*/
        mTv.setText(phone);
    }

    /**
     * 给用户提示一些信息,比如正确的,或者错误的
     * @param str
     */
    @Override
    public void showMsg(String str) {
        Toast.makeText(MainActivity.this,str, Toast.LENGTH_SHORT).show();
    }
}

LoginView
package com.example.mvp.view;

public interface LoginView {
    String getAccout();
    String getPwd();
    void showLoading();
    void dismissLoading();
    void showData(String phone);
    void showMsg(String str);
}
presenter
LoginPresenterImp
package com.example.mvp.presenter;

import android.text.TextUtils;

import com.example.mvp.bean.UserBean;
import com.example.mvp.modle.LoginModelImp;
import com.example.mvp.net.OnNetListener;
import com.example.mvp.view.MainActivity;
import com.google.gson.Gson;


/**
 * 以MVP的角度来看,该类对应的就是P(presenter)
 * 作用:1、进行业务逻辑处理前的各种条件判断
 * 2、连接View层和Model层
 */
public class LoginPresenterImp implements LoginPresenter {
    private MainActivity loginView;
    private final LoginModelImp loginModelImp;

    public LoginPresenterImp(MainActivity loginView) {
        //绑定
        this.loginView = loginView;
        //初始化model层的对象
        loginModelImp = new LoginModelImp();
    }

    //登录
    @Override
    public void login() {
        //该方法不做真正的业务逻辑即不写请求网络的方法,交给Model层去处理

        //获取用户名和密码
        String accout = loginView.getAccout();
        String pwd = loginView.getPwd();
        if (TextUtils.isEmpty(accout) || TextUtils.isEmpty(pwd)) {
            //提示用户输入账号密码不正确
            loginView.showMsg("输入账号密码不正确");
            return;
        }
        //进行网络请求
        loginView.showLoading();
        loginModelImp.login(accout, pwd, new OnNetListener() {
            @Override
            public void onSuccess(String result) {
                if (loginView == null) {
                    return;
                }
                loginView.dismissLoading();
                UserBean userBean = new Gson().fromJson(result, UserBean.class);
                loginView.showData(userBean.getData().getMobile());
            }

            @Override
            public void onFailed(Exception e) {
                if (loginView == null) {
                    return;
                }
                loginView.dismissLoading();
            }
        });
    }

    //解绑
    @Override
    public void detach() {
        if (loginView != null) {
            loginView = null;
        }
    }


}
LoginPresenter
package com.example.mvp.presenter;

public interface LoginPresenter {
    void login();
    //解绑
    void detach();
}
net
Api
package com.example.mvp.net;

public interface Api {
    public static final String LGOIN_URL = "https://www.zhaoapi.cn/user/login";
}
OkhttpUtils
package com.example.mvp.net;

import android.os.Handler;
import android.os.Looper;

import java.io.IOException;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 网络请求的工具类
 */
public class OkhttpUtils {
    private static OkhttpUtils instance;
    private final OkHttpClient okHttpClient;
    private final Handler handler;

    private OkhttpUtils() {
        //创建OkHttpClient对象
        okHttpClient = new OkHttpClient();
        handler = new Handler(Looper.getMainLooper());
    }

    public static OkhttpUtils getInstance() {
        if (instance == null) {
            instance = new OkhttpUtils();
        }
        return instance;
    }

    /**
     * 登录的方法
     *
     * @param url           地址
     * @param params        接口的参数
     * @param onNetListener 接口回调,把数据返给调用改方法的Activity
     */
    public void login(String url, Map<String, String> params, final OnNetListener onNetListener) {
        if (params == null) {
            return;
        }
        //创建Requeset对象
        FormBody.Builder builder = new FormBody.Builder();
        //添加参数
        for (Map.Entry<String, String> entry : params.entrySet()) {
            builder.add(entry.getKey(), entry.getValue());
        }
        FormBody formBody = builder.build();
        Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .build();
        //请求
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                onNetListener.onFailed(e);
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                //把回调放到主线程里
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        //已经在主线程运行了
                        final String string;
                        try {
                            //拿到服务器返回的json字符串
                            string = response.body().string();
                            onNetListener.onSuccess(string);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                    }
                });

//                onNetListener.onSuccess(string);
            }
        });
    }

}
OnNetListener
package com.example.mvp.net;

/**
 * 网络请求成功或者失败回调的接口
 */
public interface OnNetListener {
    void onSuccess(String result);

    void onFailed(Exception e);
}
modle
LoginModel
package com.example.mvp.modle;


import com.example.mvp.net.OnNetListener;

public interface LoginModel {
    void login(String accout, String pwd, OnNetListener onNetListener);
}
LoginModelImp
package com.example.mvp.modle;



import com.example.mvp.net.Api;
import com.example.mvp.net.OkhttpUtils;
import com.example.mvp.net.OnNetListener;

import java.util.HashMap;
import java.util.Map;

public class LoginModelImp implements LoginModel {
    @Override
    public void login(String accoutm, String pwd, OnNetListener onNetListener) {
        Map<String, String> params = new HashMap<>();
        params.put("mobile", accoutm);
        params.put("password", pwd);
        OkhttpUtils.getInstance().login(Api.LGOIN_URL, params, onNetListener);
    }
}
bean
UserBean
package com.example.mvp.bean;

public class UserBean {

    /**
     * msg : 登录成功
     * code : 0
     * data : {"age":null,"appkey":"07258a7bbfd8b132","appsecret":"E243E12B205A861F4BBC0492A373A36F",
     * "createtime":"2018-04-16T11:22:59","email":null,"fans":null,"follow":null,"gender":null,"icon":null,
     * "latitude":null,"longitude":null,"mobile":"18310830365","money":null,"nickname":null,
     * "password":"8F669074CAF5513351A2DE5CC22AC04C","praiseNum":null,"token":"5B5E60DC8960BA6DBCF3CBA638A1EC32",
     * "uid":1235,"userId":null,"username":"18310830365"}
     */

    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 : 07258a7bbfd8b132
         * appsecret : E243E12B205A861F4BBC0492A373A36F
         * createtime : 2018-04-16T11:22:59
         * email : null
         * fans : null
         * follow : null
         * gender : null
         * icon : null
         * latitude : null
         * longitude : null
         * mobile : 18310830365
         * money : null
         * nickname : null
         * password : 8F669074CAF5513351A2DE5CC22AC04C
         * praiseNum : null
         * token : 5B5E60DC8960BA6DBCF3CBA638A1EC32
         * uid : 1235
         * userId : null
         * username : 18310830365
         */

        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;
        }
    }
}

阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭