パッケージOkhttp+retrofit+rxjava MVPモードでログイン登録を実現
69674 ワード
一つは、まず2つのページレイアウトです
1,ログインページのレイアウト
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
android:id="@+id/phone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:gravity="center"
android:hint=" " />
android:id="@+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:gravity="center"
android:hint=" " />
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:gravity="center"
android:orientation="horizontal">
2,登録ページのレイアウト
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
android:id="@+id/phone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:gravity="center"
android:hint=" " />
android:id="@+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:gravity="center"
android:hint=" " />
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:gravity="center"
android:orientation="horizontal">
二、ログインと登録のインタフェースを取得し、それぞれ要求し、エンティティbeanクラスを作成する。
1,登録beanクラス
public class LoginBean {
/**
* msg :
* code : 0
* data : {"age":null,"appkey":"9cdef4b09eb65685","appsecret":"66B6E2E5F439618D01B67FBAEA31EFDA","createtime":"2018-01-15T16:19:03","email":null,"fans":null,"follow":null,"gender":null,"icon":null,"latitude":null,"longitude":null,"mobile":"18765432100","money":null,"nickname":null,"password":"473344696F4685CAE5B5B3C354BC77BE","praiseNum":null,"token":"AFD92DF6C6046F01B76D7C551AEC985B","uid":4362,"userId":null,"username":"18765432100"}
*/
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 : 9cdef4b09eb65685
* appsecret : 66B6E2E5F439618D01B67FBAEA31EFDA
* createtime : 2018-01-15T16:19:03
* email : null
* fans : null
* follow : null
* gender : null
* icon : null
* latitude : null
* longitude : null
* mobile : 18765432100
* money : null
* nickname : null
* password : 473344696F4685CAE5B5B3C354BC77BE
* praiseNum : null
* token : AFD92DF6C6046F01B76D7C551AEC985B
* uid : 4362
* userId : null
* username : 18765432100
*/
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;
}
}
}
2,登録クラスのBeanクラス
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;
}
}
三、okhttp+retrofit+rxjavaパッケージ
1,ApiServインタフェース
public interface ApiService {
@GET
Observable get(@Url String url, @QueryMap Map, String> map);
@FormUrlEncoded
@POST
Observable post(@Url String url, @FieldMap Map, String> map);
}
2,BaseObserver
public abstract class BaseObserver<T> implements Observer {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(String s) {
try {
Type genType = getClass().getGenericSuperclass();
Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
Class entityClass = (Class) params[0];
Gson gson = new Gson();
T t = (T)gson.fromJson(s,entityClass);
success(t);
} catch (Exception e) {
failure(1001);
e.printStackTrace();
}
}
@Override
public void onError(Throwable e) {
try {
if(e != null){
if(e instanceof HttpException){
failure(HTTP_ERROR);
} else if(e instanceof SocketException){
failure(NET_WORK_ERROR);
}else {
failure(UNKNOW_ERROR);
}
}else {
failure(UNKNOW_ERROR);
}
e.printStackTrace() ;
} catch (Exception e1) {
failure(UNKNOW_ERROR);
e1.printStackTrace();
}
}
@Override
public void onComplete() {
}
//
/**
* code
* 1000 UNKNOW_ERROR
* 1001 json parse error
* 1002 java.net.SocketException: Network is unreachable
* 1003 401 402 403 500 502 503 504
* @param code
*/
public static final int UNKNOW_ERROR = 1000;
public static final int JSON_FORMAT_ERROR = 1001;
public static final int NET_WORK_ERROR = 1002;
public static final int HTTP_ERROR = 1003;
public abstract void success(T t);
public abstract void failure(int code);
public abstract void onNextLog(LoginBean bean);
public abstract void onNextReg(RegBean regBean);
}
3,RetrofitManager
public class RetrofitManager {
public static OkHttpClient client = new OkHttpClient.Builder()
.build();
public static ApiService apiService = new Retrofit.Builder()
//
.baseUrl("http://120.27.23.105/")
.addCallAdapterFactory(RxJava2CallAdapterFactory. create()) .addConverterFactory(ScalarsConverterFactory.
create()) .client(
client) .build() .create(ApiService.
class)
;
public static void
get(String url
, Map,String> map
, Observer observer){
apiService.get(url
,map) .subscribeOn(Schedulers.
io()) .observeOn(AndroidSchedulers.
mainThread()) .subscribe(observer)
;
}
public static void
post(String url
,Map,String> map
,Observer observer){
apiService.post(url
,map) .subscribeOn(Schedulers.
io()) .observeOn(AndroidSchedulers.
mainThread()) .subscribe(observer)
;
}}
四、MVPフレームワーク
1,ログイン
ログインしたmodelレイヤ
public class LoginModel {
// map
Map,String> map=new HashMap<>();
public void getData(String phone,String pwd,final loginCallBack loginCallBack){
// map
map.put("mobile",phone);
map.put("password",pwd);
// , , map ,
RetrofitManager.get("user/login", map, new BaseObserver() {
@Override
public void success(LoginBean loginBean) {
loginCallBack.success(loginBean);
}
@Override
public void failure(int code) {
}
@Override
public void onNextLog(LoginBean bean) {
}
@Override
public void onNextReg(RegBean regBean) {
}
});
}
// model
public interface loginCallBack{
void success(LoginBean loginBean);
void error(Exception e);
}
}
ログインしたviewレイヤ
public interface LoginIview {
void success(LoginBean loginBean);
void error(String e);
String getPhone();
String getPwd();
}
登録presenterレイヤpublic class LoginPresenter {
LoginModel loginModel;
LoginIview loginIview;
public LoginPresenter(LoginIview loginIview) {
this.loginIview = loginIview;
this.loginModel = new LoginModel();
}
public void getDatas(){
String phone = loginIview.getPhone();
String pwd = loginIview.getPwd();
loginModel.getData(phone,pwd,new LoginModel.loginCallBack() {
@Override
public void success(LoginBean loginBean) {
// ,
if(loginBean.getMsg().length()==4){
loginIview.success(loginBean);
}else{
loginIview.error(loginBean.getMsg());
}
}
@Override
public void error(Exception e) {
// loginIview.error();
}
});
}
}
2、登録
登録されたmodelレイヤ
public class RegModel {
Map,String> map=new HashMap<>();
public void getData(String phone,String pwd,final RegCallBack regCallBack){
map.put("mobile",phone);
map.put("password",pwd);
//http://120.27.23.105/user/reg
RetrofitManager.get("user/reg", map, new BaseObserver() {
@Override
public void success(RegBean regBean) {
regCallBack.success(regBean);
}
@Override
public void failure(int code) {
}
@Override
public void onNextLog(LoginBean bean) {
}
@Override
public void onNextReg(RegBean regBean) {
}
});
}
public interface RegCallBack{
void success(RegBean regBean);
void error(Exception e);
}
}
登録されたviewレイヤ
public interface RegIview {
void success(RegBean regBean);
void error(Exception e);
String getPhone();
String getPwd();
}
登録されたpresenterレイヤ
public class RegPresenter {
RegModel regModel;
RegIview regIview;
public RegPresenter(RegIview regIview) {
this.regIview = regIview;
this.regModel = new RegModel();
}
public void getDatas(){
String phone = regIview.getPhone();
String pwd = regIview.getPwd();
regModel.getData(phone,pwd,new RegModel.RegCallBack() {
@Override
public void success(RegBean regBean) {
regIview.success(regBean);
}
@Override
public void error(Exception e) {
regIview.error(e);
}
});
}
}
五、Activity
コントロールを探してサードパーティのbutterknifeを使って、これは依存して、使うのは特に簡単で、調べることができます
compile 'com.jakewharton:butterknife:8.8.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
1,activityへのログイン
public class MainActivity extends AppCompatActivity implements LoginIview {
@BindView(R.id.phone)
EditText phone;
@BindView(R.id.password)
EditText password;
@BindView(R.id.login)
Button login;
@BindView(R.id.reg)
Button reg;
@BindView(R.id.activity_main)
LinearLayout activityMain;
private LoginPresenter loginPresenter;
// private String str;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
// P
loginPresenter = new LoginPresenter(this);
//
}
@Override
public void success(LoginBean loginBean) {
// str = loginBean.getMsg().toString()+loginBean.getCode().toString();
startActivity(new Intent(MainActivity.this, LieBiaoActivity.class));
Toast.makeText(this, loginBean.getMsg(), Toast.LENGTH_SHORT).show();
}
@Override
public void error(String e) {
Toast.makeText(this, e, Toast.LENGTH_SHORT).show();
}
@Override
public String getPhone() {
return phone.getText().toString();
}
@Override
public String getPwd() {
return password.getText().toString();
}
@OnClick({R.id.login, R.id.reg})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.login:
loginPresenter.getDatas();
/* if (str.length()>6){
Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
}*/
break;
case R.id.reg:
startActivity(new Intent(MainActivity.this, RegActivity.class));
break;
}
}
}
2,登録したactivity
public class RegActivity extends AppCompatActivity implements RegIview{
@BindView(R.id.phone)
EditText phone;
@BindView(R.id.password)
EditText password;
@BindView(R.id.reg)
Button reg;
@BindView(R.id.activity_main)
LinearLayout activityMain;
private RegPresenter regPresenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reg);
ButterKnife.bind(this);
// P
regPresenter = new RegPresenter(this);
}
@OnClick(R.id.reg)
public void onViewClicked() {
regPresenter.getDatas();
}
@Override
public void success(RegBean regBean) {
Toast.makeText(this, regBean.getMsg().toString()+regBean.getCode().toString(), Toast.LENGTH_SHORT).show();
}
@Override
public void error(Exception e) {
}
@Override
public String getPhone() {
return phone.getText().toString();
}
@Override
public String getPwd() {
return password.getText().toString();
}
}