契约类
package com.example.one_week_demo;
/**
* 契约类
*/
public interface IContact {
interface IView{
void success(String json);
void error(String error);
}
interface IModel{
void getData(String url, Callback callback);
}
interface IPresenter{
void startRequest(String url);
void onDetach();
}
interface Callback{
void onSuccess(String json);
void onError(String error);
}
}
Model层
package com.example.one_week_demo.model;
import com.example.one_week_demo.IContact;
import com.example.one_week_demo.utils.OkHttpUtils;
public class ModelImpl implements IContact.IModel {
@Override
public void getData(final String url, final IContact.Callback callback) {
OkHttpUtils.getInstance().asyncGetInfo(url, new OkHttpUtils.MyCallBack() {
@Override
public void onSuccess(String success) {
callback.onSuccess(success);
}
@Override
public void onError(String error) {
callback.onError(error);
}
});
}
}
Presneter层
package com.example.one_week_demo.presenter;
import com.example.one_week_demo.IContact;
import com.example.one_week_demo.model.ModelImpl;
import java.lang.ref.SoftReference;
public class PresenterImpl implements IContact.IPresenter {
private ModelImpl mModel;
private IContact.IView mIView;
private SoftReference<IContact.IView> mSoft;
public PresenterImpl(IContact.IView iView) {
mModel = new ModelImpl();
this.mIView = iView;
mSoft = new SoftReference<>(mIView);
}
@Override
public void startRequest(String url) {
mModel.getData(url, new IContact.Callback() {
@Override
public void onSuccess(String json) {
mIView.success(json);
}
@Override
public void onError(String error) {
mIView.error(error);
}
});
}
@Override
public void onDetach() {
if (mSoft != null) {
mSoft.clear();
}
if (mModel != null) {
mModel = null;
}
}
}
OKHTTP
package com.example.one_week_demo.utils;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
public class OkHttpUtils {
private OkHttpClient mOkHttp;
private Cache mCache;
private MyCallBack myCallBack;
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case 0:
myCallBack.onError(msg.obj.toString());
break;
case 1:
myCallBack.onSuccess(msg.obj.toString());
break;
}
}
};
private OkHttpUtils() {
File file = new File(Environment.getExternalStorageDirectory() + "/memeda");
if (!file.exists()) {
file.mkdir();
}
mCache = new Cache(file, 1024 * 1024 * 2);
//日志拦截器
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
mOkHttp = new OkHttpClient.Builder()
.connectTimeout(20, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.addInterceptor(loggingInterceptor)
.cache(mCache)
.build();
}
static class OkHttpHolder {
private final static OkHttpUtils ok = new OkHttpUtils();
}
public static OkHttpUtils getInstance() {
return OkHttpHolder.ok;
}
public void asyncGetInfo(String url,MyCallBack myCallBack){
this.myCallBack = myCallBack;
Request request = new Request.Builder().url(url)
//添加缓存 缓存两小时 Okhttp的源吗也是用DiskLruCache
.cacheControl(new CacheControl.Builder().maxStale(60*60*2,TimeUnit.SECONDS).build())
.build();
mOkHttp.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
mHandler.sendMessage(mHandler.obtainMessage(0,e.getMessage()));
}
@Override
public void onResponse(Call call, Response response) throws IOException {
mHandler.sendMessage(mHandler.obtainMessage(1,response.body().string()));
}
});
}
//最终版异步Post
public void lastAsyncPost(String url, Map<String,String> map, final MyCallBack myCallBack){
this.myCallBack = myCallBack;
FormBody.Builder form = new FormBody.Builder();
for (String key:map.keySet()){
form.add(key,map.get(key));
}
FormBody body = form.build();
Request request = new Request.Builder().url(url).method("POST",body).build();
mOkHttp.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
mHandler.sendMessage(mHandler.obtainMessage(1, e.getMessage()));
}
@Override
public void onResponse(Call call, Response response) throws IOException {
mHandler.sendMessage(mHandler.obtainMessage(0, response.body().string()));
}
});
}
//上传图片
public void uploadImage(String url,MyCallBack myCallBack){
File file = new File(Environment.getExternalStorageDirectory()+"/Pictures/dream.jpg");
Log.e("filename",file.getName());
RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
//添加参数 参数1:接口参数的key 参数2:上传文件的名字,参数3:请求体里面两个参数 参数1:声明你上传的格式参数2:具体某个文件
.addFormDataPart("image","dream.jpg",RequestBody.create(MediaType.parse("image/jpg"), file)).build();
Request request = new Request.Builder().method("POST",requestBody)
.addHeader("userId","5953")
.addHeader("sessionId","15601336197575953").url(url).build();
mOkHttp.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
mHandler.sendMessage(mHandler.obtainMessage(1, e.getMessage()));
}
@Override
public void onResponse(Call call, Response response) throws IOException {
mHandler.sendMessage(mHandler.obtainMessage(0, response.body().string()));
}
});
}
public interface MyCallBack{
void onSuccess(String success);
void onError(String error);
}
}
Main
package com.example.one_week_demo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.example.one_week_demo.fragment.LeftFragment;
import com.example.one_week_demo.fragment.RightFragment;
public class MainActivity extends AppCompatActivity {
private LeftFragment leftFragment;
private RightFragment rightFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initFrag();
}
private void initFrag() {
leftFragment = new LeftFragment();
rightFragment = new RightFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.Lienar_Left, leftFragment).commit();
getSupportFragmentManager().beginTransaction().replace(R.id.Liear_Right, rightFragment).commit();
}
}
Left
package com.example.one_week_demo.fragment;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.example.one_week_demo.BaseUrl;
import com.example.one_week_demo.IContact;
import com.example.one_week_demo.R;
import com.example.one_week_demo.adapter.MyLeftAdapter;
import com.example.one_week_demo.bean.LeftBean;
import com.example.one_week_demo.presenter.PresenterImpl;
import com.google.gson.Gson;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
public class LeftFragment extends Fragment implements IContact.IView {
@BindView(R.id.Left_Recy)
RecyclerView LeftRecy;
Unbinder unbinder;
private View mView;
private List<LeftBean.ResultBean> mList = new ArrayList<>();
private MyLeftAdapter mAdapter;
private PresenterImpl mPresenter;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.frag_left, container, false);
EventBus.getDefault().register(this);
unbinder = ButterKnife.bind(this, mView);
initRecy();
mPresenter = new PresenterImpl(this);
mPresenter.startRequest(BaseUrl.LEFT);
itemClick();
return mView;
}
private void initRecy() {
LinearLayoutManager manager = new LinearLayoutManager(getContext());
LeftRecy.setLayoutManager(manager);
mAdapter = new MyLeftAdapter(mList);
LeftRecy.setAdapter(mAdapter);
}
private void itemClick() {
mAdapter.setOnItemClick(new MyLeftAdapter.ItemClick() {
@Override
public void onItemClick(int position) {
LeftBean.ResultBean resultBean = mList.get(position);
EventBus.getDefault().post(resultBean.getId());
}
});
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void sendId(String id) {
}
@Override
public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();
}
@Override
public void success(String json) {
if (json != null) {
Gson gson = new Gson();
LeftBean leftBean = gson.fromJson(json, LeftBean.class);
mList.addAll(leftBean.getResult());
mAdapter.notifyDataSetChanged();
} else {
Toast.makeText(getContext(), "请求异常", Toast.LENGTH_SHORT).show();
}
}
@Override
public void error(String error) {
Log.e("error", error);
Toast.makeText(getContext(), error, Toast.LENGTH_SHORT).show();
}
@Override
public void onDestroy() {
super.onDestroy();
if (mAdapter != null) {
mAdapter.unBind();
}
if (unbinder != null) {
unbinder.unbind();
}
if (EventBus.getDefault().isRegistered(this)) {
EventBus.getDefault().unregister(this);
}
if(mPresenter!=null){
mPresenter.onDetach();
}
}
}
Right
package com.example.one_week_demo.fragment;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.example.one_week_demo.BaseUrl;
import com.example.one_week_demo.IContact;
import com.example.one_week_demo.R;
import com.example.one_week_demo.adapter.MyRightAdapter;
import com.example.one_week_demo.bean.RightBean;
import com.example.one_week_demo.presenter.PresenterImpl;
import com.google.gson.Gson;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
public class RightFragment extends Fragment implements IContact.IView {
@BindView(R.id.Right_Recy)
RecyclerView Right_Recy;
Unbinder unbinder;
private View mView;
private List<RightBean.ResultBean> mList = new ArrayList<>();
private MyRightAdapter mAdapter;
private PresenterImpl mPresenter;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.frag_right, container, false);
EventBus.getDefault().register(this);
unbinder = ButterKnife.bind(this, mView);
initRecy();
mPresenter = new PresenterImpl(this);
return mView;
}
private void initRecy() {
GridLayoutManager manager = new GridLayoutManager(getContext(), 2);
Right_Recy.setLayoutManager(manager);
mAdapter = new MyRightAdapter(mList, getContext());
Right_Recy.setAdapter(mAdapter);
}
@Override
public void success(String json) {
mList.clear();
if (json != null) {
Gson gson = new Gson();
RightBean rightBean = gson.fromJson(json, RightBean.class);
mList.addAll(rightBean.getResult());
mAdapter.notifyDataSetChanged();
} else {
Toast.makeText(getContext(), "请求异常", Toast.LENGTH_SHORT).show();
}
}
@Override
public void error(String error) {
Toast.makeText(getContext(), error, Toast.LENGTH_SHORT).show();
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void getId(String id) {
Log.e("id", id);
mPresenter.startRequest(BaseUrl.RIGHT + "?categoryId=" + id + "&page=1&count=10");
}
@Override
public void onDestroy() {
super.onDestroy();
if (mAdapter != null) {
mAdapter.unBind();
}
if (unbinder != null) {
unbinder.unbind();
}
if (EventBus.getDefault().isRegistered(this)) {
EventBus.getDefault().unregister(this);
}
if(mPresenter!=null){
mPresenter.onDetach();
}
}
}
LeftAdapter
package com.example.one_week_demo.adapter;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.one_week_demo.R;
import com.example.one_week_demo.bean.LeftBean;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
public class MyLeftAdapter extends RecyclerView.Adapter<MyLeftAdapter.Holder> {
private List<LeftBean.ResultBean> mList;
private Unbinder bind;
public MyLeftAdapter(List<LeftBean.ResultBean> mList) {
this.mList = mList;
}
@NonNull
@Override
public Holder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View view = View.inflate(viewGroup.getContext(), R.layout.item_left, null);
Holder holder = new Holder(view);
return holder;
}
@Override
public void onBindViewHolder(@NonNull Holder holder, final int i) {
holder.mText.setText(mList.get(i).getName() + "");
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mItem != null) {
mItem.onItemClick(i);
}
}
});
}
@Override
public int getItemCount() {
return mList.size();
}
public class Holder extends RecyclerView.ViewHolder {
@BindView(R.id.left_Text)
public TextView mText;
public Holder(@NonNull View itemView) {
super(itemView);
bind = ButterKnife.bind(this, itemView);
}
}
public void unBind() {
if (bind != null) {
bind.unbind();
}
}
public interface ItemClick {
void onItemClick(int position);
}
private ItemClick mItem;
public void setOnItemClick(ItemClick itemClick) {
this.mItem = itemClick;
}
}
RightAdapter
package com.example.one_week_demo.adapter;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.example.one_week_demo.R;
import com.example.one_week_demo.bean.RightBean;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
public class MyRightAdapter extends RecyclerView.Adapter<MyRightAdapter.Holder> {
private List<RightBean.ResultBean> mList;
private Unbinder bind;
private Context mContext;
public MyRightAdapter(List<RightBean.ResultBean> mList,Context context) {
this.mList = mList;
this.mContext = context;
}
@NonNull
@Override
public Holder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View view = View.inflate(mContext,R.layout.item_right,null);
Holder holder = new Holder(view);
return holder;
}
@Override
public void onBindViewHolder(@NonNull Holder holder, int i) {
Glide.with(mContext).load(mList.get(i).getMasterPic()).into(holder.mImage);
holder.mText.setText(mList.get(i).getCommodityName()+"");
}
@Override
public int getItemCount() {
return mList.size();
}
public class Holder extends RecyclerView.ViewHolder {
@BindView(R.id.Right_Image)
public ImageView mImage;
@BindView(R.id.Right_Text)
public TextView mText;
public Holder(@NonNull View itemView) {
super(itemView);
bind = ButterKnife.bind(this, itemView);
}
}
public void unBind(){
if (bind!=null){
bind.unbind();
}
}
}