电商项目mvp框架和二级联动显示列表Retrofit网络工具类实现

前言
Retrofit 是一个 RESTful 的 HTTP 网络请求框架的封装,网络请求的工作本质上是 OkHttp 完成,而 Retrofit 仅负责 网络请求接口的封装

在这里插入图片描述

在这里插入图片描述

需要添加的依赖

apply plugin: 'com.android.application'
apply plugin: 'com.jakewharton.butterknife'
apply plugin: 'org.greenrobot.greendao' // apply plugin
android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"
    defaultConfig {
        applicationId "com.bawei.dianshangzhoukao2moni"
        minSdkVersion 15
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"

        compileOptions {
            sourceCompatibility JavaVersion.VERSION_1_8
            targetCompatibility JavaVersion.VERSION_1_8
        }
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    greendao {
        schemaVersion 1
        daoPackage 'com.bawei.dianshangzhoukao2moni'
        targetGenDir 'src/main/java'
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

    //recycelrview,列表控件,和listview差不多,升级版
    implementation 'androidx.recyclerview:recyclerview:1.1.0'

    //EventBus依赖
    implementation 'org.greenrobot:eventbus:3.1.1'


    //retrofit辅助 ,gson解析的库
    implementation 'com.squareup.retrofit2:converter-gson:2.6.2'

    implementation 'com.jakewharton:butterknife:10.2.1'
    annotationProcessor 'com.jakewharton:butterknife-compiler:10.2.1'
    implementation 'com.github.tongchexinfeitao:QRCodeLibrary:1.0'

    implementation 'com.squareup.retrofit2:retrofit:2.6.2'    //Retrofit
    implementation 'com.squareup.retrofit2:converter-gson:2.0.2'
    implementation 'com.squareup.retrofit2:adapter-rxjava2:2.6.2' // 必要依赖,和Rxjava结合必须用到,下面会提到
    implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'

    //okhttp日志拦截器
    implementation 'com.squareup.okhttp3:logging-interceptor:4.2.2'


//glidee
    implementation("com.github.bumptech.glide:glide:4.10.0") {
        exclude group: "com.android.support"
    }

    //greendao 数据存储orm框架
    implementation 'org.greenrobot:greendao:3.2.2' // add library

    // if u use AndroidX, use the following,网络判断工具类
    implementation 'com.blankj:utilcodex:1.26.0'

}

根目录

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        google()
        jcenter()
        mavenCentral()
        maven { url 'https://jitpack.io' }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.2'
        classpath 'com.jakewharton:butterknife-gradle-plugin:10.2.1'

        classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        mavenCentral()
        maven { url 'https://jitpack.io' }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Mvp

v层

public interface IBaseView {
}

m层

public interface IBaseModel {
}

p层

public abstract class BasePresenter<M extends IBaseModel,V extends IBaseView> {
    public M model;
    public WeakReference<V> weakReference;

    public BasePresenter(){
        model=initModel();
    }

    public void attch(V v){
        weakReference=new WeakReference<>(v);
    }

    protected abstract M initModel();

    public void death(){
        if (weakReference!=null) {
            weakReference.clear();
            weakReference = null;
        }
    }

    public V getView(){
        return weakReference.get();
    }

BaseActivity

public abstract class BaseActivity<P extends BasePresenter> extends AppCompatActivity implements IBaseView {


    public P presenter;
     public Unbinder unbinder;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(layoutId());
        unbinder= ButterKnife.bind(this);

        presenter=initPresenter();
        if (presenter!=null){
            presenter.attch(this);
        }

        initView();

        initData();
    }

    protected abstract void initData();

    protected abstract void initView();

    protected abstract P initPresenter();

    protected abstract int layoutId();

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (presenter!=null) {
            presenter.death();
        }

        if (unbinder!=null){
            unbinder.unbind();
        }
    }
}

contract

public interface ProductContract {

    interface IModel extends IBaseModel {
        //左侧分类
        void getLeft(ImodelCallBack imodelCallBack);
        //根据二级分类查询之下的商品
        void getSecond(HashMap<String,String> params,ImodelCallBack imodelCallBack);

        interface ImodelCallBack{
            void success(Object data);
            void failure(Object data);
        }
    }

    interface IView extends IBaseView {
        void success(Object data);
        void failure(Object data);

    }

    interface IPresenter{
        //左侧分类
        void getLeft();
        //根据二级分类查询之下的商品
        void getSecond(HashMap<String,String> params);

    }
}

Api

public class Api {

    public static String BASE_URL="http://172.17.8.100/";
}

LeftService

public interface LeftService {

    @GET("small/commodity/v1/findCategory")
    Observable<ProductEntity> getProduct();


    @GET("small/commodity/v1/findCommodityByCategory")
    Observable<HomeEntity> getHome(@QueryMap HashMap<String,String> params);
}

RetrofitUtils

public class RetrofitUtils {


    private static RetrofitUtils retrofitUtils;

    private Retrofit retrofit;
    private RetrofitUtils(){

        OkHttpClient okHttpClient=new OkHttpClient.Builder()
                .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
                .build();

        //第一步
        retrofit=new Retrofit.Builder()
                .baseUrl(Api.BASE_URL)
                .client(okHttpClient)//关联okhttp
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
    }
    public static RetrofitUtils getInstance() {
        if (retrofitUtils==null){
            synchronized (RetrofitUtils.class){
                if (retrofitUtils==null){
                    retrofitUtils=new RetrofitUtils();
                }
            }
        }
        return retrofitUtils;
    }




    //动态获取接口管理类对象
    public<T> T createService(Class<T> tClass){
        T t=retrofit.create(tClass);

        return t;
    }

    public boolean hasNet(Context context){
        ConnectivityManager connectivityManager= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        final NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();

        if (activeNetworkInfo!=null&&activeNetworkInfo.isAvailable()){
            return true;
        }

        return false;
    }

    //判断是否有网
    public boolean isNet(){
        return NetworkUtils.isConnected();

    }

}

HomeModel

public class HomeModel implements ProductContract.IModel {
    @Override
    public void getLeft(ImodelCallBack imodelCallBack) {

        RetrofitUtils.getInstance().createService(LeftService.class)
                .getProduct() //获取rxjava的被观察者,observable对象
        .subscribeOn(Schedulers.io())//指定obserable被观察者所在线程(请求网络的线程)
                .observeOn(AndroidSchedulers.mainThread())//指定observer观察者所在线程(响应后的数据所在的线程,onnext方法运行的线程);
                .subscribe(new Observer<ProductEntity>() {//订阅关系

                    //是否订阅成功
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    //接受成功
                    @Override
                    public void onNext(ProductEntity productEntity) {
                        imodelCallBack.success(productEntity);
                    }

                    //失败
                    @Override
                    public void onError(Throwable e) {

                    }

                    //接受完成
                    @Override
                    public void onComplete() {

                    }
                });



    }

    @Override
    public void getSecond(HashMap<String, String> params, ImodelCallBack imodelCallBack) {
        RetrofitUtils.getInstance().createService(LeftService.class)
                .getHome(params)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<HomeEntity>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(HomeEntity homeEntity) {
                        imodelCallBack.success(homeEntity);
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }



}

HomePresenter

public class HomePresenter extends BasePresenter<HomeModel, ProductContract.IView> implements ProductContract.IPresenter {
    @Override
    public void getLeft() {
        model.getLeft( new ProductContract.IModel.ImodelCallBack() {
            @Override
            public void success(Object data) {
                getView().success(data);
            }

            @Override
            public void failure(Object data) {

            }
        });
    }

    @Override
    public void getSecond(HashMap<String, String> params) {
        model.getSecond(params, new ProductContract.IModel.ImodelCallBack() {
            @Override
            public void success(Object data) {
                getView().success(data);
            }

            @Override
            public void failure(Object data) {

            }
        });
    }


    @Override
    protected HomeModel initModel() {
        return new HomeModel();
    }
}

LeftAdapter

public class LeftAdapter extends RecyclerView.Adapter<LeftAdapter.MyViewHorlder> {


    private Context context;
    private List<ProductEntity.ResultBean.SecondCategoryVoBean> list1;


    public LeftAdapter(Context context, List<ProductEntity.ResultBean.SecondCategoryVoBean> list1) {
        this.context = context;
        this.list1 = list1;
    }

    @NonNull
    @Override
    public MyViewHorlder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        final View inflate = View.inflate(context, R.layout.left_item_layout, null);

        final MyViewHorlder myViewHorlder = new MyViewHorlder(inflate);

        return myViewHorlder;
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHorlder holder, int position) {
        holder.tv.setText(list1.get(position).getName());

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                recLeftonclick.getLeftpnClick(list1.get(position).getId());
            }
        });

    }

    @Override
    public int getItemCount() {
        return list1.size();
    }

    class MyViewHorlder extends RecyclerView.ViewHolder {

        @BindView(R.id.tv)
        TextView tv;
        public MyViewHorlder(@NonNull View itemView) {
            super(itemView);

            ButterKnife.bind(this, itemView);
        }
    }


    private RecLeftonclick recLeftonclick;

    public void setRecLeftonclick(RecLeftonclick recLeftonclick) {
        this.recLeftonclick = recLeftonclick;
    }

    public interface RecLeftonclick{
        void getLeftpnClick(String id);
    }
}

RightAdapter

public class RightAdapter extends RecyclerView.Adapter<RightAdapter.MyViewHorlder> {



    private Context context;
    private List<HomeEntity.ResultBean> list;


    public RightAdapter(Context context, List<HomeEntity.ResultBean> list) {
        this.context = context;
        this.list = list;
    }

    @NonNull
    @Override
    public MyViewHorlder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        final View inflate = View.inflate(context, R.layout.right_item_layout, null);

        final MyViewHorlder myViewHorlder = new MyViewHorlder(inflate);

        return myViewHorlder;
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHorlder holder, int position) {
        holder.tv.setText(list.get(position).getCommodityName());

        Glide.with(context).load(list.get(position).getMasterPic())
                .placeholder(R.mipmap.ic_launcher)
                .error(R.mipmap.ic_launcher)
                .circleCrop()
                .into(holder.iv);

    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    class MyViewHorlder extends RecyclerView.ViewHolder {

        @BindView(R.id.iv)
        ImageView iv;
        @BindView(R.id.tv)
        TextView tv;
        public MyViewHorlder(@NonNull View itemView) {
            super(itemView);

            ButterKnife.bind(this, itemView);
        }
    }



}

MainActivity

public class MainActivity extends BaseActivity<HomePresenter> implements ProductContract.IView {


    @BindView(R.id.rv_left)
    RecyclerView rvLeft;
    @BindView(R.id.rv_right)
    RecyclerView rvRight;
    private HashMap<String, String> params;
    private DaoSession daoSession;

    @Override
    protected void initData() {

    }

    @Override
    protected void initView() {

        //注册Eventbus
        EventBus.getDefault().register(this);
        rvLeft.setLayoutManager(new LinearLayoutManager(this));
        rvRight.setLayoutManager(new LinearLayoutManager(this));

        //数据库帮助类,创建数据库,以zhy为名字
        DaoMaster.DevOpenHelper helper=new DaoMaster.DevOpenHelper(this,"zhydb");

        //创建数据库的读写工具类
        SQLiteDatabase sqLiteDatabase=helper.getWritableDatabase();

        //创建daomaster对象
        DaoMaster daoMaster=new DaoMaster(sqLiteDatabase);

        //创建daosession
        daoSession = daoMaster.newSession();

        if (RetrofitUtils.getInstance().hasNet(this)){//判断网络
            presenter.getLeft();
        }else {
            final List<GreendaoEntity> greendaoEntities = daoSession.getGreendaoEntityDao().loadAll();
            if (greendaoEntities!=null&&greendaoEntities.size()>0){
                final GreendaoEntity greendaoEntity = greendaoEntities.get(0);//第0条数据
                String json=greendaoEntity.getJson();
                final ProductEntity productEntity = new Gson().fromJson(json, ProductEntity.class);
                //只获取一级女装下的二级列表
                final LeftAdapter leftAdapter = new LeftAdapter(this, productEntity.getResult().get(0).getSecondCategoryVo());

                rvLeft.setAdapter(leftAdapter);

                //接口回调的实现,得到值了
                leftAdapter.setRecLeftonclick(new LeftAdapter.RecLeftonclick() {
                    @Override
                    public void getLeftpnClick(String id) {

                        EventBus.getDefault().post(id);
                    }
                });

            }
        }

    }

    @Override
    protected HomePresenter initPresenter() {
        return new HomePresenter();
    }

    @Override
    protected int layoutId() {
        return R.layout.activity_main;
    }

    @Override
    public void success(Object data) {

        //首次请求左侧分类json串
        if (data instanceof ProductEntity){

            ProductEntity productEntity= (ProductEntity) data;

            final LeftAdapter leftAdapter = new LeftAdapter(this, productEntity.getResult().get(0).getSecondCategoryVo());

            rvLeft.setAdapter(leftAdapter);

            leftAdapter.setRecLeftonclick(new LeftAdapter.RecLeftonclick() {
                @Override
                public void getLeftpnClick(String id) {

                    //发送
                    EventBus.getDefault().post(id);
                }
            });



            //缓存数据
            GreendaoEntity greendaoEntity=new GreendaoEntity();
            String json=new Gson().toJson(productEntity);
            greendaoEntity.setJson(json);
            greendaoEntity.setTag("分类");
            daoSession.getGreendaoEntityDao().insert(greendaoEntity);



        }else if (data instanceof HomeEntity){
            final List<HomeEntity.ResultBean> result1 = ((HomeEntity) data).getResult();

            final RightAdapter rightAdapter = new RightAdapter(this, result1);

            rvRight.setAdapter(rightAdapter);

        }
    }


    //接收二级类目的id
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getId(String id){
        params = new HashMap<>();

        params.put("categoryId",id);
        params.put("page","1");
        params.put("count","10");

        presenter.getSecond(params);
    }

    @Override
    public void failure(Object data) {

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

        EventBus.getDefault().unregister(this);
    }
}

权限


<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

GreendaoEntity

@Entity
public class GreendaoEntity {

    @Id(autoincrement = true)
    private Long id;

    private String json;

    private String tag;//key区分哪个json

加完依赖然后编译一下,green3个类就建好了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值