工具类
public class MyApplication extends Application { public static GetDataInterface getDataInterface; @Override public void onCreate() { super.onCreate(); //1. 用于全局配置初始化Fresco 图片加载 Fresco.initialize(this); //2. 用于全局配置初始化Retrofit 网络请求 //构建Retrofit类,初始化参数 Retrofit retrofit = new Retrofit.Builder() .baseUrl("http://result.eolinker.com") .addConverterFactory(GsonConverterFactory.create()) .build(); //3.//创建网络请求接口实例 getDataInterface = retrofit.create(GetDataInterface.class); } }
MyModel 层
public class MyModel { public void getDataM(final ModelCallBack modelCallBack){ Call<DataDataBean> into = MyApplication.getDataInterface.getInto(); //发起异步请求 into.enqueue(new Callback<DataDataBean>() { @Override public void onResponse(Call<DataDataBean> call, Response<DataDataBean> response) { //获取响应的数据 if (response.body()!=null&&response.isSuccessful()){ DataDataBean dataDataBean = response.body(); modelCallBack.onSuccess(dataDataBean); } } @Override public void onFailure(Call<DataDataBean> call, Throwable t) { //请求失败时返回数据 modelCallBack.onFailure(new Exception("")); } }); } }
DateDataBean 数据接口
Model层下接口
public interface ModelCallBack { public void onSuccess(DataDataBean dataDataBean); public void onFailure(Exception e); }
Present层下
import xieshuaikang.com.www.zhoukao1_moni_20171230.Model.DataDataBean; import xieshuaikang.com.www.zhoukao1_moni_20171230.Model.Interfac.ModelCallBack; import xieshuaikang.com.www.zhoukao1_moni_20171230.Model.MyModel; import xieshuaikang.com.www.zhoukao1_moni_20171230.View.Fragment.ShouYe_Fragment; import xieshuaikang.com.www.zhoukao1_moni_20171230.View.Interfa.MyView; /** * Created by Administrator on 2017/12/30. */ public class MyPresenter { private MyModel myModel; MyView myView; public MyPresenter(MyView myView) { myModel = new MyModel(); this.myView = myView; } public void getData() { myModel.getDataM(new ModelCallBack() { @Override public void onSuccess(DataDataBean dataDataBean) { //数据交互时,为防止内存泄露,设置view层数据为空 if (myView!=null){ myView.onSuccess(dataDataBean); } } @Override public void onFailure(Exception e) { //数据交互时,为防止内存泄露,设置view层数据为空 if (myView != null){ myView.onFailure(e); } } }); } }