1.工具类
package com.example.utils;
import java.io.IOException;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
/**
* Created by 。 on 2018/12/17.
*/
public class HttpUtils {
private static HttpUtils httpUtils = new HttpUtils();
private HttpUtils(){
}
public static HttpUtils getHttpUtils(){
if(httpUtils==null){
httpUtils =new HttpUtils();
}
return httpUtils;
}
public String getJson(String url){
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder().url(url).get().build();
try {
Response response = okHttpClient.newCall(request).execute();
return response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
2.Model层
package com.example.model;
import com.example.bean.Result;
import com.example.bean.Shop;
import com.example.utils.HttpUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.List;
/**
* Created by 。 on 2018/12/17.
*/
public class MyModel {
public Result getData(){
String url = "http://www.zhaoapi.cn/product/getCarts?uid=71";
HttpUtils httpUtils = HttpUtils.getHttpUtils();
String json = httpUtils.getJson(url);
Gson gson = new Gson();
Type type = new TypeToken<Result<List<Shop>>>() {}.getType();
Result result = gson.fromJson(json, type);
return result;
}
}
3.Presenter层
父类
package com.example.presenter;
import android.os.AsyncTask;
import com.example.bean.Result;
import com.example.core.BaseCall;
/**
* Created by 。 on 2018/12/17.
*/
public abstract class BasePresenter{
public BaseCall baseCall;
public BasePresenter(BaseCall baseCall){
this.baseCall = baseCall;
}
public void unBindBaseCall(){
baseCall = null;
}
public void getData(String...args){
new MyTask().execute(args);
}
class MyTask extends AsyncTask<String,Void,Result>{
@Override
protected Result doInBackground(String[] ts) {
Result result = getAD(ts);
return result;
}
@Override
protected void onPostExecute(Result result) {
super.onPostExecute(result);
if(result.getCode().equals("0")){
baseCall.loadSuccess(result.getData());
}else{
baseCall.loadError(result);
}
}
}
protected abstract Result getAD(String...args);
}
子类
package com.example.presenter;
import com.example.bean.Result;
import com.example.core.BaseCall;
import com.example.model.MyModel;
/**
* Created by 。 on 2018/12/17.
*/
public class MyPresenter extends BasePresenter {
private static final String TAG = "MyPresenter";
public MyPresenter(BaseCall baseCall) {
super(baseCall);
}
@Override
protected Result getAD(String[] args) {
//Log.d(TAG, "getAD:11111 "+args[1]);
Result result = new MyModel().getData();
return result;
}
}
4.接口
package com.example.core;
import com.example.bean.Result;
/**
* Created by 。 on 2018/12/17.
*/
public interface BaseCall<T> {
void loadSuccess(T data);
void loadError(Result result);
}