MVP结合OKhttpclient的登录操作

来源:互联网 发布:日语jtest考试软件 编辑:程序博客网 时间:2024/05/19 02:18

m层

public interface IUserModel {    public void setUserName(String userName);    public void setUserPwd(String userPwd);    public User getUser();}

public class UserModel implements IUserModel {    User user = new User();    @Override    public void setUserName(String userName) {        user.setUserName(userName);    }    @Override    public void setUserPwd(String userPwd) {        user.setUserPwd(userPwd);    }    @Override    public User getUser() {        return user;    }}

v层

public interface IUser {    public String getUserName();    public String getUserPwd();    public void showUser(User user);}

p层

public class UserPresenter {    private IUser iUser;    private IUserModel iUserModel;    public UserPresenter(IUser iUser) {        this.iUser = iUser;        iUserModel = new UserModel();    }    public void register() {        String userName = iUser.getUserName();        String userPwd = iUser.getUserPwd();        iUserModel.setUserName(userName);        iUserModel.setUserPwd(userPwd);    }    public void show() {        User user = iUserModel.getUser();        iUser.showUser(user);    }}
OKhttpclient

public class MyOkHttpClient {    private static volatile MyOkHttpClient myOkHttpClient;    private Context context;    private final OkHttpClient client;    private OnClickReturn onClickReturn;    public MyOkHttpClient(Context context) {        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();        logging.setLevel(HttpLoggingInterceptor.Level.BODY);        client = new OkHttpClient.Builder()                .addInterceptor(logging)                .build();        this.context = context;    }    public interface OnClickReturn {        public void getCode(String code, String uid);    }    public void setOnClickReturn(OnClickReturn onClickReturn) {        this.onClickReturn = onClickReturn;    }    public static MyOkHttpClient getInstance(Context context) {        if (myOkHttpClient == null) {            synchronized (MyOkHttpClient.class) {                if (myOkHttpClient == null) {                    myOkHttpClient = new MyOkHttpClient(context);                }            }        }        return myOkHttpClient;    }    public void dopost(String url, Map<String, String> params, final Class clazz) {        FormBody.Builder builder = new FormBody.Builder();        for (Map.Entry<String, String> gmap : params.entrySet()) {            builder.add(gmap.getKey(), gmap.getValue());        }        FormBody formBody = builder.build();        Request request = new Request.Builder().url(url).post(formBody).build();        client.newCall(request).enqueue(new Callback() {            @Override            public void onFailure(Call call, IOException e) {            }            @Override            public void onResponse(Call call, Response response) throws IOException {                String string = response.body().string();                Log.e("REGISTERURL:---", string);                SelectInfo selectInfo = new Gson().fromJson(string.toString(), SelectInfo.class);                String msg = selectInfo.getMsg();                if (msg.equals("查询成功")) {                    Log.e("REGISTERURL:---", "查询成功!!!!!!!!!!!!!!!!");                } else {                    CodeBean codeBean = (CodeBean) new Gson().fromJson(string.toString(), clazz);                    String code = codeBean.getCode();                    int uid = 123;                    if (code.equals("0")) {                        uid = codeBean.getData().getUid();                    }                    Log.e("REGISTERURL:---", code + "");                    onClickReturn.getCode(code, uid + "");                }            }        });    }}
1主

public class Main2Activity extends AppCompatActivity implements IUser, View.OnClickListener {    private EditText etName;    private EditText etPwd;    private Button bt_register;    private Button bt_show;    private User user;    private UserPresenter userPresenter;    private Handler handker = new Handler() {        @Override        public void handleMessage(Message msg) {            super.handleMessage(msg);            switch (msg.what) {                case 0:                    Toast.makeText(Main2Activity.this, "登录成功!", Toast.LENGTH_SHORT).show();                    Intent intent = new Intent(Main2Activity.this, InFoActivity.class);                    startActivity(intent);                    Main2Activity.this.finish();                    break;                case 1:                    Toast.makeText(Main2Activity.this, "登录失败!", Toast.LENGTH_SHORT).show();                    break;            }        }    };    private String namephone;    private String pwd;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main2);        userPresenter = new UserPresenter(this);        SharedPreferences name = getSharedPreferences("name", MODE_PRIVATE);        findid();    }    public void findid() {        etName = (EditText) findViewById(R.id.etName);        etPwd = (EditText) findViewById(R.id.etPwd);        bt_register = (Button) findViewById(R.id.bt_register);        bt_register.setOnClickListener(this);        bt_show = (Button) findViewById(R.id.bt_show);        bt_show.setOnClickListener(this);    }    @Override    public void onClick(View v) {        switch (v.getId()) {            case R.id.bt_register:                //首先获取用户的账号密码                //userPresenter.show();                String username = etName.getText().toString().trim();                String userpwd = etPwd.getText().toString().trim();                if (TextUtils.isEmpty(username) || TextUtils.isEmpty(userpwd)) {                    Toast.makeText(this, "账号和密码不能为空!", Toast.LENGTH_SHORT).show();                } else if (username.length() != 11) {                    Toast.makeText(this, "手机号长度为11位!", Toast.LENGTH_SHORT).show();                } else if (userpwd.length() > 16 || username.length() < 6) {                    Toast.makeText(this, "密码的长度为6-16!", Toast.LENGTH_SHORT).show();                } else {                    HashMap<String, String> hashMap = new HashMap<>();                    hashMap.put("mobile", username);                    hashMap.put("password", userpwd);                    MyOkHttpClient.getInstance(this).dopost(Api.REGISTERID, hashMap, CodeBean.class);                }                MyOkHttpClient.getInstance(this).setOnClickReturn(new MyOkHttpClient.OnClickReturn() {                    @Override                    public void getCode(String code, final String uid) {                        if (code.equals("0")) {                            runOnUiThread(new Runnable() {                                @Override                                public void run() {                                    SharedPreferences name = getSharedPreferences("name", MODE_PRIVATE);                                    SharedPreferences.Editor edit = name.edit();                                    edit.putString("uid",uid);                                    edit.commit();                                }                            });                            handker.sendEmptyMessage(0);                        } else {                            handker.sendEmptyMessage(1);                        }                    }                });                break;            case R.id.bt_show:                Intent intent = new Intent(this, RegisterActivity.class);                startActivityForResult(intent, Api.ACTIVITYCODE);                break;        }    }    @Override    protected void onActivityResult(int requestCode, int resultCode, Intent data) {        super.onActivityResult(requestCode, resultCode, data);        namephone = data.getExtras().getString("username");        pwd = data.getExtras().getString("userpwd");        userPresenter.register();    }    @Override    public String getUserName() {        return namephone;    }    @Override    public String getUserPwd() {        return pwd;    }    @Override    public void showUser(User user) {        Toast.makeText(Main2Activity.this, user.getUserName()+"----"+user.getUserPwd(), Toast.LENGTH_SHORT).show();    }}

2主

public class RegisterActivity extends AppCompatActivity implements View.OnClickListener {    /**     * 请输入手机号     */    private EditText mEtRegisterName;    /**     * 请输入密码     */    private EditText mEtRegisterPwd;    /**     * 注册     */    private Button mBtRegisterUp;    private Handler handker = new Handler() {        @Override        public void handleMessage(Message msg) {            super.handleMessage(msg);            switch (msg.what) {                case 0:                    Toast.makeText(RegisterActivity.this, "成功!", Toast.LENGTH_SHORT).show();                    Intent intent = new Intent();                    intent.putExtra("username", username);                    intent.putExtra("userpwd", userpwd);                    setResult(Api.ACTIVITYCODE, intent);                    RegisterActivity.this.finish();                    break;                case 1:                    Toast.makeText(RegisterActivity.this, "失败!", Toast.LENGTH_SHORT).show();                    break;            }        }    };    private String username;    private String userpwd;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_register);        initView();    }    private void initView() {        mEtRegisterName = (EditText) findViewById(R.id.et_register_Name);        mEtRegisterPwd = (EditText) findViewById(R.id.et_register_Pwd);        mBtRegisterUp = (Button) findViewById(R.id.bt_register_up);        mBtRegisterUp.setOnClickListener(this);    }    @Override    public void onClick(View v) {        switch (v.getId()) {            case R.id.bt_register_up:                username = mEtRegisterName.getText().toString().trim();                userpwd = mEtRegisterPwd.getText().toString().trim();                if (TextUtils.isEmpty(username) || TextUtils.isEmpty(userpwd)) {                    Toast.makeText(this, "账号和密码不能为空!", Toast.LENGTH_SHORT).show();                } else if (username.length() != 11) {                    Toast.makeText(this, "手机号长度为11位!", Toast.LENGTH_SHORT).show();                } else if (userpwd.length() > 16 || username.length() < 6) {                    Toast.makeText(this, "密码的长度为6-16!", Toast.LENGTH_SHORT).show();                } else {                    HashMap<String, String> hashMap = new HashMap<>();                    hashMap.put("mobile", username);                    hashMap.put("password", userpwd);                    MyOkHttpClient.getInstance(this).dopost(Api.ZHUCEID, hashMap, CodeBean.class);                    MyOkHttpClient.getInstance(this).setOnClickReturn(new MyOkHttpClient.OnClickReturn() {                        @Override                        public void getCode(String code, String uid) {                            if (code.equals("0")) {                                handker.sendEmptyMessage(0);                            } else {                                handker.sendEmptyMessage(1);                            }                        }                    });                }                break;        }    }}
3主

public class InFoActivity extends AppCompatActivity implements View.OnClickListener {    /**     * username     */    private TextView mTvInfoUsername;    /**     * 退出登录     */    private Button mBtInfoReturn;    /**     * 跳转到商品搜索页     */    private Button mBtInfoSelect;    private SharedPreferences name;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_in_fo);        initView();        setuid();    }    private void setuid() {        name = getSharedPreferences("name", MODE_PRIVATE);        String string = name.getString("uid", "username字段");        mTvInfoUsername.setText(string);    }    private void cleanPreferences() {        SharedPreferences.Editor edit = name.edit();        edit.clear();        edit.commit();    }    private void initView() {        mTvInfoUsername = (TextView) findViewById(R.id.tv_info_username);        mBtInfoReturn = (Button) findViewById(R.id.bt_info_return);        mBtInfoReturn.setOnClickListener(this);        mBtInfoSelect = (Button) findViewById(R.id.bt_info_select);        mBtInfoSelect.setOnClickListener(this);    }    @Override    public void onClick(View v) {        switch (v.getId()) {            case R.id.bt_info_return:                cleanPreferences();                Intent intent = new Intent(InFoActivity.this, Main2Activity.class);                startActivity(intent);                InFoActivity.this.finish();                break;            case R.id.bt_info_select:                Intent intent2 = new Intent(InFoActivity.this, ShoppingActivity.class);                startActivity(intent2);                InFoActivity.this.finish();                break;        }    }}
4主

public class ShoppingActivity extends AppCompatActivity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_shopping);        HashMap<String, String> hashMap = new HashMap<>();        hashMap.put("keywords", "笔记本");        MyOkHttpClient.getInstance(this).dopost(Api.SHOPPINGSELECT, hashMap, null);    }}

1主xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical">    <EditText        android:layout_margin="15dp"        android:id="@+id/etName"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:hint="请输入账号" />    <EditText        android:layout_marginRight="15dp"        android:layout_marginLeft="15dp"        android:layout_marginBottom="15dp"        android:id="@+id/etPwd"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:hint="请输入密码" /><RadioGroup    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:gravity="center"    android:orientation="horizontal">    <Button        android:id="@+id/bt_register"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="登录" />    <Button        android:id="@+id/bt_show"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="注册" /></RadioGroup></LinearLayout>
2主xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical">    <EditText        android:layout_margin="15dp"        android:id="@+id/et_register_Name"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:hint="请输入手机号" />    <EditText        android:layout_marginRight="15dp"        android:layout_marginLeft="15dp"        android:layout_marginBottom="15dp"        android:id="@+id/et_register_Pwd"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:hint="请输入密码" />    <RadioGroup        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:gravity="center"        android:orientation="horizontal">        <Button            android:id="@+id/bt_register_up"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="注册" />    </RadioGroup></LinearLayout>

3主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"    tools:context="com.example.smallreegister.activity.InFoActivity">    <TextView        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_margin="10dp"        android:gravity="center"        android:text="个人信息"        android:textSize="25dp" />    <View        android:layout_width="match_parent"        android:layout_height="1dp"        android:background="#000000"></View>    <RelativeLayout        android:layout_width="match_parent"        android:layout_height="60dp"        android:layout_margin="10dp">        <TextView            android:layout_width="wrap_content"            android:layout_height="60dp"            android:gravity="center_vertical"            android:text="头像"            android:textSize="20dp" />        <ImageView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_alignParentRight="true"            android:layout_marginRight="50dp"            android:src="@mipmap/ic_launcher" />        <TextView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_alignParentRight="true"            android:text=">"            android:textSize="50dp" />    </RelativeLayout>    <View        android:layout_width="match_parent"        android:layout_height="1dp"        android:background="#000000"></View>    <RelativeLayout        android:layout_width="match_parent"        android:layout_height="60dp"        android:layout_margin="10dp">        <TextView            android:layout_width="wrap_content"            android:layout_height="60dp"            android:gravity="center_vertical"            android:text="用户名"            android:textSize="20dp" />        <TextView            android:id="@+id/tv_info_username"            android:layout_width="wrap_content"            android:layout_height="60dp"            android:layout_alignParentRight="true"            android:layout_marginRight="50dp"            android:gravity="center_vertical"            android:text="username" />    </RelativeLayout>    <View        android:layout_width="match_parent"        android:layout_height="1dp"        android:background="#000000"></View>    <RelativeLayout        android:layout_width="match_parent"        android:layout_height="60dp"        android:layout_margin="10dp">        <TextView            android:layout_width="wrap_content"            android:layout_height="60dp"            android:gravity="center_vertical"            android:text="昵称"            android:textSize="20dp" />        <TextView            android:layout_width="wrap_content"            android:layout_height="60dp"            android:layout_alignParentRight="true"            android:layout_marginRight="50dp"            android:gravity="center_vertical"            android:text="kson" />        <TextView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_alignParentRight="true"            android:text=">"            android:textSize="50dp" />    </RelativeLayout>    <View        android:layout_marginBottom="50dp"        android:layout_width="match_parent"        android:layout_height="1dp"        android:background="#000000"></View>    <RadioGroup        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:gravity="center"        android:orientation="horizontal">        <Button            android:id="@+id/bt_info_return"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="退出登录"/>        <Button            android:id="@+id/bt_info_select"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="跳转到商品搜索页"/>    </RadioGroup></LinearLayout>
4主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"    tools:context="com.example.smallreegister.activity.ShoppingActivity">    <RadioGroup        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:orientation="horizontal">        <EditText            android:id="@+id/rt_shop_info"            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:layout_weight="1"            android:text="输入搜索关键词" />        <Button            android:id="@+id/bt_shop_select"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="搜索" />        <Button            android:id="@+id/bt_shop_change"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="师徒切换" />    </RadioGroup>    <android.support.v7.widget.RecyclerView        android:id="@+id/rl_shop_item"        android:layout_width="match_parent"        android:layout_height="wrap_content">    </android.support.v7.widget.RecyclerView></LinearLayout>



原创粉丝点击