MVP+OkhttpClient二次封装+Listview

build.gradle页面

api 'com.android.support:recyclerview-v7:27.1.1'

    //okhttp
    api 'com.squareup.okhttp3:okhttp:3.12.0'
    compile 'com.squareup.okhttp3:logging-interceptor:3.12.0'
    implementation 'com.google.code.gson:gson:2.8.5'

    //黄油刀
    implementation 'com.jakewharton:butterknife:8.7.0'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.7.0'

    //图片加载框架,glide
    implementation 'com.github.bumptech.glide:glide:3.7.0'

**

MainActivity页面

**

package com.example.y700_15.news_homes.activity;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.y700_15.news_homes.R;
import com.example.y700_15.news_homes.adapter.MyBaseAdapter;
import com.example.y700_15.news_homes.contract.CqiYuelei;
import com.example.y700_15.news_homes.entity.UserEntity;
import com.example.y700_15.news_homes.presenter.Presenter;

import java.util.HashMap;

public class MainActivity extends AppCompatActivity implements CqiYuelei.IoDataView {
    private EditText editText;
    private TextView textView;
    private ListView listView;

    private Presenter presenter;
    private MyBaseAdapter myBaseAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //获取资源ID
        initView();
        //实现新的借还
        initData();

        listView.setAdapter(myBaseAdapter);

        dianji();
    }

    /**
     * 点击事件
     */
    private void dianji(){
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String s = editText.getText().toString();
                HashMap<String,String> hashMap = new HashMap<>();
                hashMap.put("keywords",s);
                presenter.getData(hashMap);
            }
        });

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(MainActivity.this,"点击事件",Toast.LENGTH_SHORT).show();
            }
        });

        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

                Toast.makeText(MainActivity.this,"长按点击事件",Toast.LENGTH_SHORT).show();

                return true;
            }
        });
    }

    /**
     * 加载数据
     */
    public void initData(){
        presenter = new Presenter(this);
        myBaseAdapter = new MyBaseAdapter(this);
    }

    /**
     * 获取资源ID
     */
    public void initView(){
        editText = findViewById(R.id.edit_text);
        textView = findViewById(R.id.text01);
        listView = findViewById(R.id.list_view);
    }

    /**
     * 失败方法
     * @param msg
     */
    @Override
    public void failure(String msg) {
        Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
    }

    /**
     * 成功方法
     * @param s
     */
    @Override
    public void success(UserEntity s) {
        Toast.makeText(MainActivity.this, "成功", Toast.LENGTH_SHORT).show();
        myBaseAdapter.setList(s.data);
    }
}

**

activity_main布局页面(布局不唯一)

**

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".activity.MainActivity">

    <LinearLayout
        android:paddingBottom="10dp"
        android:paddingLeft="2dp"
        android:paddingRight="2dp"
        android:paddingTop="10dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ImageView
            android:id="@+id/img"
            android:layout_width="wrap_content"
            android:layout_height="50dp"
            android:src="@mipmap/ic_launcher"
            />
        <EditText
            android:id="@+id/edit_text"
            android:background="@drawable/yuanjiaobuju"
            android:layout_width="wrap_content"
            android:layout_height="50dp"
            android:layout_weight="1"
            android:paddingLeft="30dp"
            android:hint="请输入您想要的。。。"
            />
        
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="50dp"
            android:id="@+id/text01"
            android:text="搜索"
            android:textSize="20dp"
            />
    </LinearLayout>

    <ListView
        android:id="@+id/list_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        ></ListView>

</LinearLayout>

Api网络接口类

package com.example.y700_15.news_homes.api;

public class Api {
    public static String urlstr = "http://www.zhaoapi.cn/product/searchProducts";
}

**

OkhttpCallback页面

**

package com.example.y700_15.news_homes.net;

import com.example.y700_15.news_homes.entity.UserEntity;

public interface OkhttpCallback {
    void failure(String msg);
    void success(UserEntity s);
}

**

OkhttpUtils页面

**

package com.example.y700_15.news_homes.net;

import android.os.Handler;

import com.example.y700_15.news_homes.entity.UserEntity;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;

/**
 * okhttp二次封装,封装网络框架
 */
public class OkhttpUtils {

    private Handler handler = new Handler();

    private OkHttpClient okHttpClient;

    private static OkhttpUtils mInstance;

    private OkhttpUtils(){
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        okHttpClient = new OkHttpClient.Builder()
                .addNetworkInterceptor(loggingInterceptor)
                .writeTimeout(5, TimeUnit.SECONDS)
                .readTimeout(5, TimeUnit.SECONDS)
                .connectTimeout(5, TimeUnit.SECONDS)
                .build();

    }

    //创建实例,双重检验锁
    public static OkhttpUtils getmInstance(){
        if (mInstance == null){
            synchronized (OkhttpUtils.class){
                if (mInstance == null){
                    mInstance = new OkhttpUtils();
                }
            }
        }
        return mInstance;
    }

    /**
     * get请求方法
     */

    public void doGet(String url, final OkhttpCallback requestCallback){
        //创建request获取接口数据
        Request request = new Request.Builder().url(url).get().build();
        //new Call
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                if (requestCallback != null){
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            requestCallback.failure("网络异常");
                        }
                    });
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //创建一个string对象,获取响应的数据
                final String result = response.body().string();
                final UserEntity entity = new Gson().fromJson(result,UserEntity.class);
                if (requestCallback != null){
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            requestCallback.success(entity);
                        }
                    });
                }
            }
        });
    }

    /**
     * post请求方式
     */
    public void doPost(String url, HashMap<String, String> parmas, final OkhttpCallback callback){

        FormBody.Builder builder = new FormBody.Builder();

        for (Map.Entry<String, String> map : parmas.entrySet()){
            builder.add(map.getKey(),map.getValue());
        }

        RequestBody requestBody = builder.build();

        Request request = new Request.Builder().url(url).post(requestBody).build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                if (callback != null){
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            callback.failure("网络异常");
                        }
                    });
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                if (callback != null){
                    if (200 == response.code()){
                        final String result = response.body().string();
                        final UserEntity entity = new Gson().fromJson(result, UserEntity.class);
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                callback.success(entity);
                            }
                        });
                    }
                }
            }
        });


    }

    /**
     * 取消所有请求,好处:节省开销:内存开销,CPU的开销(线程开销)
     */
    public void cancelAllTask(){
        if (okHttpClient != null){
            okHttpClient.dispatcher().cancelAll();
        }
    }
}

契约类 CqiYuelei页面

package com.example.y700_15.news_homes.contract;

import com.example.y700_15.news_homes.entity.UserEntity;
import com.example.y700_15.news_homes.net.OkhttpCallback;

import java.util.HashMap;

public interface CqiYuelei {

    /**
     * model层的实现方法
     */
    public interface IoDataModer{
        void getDataModel(HashMap<String,String> hashMap, OkhttpCallback callback);
    }

    /**
     * 定义一个抽象方法
     */
    public abstract class DataPresenter{
        public abstract void getData(HashMap<String,String> hashMap);
    }

    /**
     * 定义一个view层方法
     */
    public interface IoDataView{
        void failure(String msg);
        void success(UserEntity s);
    }

}

**

Model层 DataModle页面

**

package com.example.y700_15.news_homes.model;

import android.os.Handler;

import com.example.y700_15.news_homes.api.Api;
import com.example.y700_15.news_homes.contract.CqiYuelei;
import com.example.y700_15.news_homes.entity.UserEntity;
import com.example.y700_15.news_homes.net.OkhttpCallback;
import com.example.y700_15.news_homes.net.OkhttpUtils;

import java.util.HashMap;

public class DataModle implements CqiYuelei.IoDataModer {
    private Handler handler = new Handler();

    //调用工具类传递数据
    @Override
    public void getDataModel(HashMap<String, String> hashMap, final OkhttpCallback callback) {
        OkhttpUtils.getmInstance().doPost(Api.urlstr, hashMap, new OkhttpCallback() {
            @Override
            public void failure(final String msg) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        callback.failure(msg);
                    }
                });
            }

            @Override
            public void success(UserEntity s) {
                callback.success(s);
            }
        });
    }
}

**

P层 Presenter页面

**

package com.example.y700_15.news_homes.presenter;

import com.example.y700_15.news_homes.contract.CqiYuelei;
import com.example.y700_15.news_homes.entity.UserEntity;
import com.example.y700_15.news_homes.model.DataModle;
import com.example.y700_15.news_homes.net.OkhttpCallback;

import java.util.HashMap;

public class Presenter extends CqiYuelei.DataPresenter {

    private DataModle dataModle;
    private CqiYuelei.IoDataView ioDataView;

    public Presenter(CqiYuelei.IoDataView ioDataView) {
        dataModle = new DataModle();
        this.ioDataView = ioDataView;
    }

    @Override
    public void getData(HashMap<String, String> hashMap) {

        final String s = hashMap.get("keywords");

        if (s!=null){
            dataModle.getDataModel(hashMap, new OkhttpCallback() {
                @Override
                public void failure(String msg) {
                    ioDataView.failure(msg);
                }

                @Override
                public void success(UserEntity s) {
                    ioDataView.success(s);
                }
            });
        }else {
            return;
        }
    }
}

**

Bean类 UserEntity页面

**

package com.example.y700_15.news_homes.entity;

import java.util.List;

public class UserEntity {
    public String msg;
    public String code;
    public List<DataBean> data;

    public class DataBean{
        public String title;
        public String images;
    }
}

**

adapter MyBaseAdapter页面

**

package com.example.y700_15.news_homes.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.y700_15.news_homes.R;
import com.example.y700_15.news_homes.entity.UserEntity;

import java.util.ArrayList;
import java.util.List;

public class MyBaseAdapter extends BaseAdapter {

    private List<UserEntity.DataBean> list;
    private Context context;

    public MyBaseAdapter(Context context) {
        this.context = context;
        list = new ArrayList<>();
    }

    public void setList(List<UserEntity.DataBean> slist) {
        list.clear();
        if (slist!=null){
            list.addAll(slist);
        }
        notifyDataSetChanged();
    }

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

    @Override
    public UserEntity.DataBean getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView==null){
            convertView = LayoutInflater.from(context).inflate(R.layout.item,parent,false);
            holder = new ViewHolder(convertView);
        }else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.textView.setText(getItem(position).title);

        String[] split = getItem(position).images.split("\\|");

        Glide.with(context).load(split[0]).into(holder.imageView);

        return convertView;
    }

    class ViewHolder{
        private ImageView imageView;
        private TextView textView;

        public ViewHolder(View convertView){
            imageView = convertView.findViewById(R.id.img1);
            textView = convertView.findViewById(R.id.text1);
            convertView.setTag(this);
        }
    }
}

**

item布局页面

**

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="20dp"
    android:background="#fff"
    >
    <ImageView
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:id="@+id/img1"
        />
    <TextView
        android:id="@+id/text1"
        android:textSize="30sp"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值