一、view层接口 (IView)
package com.xwj.lenovo.my_mvp_two.view;
/**
* Created by lenovo on 2018/5/7.
*/
public interface IView {
void getSuccess(String string);
void getError(String error);
}
二、IPresenter层
1.(IPresenter)接口
package com.xwj.lenovo.my_mvp_two.presenter;
import java.util.Map;
/**
* Created by lenovo on 2018/5/7.
*/
public interface IPresenter {
//成功的
void getSuccess(String string);
//失败的
void getError(String error);
//获取数据
void getData(String url, Map<String, String> map);
}
2.IPresenter的实现类 (IPresenterImpI)
package com.xwj.lenovo.my_mvp_two.presenter;
import com.xwj.lenovo.my_mvp_two.model.IModelmpI;
import com.xwj.lenovo.my_mvp_two.view.IView;
import java.util.Map;
/**
* Created by lenovo on 2018/5/7.
*/
public class IPresenterImpI implements IPresenter {
private IView iView;
private final IModelmpI iModelmpI;
//有参构造
public IPresenterImpI(IView iView) {
//实例化model类
iModelmpI = new IModelmpI(this);
this.iView = iView;
}
//成功的
@Override
public void getSuccess(String string) {
iView.getSuccess(string);
}
//失败的
@Override
public void getError(String error) {
iView.getError(error);
}
//获取数据
@Override
public void getData(String url, Map<String, String> map) {
iModelmpI.getData(url, map);
}
}
三、model层
1、model层接口 (IModel)
package com.xwj.lenovo.my_mvp_two.model;
import java.util.Map;
/**
* Created by lenovo on 2018/5/7.
*/
public interface IModel {
void getData(String url, Map<String,String> map);
}
2.model层的实现类 (IModelmpI )
注意:下面 判断时根据自己的bean类,去决定要判断的值,我这里是状态,状态为false时,获取数据,一般大部分都是code=0为成功,不要写错呦!
package com.xwj.lenovo.my_mvp_two.model;
import android.util.Log;
import com.xwj.lenovo.my_mvp_two.http.RetrofitUtils;
import com.xwj.lenovo.my_mvp_two.presenter.IPresenter;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.Map;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;
/**
* Created by lenovo on 2018/5/7.
*/
public class IModelmpI implements IModel {
IPresenter iPresenter;
//构造方法
public IModelmpI(IPresenter iPresenter) {
this.iPresenter = iPresenter;
}
@Override
public void getData(String url, Map<String, String> map) {
RetrofitUtils.getService().getDataGetView(url,map)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(new Observer<ResponseBody>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(ResponseBody responseBody) {
try {
String string = responseBody.string();
try {
JSONObject jsonObject = new JSONObject(string);
String error = jsonObject.getString("error");
//判断状态为false时,获取数据------》根据自己的bean类决定自己要判断的参数
if ("false".equals(error)){
iPresenter.getSuccess(string);
}else {
//失败的回调
iPresenter.getError(string);
}
} catch (JSONException e) {
e.printStackTrace();
//失败的回调
iPresenter.getError(string);
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onError(Throwable e) {
Log.d("IModelmpI", "出现异常----------------------"+e.getMessage());
}
@Override
public void onComplete() {
}
});
}
}
四、需要用到的 ApiService
里面是需要用到的两种请求方式
package com.xwj.lenovo.my_mvp_two.http;
import java.util.Map;
import io.reactivex.Observable;
import okhttp3.ResponseBody;
import retrofit2.http.FieldMap;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Path;
import retrofit2.http.QueryMap;
/**
* Created by lenovo on 2018/5/7.
*/
public interface ApiService {
//get请求
@GET("{url}")
Observable<ResponseBody> getDataGetView(@Path(value = "url", encoded = true) String url, @QueryMap Map<String, String> map);
//Post请求
@FormUrlEncoded
@POST("{url}")
Observable<ResponseBody> getDataPostView(@Path(value = "url", encoded = true) String url, @FieldMap Map<String, String> map);
}
五、RetrofitUtils 工具类
package com.xwj.lenovo.my_mvp_two.http;
import android.util.Log;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* Created by Administrator on 2018/4/9 0009.
*/
public class RetrofitUtils {
private Retrofit retrofit;
private static RetrofitUtils retrofitUtils = null;
public RetrofitUtils() {
}
public RetrofitUtils(String baseUrl) {
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addInterceptor(new CommonParamsInterceptor())
.build();
retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
}
public static RetrofitUtils getInstance(String baseUrl) {
if (retrofitUtils == null) {
synchronized (RetrofitUtils.class) {
if (retrofitUtils == null) {
retrofitUtils = new RetrofitUtils(baseUrl);
}
}
}
return retrofitUtils;
}
public <T> T createService(Class<T> service) {
return retrofit.create(service);
}
public static ApiService getService() {
return RetrofitUtils.getInstance(HttpConfig.base_url).createService(ApiService.class);
}
//拦截器
public class CommonParamsInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
//调用request()方法得到拦截的请求
Request request = chain.request();
//获取请求的方式
String method = request.method();//GET POST
//拦截的请求的路径
String oldUrl = request.url().toString();
Log.e("----oldUrl", oldUrl);
//要添加的公共参数...map
Map<String, String> map = new HashMap<>();
map.put("source", "android");
map.put("appVersion", "100");
if ("GET".equals(method)) {
StringBuilder stringBuilder = new StringBuilder();//创建一个stringBuilder...字符串缓冲区
stringBuilder.append(oldUrl);
if (oldUrl.contains("?")) {
//?在最后面....2类型
if (oldUrl.indexOf("?") == oldUrl.length() - 1) {
} else {
//3类型...拼接上&
stringBuilder.append("&");
}
} else {
//不包含? 属于1类型,,,先拼接上?号
stringBuilder.append("?");
}
//添加公共参数....source=android&appVersion=100&
for (Map.Entry<String, String> entry : map.entrySet()) {
//拼接
stringBuilder.append(entry.getKey())
.append("=")
.append(entry.getValue())
.append("&");
}
//删掉最后一个&符号
if (stringBuilder.indexOf("&") != -1) {
stringBuilder.deleteCharAt(stringBuilder.lastIndexOf("&"));
}
//得到含有公共参数的新路径.....使用新路径去请求
String newUrl = stringBuilder.toString();
Log.e("----newUrl", newUrl);
//新的路径构建一个新的请求
request = request.newBuilder().url(newUrl).build();
} else if ("POST".equals(method)) {
//参数在请求的实体内容上....拿到以前的参数,把以前的参数和公共参数全都添加到请求实体上
RequestBody requestBody = request.body();
if (requestBody instanceof FormBody) {//前边是不是后边的子类/实例对象
FormBody oldBody = (FormBody) requestBody;//keywords...page
FormBody.Builder builder = new FormBody.Builder();
//先添加之前的参数
for (int i = 0; i < oldBody.size(); i++) {
//键值对的形式添加
builder.add(oldBody.name(i), oldBody.value(i));
}
//添加公共参数
for (Map.Entry<String, String> entry : map.entrySet()) {
builder.add(entry.getKey(), entry.getValue());
}
//构建一个新的请求
request = request.newBuilder().url(oldUrl).post(builder.build()).build();
} else if (request.body() instanceof MultipartBody) {
MultipartBody body = (MultipartBody) request.body();
MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
builder.addFormDataPart("source", "android")
.addFormDataPart("appVersion", "101");
List<MultipartBody.Part> parts = body.parts();
for (MultipartBody.Part part : parts) {
builder.addPart(part);
}
request = request.newBuilder().url(oldUrl).post(builder.build()).build();
}
}
//执行请求 获取到响应
Response response = chain.proceed(request);
return response;
}
}
}
六、MainActivity的布局
<?xml version="1.0" encoding="utf-8"?>
<com.scwang.smartrefresh.layout.SmartRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/refreshLayout"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.xwj.lenovo.my_mvp_two.MainActivity">
<android.support.v7.widget.RecyclerView
android:id="@+id/recy_view"
android:layout_width="match_parent"
android:layout_height="match_parent"></android.support.v7.widget.RecyclerView>
</com.scwang.smartrefresh.layout.SmartRefreshLayout>
七、MainActivity中做的具体操作
package com.xwj.lenovo.my_mvp_two;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.xwj.lenovo.my_mvp_two.adpter.MyRecylerView;
import com.xwj.lenovo.my_mvp_two.bean.MyBean;
import com.xwj.lenovo.my_mvp_two.http.HttpConfig;
import com.xwj.lenovo.my_mvp_two.presenter.IPresenterImpI;
import com.xwj.lenovo.my_mvp_two.view.IView;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import butterknife.BindView;
import butterknife.ButterKnife;
public class MainActivity extends AppCompatActivity implements IView {
int page = 1;
@BindView(R.id.recy_view)
RecyclerView recyView;
@BindView(R.id.refreshLayout)
com.scwang.smartrefresh.layout.SmartRefreshLayout refreshLayout;
private IPresenterImpI iPresenterImpI;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
//布局管理器
recyView.setLayoutManager(new LinearLayoutManager(this));
//调用MVP
iPresenterImpI = new IPresenterImpI(this);
//获取数据的方法
initview();
}
private void initview() {
Map<String, String> map = new HashMap<>();
iPresenterImpI.getData(HttpConfig.data_url + page, map);
}
/**
* 重写的view 层的方法
* @param string
*/
@Override
public void getSuccess(String string) {
MyBean myBean = new Gson().fromJson(string, MyBean.class);
List<MyBean.ResultsBean> list = myBean.getResults();
MyRecylerView myRecylerView = new MyRecylerView(this, list);
recyView.setAdapter(myRecylerView);
//SmartRefreshLayout控件的刷新
refreshLayout.setOnRefreshListener(new OnRefreshListener() {
@Override
public void onRefresh(RefreshLayout refreshlayout) {
page = 1;
//重新加载数据
initview();
//3秒以后关闭刷新的视图
refreshlayout.finishRefresh(4000);
}
});
//SmartRefreshLayout控件的加载
refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
@Override
public void onLoadmore(RefreshLayout refreshlayout) {
//页数++ 进行加载下一页
page++;
//重新加载数据
initview();
//3秒以后关闭加载的视图
refreshlayout.finishLoadmore(3000);
}
});
}
//失败的方法
@Override
public void getError(String error) {
Log.d("MainActivity", "失败啦!-----》"+error);
}
}
接下来就是写适配器了,我用的是RecyclerView,相信RecyclerView的适配器大家都会写的,这里就不贴出来啦!
这样一个通过mvp框架+RecyclerView展示数据+第三方控件SmartRefreshLayout进行刷新的小demo就完成啦!
对了,小伙伴们不要忘记加权限哦!
效果基本就是下面这样: