// View
public class MainActivity extends AppCompatActivity implements IContract.IView {
@BindView(R.id.et_location)
EditText etLocation;
@BindView(R.id.btn_confirm)
Button btnConfirm;
private IContract.IPresenter<IContract.IView> presenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
//创建P层对象
presenter = new PresenterImpl();
//关联V层对象
presenter.attachView(this);
}
@Override
public void showData(String response) {
Toast.makeText(this, response, Toast.LENGTH_SHORT).show();
}
@Override
protected void onDestroy() {
super.onDestroy();
//取消解绑V层
presenter.detachView(this);
}
@OnClick(R.id.btn_confirm)
public void onViewClicked() {
//获取输入框内容:地址
String location = etLocation.getText().toString();
presenter.requestInfo(location);
}
}
//Modle
@Override
public void requestData(String userName, String pwd, String rePwd, final onCallBackLisenter onCallBackLisenter) {
if (userName.equals("") || pwd.equals("") || rePwd.equals("")) {
onCallBackLisenter.responseMsg("用户名或密码为空");
return;
}
FormBody formBody = new FormBody.Builder()
.add("username", userName)
.add("password", pwd)
.add("repassword", rePwd)
.build();
OKHttpUtil.getInstance().post(URL_STRING, formBody, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
String failureString = e.getMessage().toString();
onCallBackLisenter.responseMsg(failureString);
Log.e("ModelImpl", failureString);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String reponseString = response.body().string();
onCallBackLisenter.responseMsg(reponseString);
Log.e("ModelImpl", reponseString);
Gson gson = new Gson();
ResponseBean responseBean = gson.fromJson(reponseString, ResponseBean.class);
}
});
}
//Pressenter
public class PresenterImpl implements IContract.IPresenter<IContract.IView> {
private WeakReference<IContract.IView> viewWeakReference;
IContract.IView iView;
private ModelImpl model;
private WeakReference<IContract.IModel> modelWeakReference;
@Override
public void attachView(IContract.IView iView) {
this.iView = iView;
//获取M层对象
model = new ModelImpl();
//弱引用包裹V层、M层对象
viewWeakReference = new WeakReference<>(iView);
modelWeakReference = new WeakReference<IContract.IModel>(model);
}
@Override
public void detachView(IContract.IView iView) {
//弱引用解绑/去除包裹的V层、M层对象
viewWeakReference.clear();
modelWeakReference.clear();
}
@Override
public void requestInfo(String location) {
model.requestData(location,new IContract.IModel.onCallBack() {
@Override
public void responseMsg(String response) {
iView.showData(response);
}
});
}
}
//App 得到上下文
public class App extends Application {
private static App app;
@Override
public void onCreate() {
super.onCreate();
app = this;
}
public static App getInstance() {
return app;
}
}