MVP+recyclerview网络请求列表数据

本文介绍了一个基于MVP模式的Android应用实例,展示了如何使用RecyclerView组件结合OkHttp进行网络请求,加载并显示新闻列表数据。文章涵盖了自定义适配器、Gson解析、错误处理等关键技术点。

文件夹名adapter>>>>文件名NewsListAdapter

package com.bwie.mvpokrecyclerview.adapter;

import android.content.Context;
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.bwie.mvpokrecyclerview.R;
import com.bwie.mvpokrecyclerview.entity.NewsBean;

import java.util.List;


public class NewsListAdapter extends RecyclerView.Adapter<NewsListAdapter.ViewHolder> {
    private Context context;

    private List<NewsBean> list;

    public NewsListAdapter(Context context, List<NewsBean> list) {
        this.context = context;
        this.list = list;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = View.inflate(context, R.layout.item_news, null);
        ViewHolder holder = new ViewHolder(v);
        return holder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        Glide.with(context).load(list.get(position).getThumbnailPic01()).into(holder.imgLogo);
        holder.txtTitle.setText(list.get(position).getTitle());
        holder.txtTime.setText(list.get(position).getDate());
    }

    @Override
    public int getItemCount() {
        if (list == null) {
            return 0;
        }
        return list.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder {
        private ImageView imgLogo;
        private TextView txtTitle;
        private TextView txtTime;

        public ViewHolder(View itemView) {
            super(itemView);
            imgLogo = (ImageView) itemView.findViewById(R.id.img_logo);
            txtTitle = (TextView) itemView.findViewById(R.id.txt_title);
            txtTime = (TextView) itemView.findViewById(R.id.txt_time);
        }
    }
}

callback>>>>CallBack

public interface CallBack {
    void onSuccess(String tag, Object o);

    void onFailed(String tag, Exception e);
}

callback>>>>>INewsView

public interface INewsView {
    void success(String tag, List<NewsBean> news);

    void failed(String tag, Exception e);
}

entity>>>>>MessageBean

public class MessageBean {
    private String reason;
    @SerializedName("error_code")
    private int errorCode;

    private Result result;

    public String getReason() {
        return reason;
    }

    public void setReason(String reason) {
        this.reason = reason;
    }

    public int getErrorCode() {
        return errorCode;
    }

    public void setErrorCode(int errorCode) {
        this.errorCode = errorCode;
    }

    public Result getResult() {
        return result;
    }

    public void setResult(Result result) {
        this.result = result;
    }
}

entity>>>>>NewsBean

json数据每个接口都不一样

entity>>>>>Result

public class Result {
    private String stat;
    private List<NewsBean> data;

    public String getStat() {
        return stat;
    }

    public void setStat(String stat) {
        this.stat = stat;
    }

    public List<NewsBean> getData() {
        return data;
    }

    public void setData(List<NewsBean> data) {
        this.data = data;
    }
}

http>>>>>HttpUtils网络请求工具类

public class HttpUtils {
    private static final String TAG = "HttpUtils";
    private static volatile HttpUtils instance;

    private static Handler handler = new Handler();

    private HttpUtils() {

    }

    public static HttpUtils getInstance() {
        if (null == instance) {
            synchronized (HttpUtils.class) {
                if (instance == null) {
                    instance = new HttpUtils();
                }
            }
        }
        return instance;
    }


    /**
     * Get请求
     */
    public void get(String url, Map<String, String> map, final CallBack callBack,
                    final Class cls, final String tag) {
      
        if (TextUtils.isEmpty(url)) {
            return;
        }

        StringBuffer sb = new StringBuffer();
        sb.append(url);

        // 如果包含?说明是2.3类型
        if (url.contains("?")) {
            // 如果包含?并且?是最后一位,对应是2类型
            if (url.indexOf("?") == url.length() - 1) {

            } else {
                // 如果包含?并且?不是最后一位,对应是3类型
                sb.append("&");
            }
        } else {
            // 不包含?,对应的1类型
            sb.append("?");
        }

        // 遍历map集合进行拼接,拼接的形式是 key=value&
        for (Map.Entry<String, String> entry : map.entrySet()) {
            sb.append(entry.getKey())
                    .append("=")
                    .append(entry.getValue())
                    .append("&");
        }

        // 如果存在&号,把最后一个&去掉
        if (sb.indexOf("&") != -1) {
            sb.deleteCharAt(sb.lastIndexOf("&"));
        }

        Log.i(TAG, "get url: " + sb);

        OkHttpClient client = new OkHttpClient();

        final Request request = new Request.Builder()
                .get()
                .url(sb.toString())
                .build();

        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        // 通过自己传进来的回调接口对象回传回去
                        callBack.onFailed(tag, e);
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String result = response.body().string();
                // 请求成功之后做解析,通过自己的回调接口将数据返回回去
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        Object o;
                        if (TextUtils.isEmpty(result)) {
                            o = null;
                        } else {
                            o = GsonUtils.getInstance().fromJson(result, cls);
                        }
                        callBack.onSuccess(tag, o);
                    }
                });
            }
        });


    }
}



presaenter>>>>>>NewsPresenter   P层

public class NewsPresenter {
    private INewsView inv;

    public void attachView(INewsView inv) {
        this.inv = inv;
    }

    public void getNews() {
        //type=top&key=dbedecbcd1899c9785b95cc2d17131c5
        Map<String, String> map = new HashMap<>();
        map.put("type", "top");
        map.put("key", "dbedecbcd1899c9785b95cc2d17131c5");
        HttpUtils.getInstance().get("http://v.juhe.cn/toutiao/index", map, new CallBack() {
            @Override
            public void onSuccess(String tag, Object o) {
                MessageBean bean = (MessageBean) o;
                if (bean != null) {
                    List<NewsBean> data = bean.getResult().getData();
                    inv.success(tag, data);
                }
            }

            @Override
            public void onFailed(String tag, Exception e) {
                inv.failed(tag, e);
            }
        }, MessageBean.class, "news");
    }


    public void detachView() {
        if (inv != null) {
            inv = null;
        }

    }
}


utils>>>>>GsonUtils接口

public class GsonUtils {
    private static Gson instance;

    private GsonUtils() {

    }

    public static Gson getInstance() {
        if (instance == null) {
            instance = new Gson();
        }
        return instance;
    }
}

MainActivity

public class MainActivity extends AppCompatActivity implements INewsView {
    private static final String TAG = "MainActivity";

    private RecyclerView rvNews;

    private NewsPresenter presenter;

    private NewsListAdapter adapter;

    private List<NewsBean> list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        rvNews = (RecyclerView) findViewById(R.id.rv_news);

        list = new ArrayList<>();
        adapter = new NewsListAdapter(this, list);

        LinearLayoutManager manager = new LinearLayoutManager(this);
        rvNews.setLayoutManager(manager);
        rvNews.setAdapter(adapter);

        presenter = new NewsPresenter();
        presenter.attachView(this);

        presenter.getNews();
    }

    @Override
    public void success(String tag, List<NewsBean> news) {
        if (null != news) {
            list.addAll(news);
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    public void failed(String tag, Exception e) {
        Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
    }

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


需要导入的依赖

 compile 'com.squareup.okhttp3:okhttp:3.9.0'
    compile 'com.google.code.gson:gson:2.8.1'
  annotationProcessor 'com.github.bumptech.glide:compiler:4.3.1'

 compile 'com.android.support:recyclerview-v7:25.3.1'











评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值