首页
登录 | 注册

RecyclerView和okhttp结合 实现一个网络请求数据

视图层:

package bawe.com.day_okhttp_recyclerview_lianxi;


import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;

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

import bawe.com.day_okhttp_recyclerview_lianxi.Adpater.RecyclerviewAdpader;
import bawe.com.day_okhttp_recyclerview_lianxi.bean2.Newslist;
import bawe.com.day_okhttp_recyclerview_lianxi.presaenter.Presaenter;

public class MainActivity extends AppCompatActivity implements IView {

    private RecyclerView rlv;

    private List<Newslist> list=new ArrayList<Newslist>();
    private Presaenter presaenter;
    private RecyclerviewAdpader adpaader;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //查找控件
        rlv = (RecyclerView) findViewById(R.id.rlv_itme);


        //设置适配器
        adpaader = new RecyclerviewAdpader(this,list);
        //线性布局管理器
        LinearLayoutManager manager = new LinearLayoutManager(this);
        rlv.setLayoutManager(manager);
        rlv.setAdapter(adpaader);


        //new  P层
        presaenter = new Presaenter();
        //p层方法
        presaenter.attachView(this);
        //p层方法
        presaenter.getNews();


    }

    @Override
    public void success(String tag, List<Newslist> news) {
        if (null != news) {
            list.addAll(news);
            //刷新适配器
            adpaader.notifyDataSetChanged();
        }

    }

    @Override
    public void failed(String tag, Exception e) {

        Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
    }

//销毁的时候    调用P层的方法  防止内存泄漏问题
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (presaenter != null) {
            //调用P层的方法
            presaenter.detachView();
        }
    }
}


/**
 * 视图层接口
 */

public interface IView {

    void success( String tag,List<Newslist> news);
    void failed( String tag,Exception e);


}




模型层:

package bawe.com.day_okhttp_recyclerview_lianxi.Http;

import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;

import java.io.IOException;
import java.util.Map;

import bawe.com.day_okhttp_recyclerview_lianxi.utlis.GsonUtlis;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 模型层
 */

public class HttpUtils {

    private static final String TAG = "HttpUtils";

    private static Handler handler=new Handler();

    private static volatile HttpUtils instance;

    private HttpUtils(){

    }



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

    public void get(String url, Map<String,String> map, final CallBack callBack, final Class cls, final String tag){
        // http://www.baoidu.com/login?mobile=11111&password=11111&age=1&name=zw

        // 1.http://www.baoidu.com/login                --------? key=value&key=value
        // 2.http://www.baoidu.com/login?               --------- key=value&key=value
        // 3.http://www.baoidu.com/login?mobile=11111   -----&key=value&key=value


        if (TextUtils.isEmpty(url)){
            return;
        }
        StringBuffer sb = new StringBuffer();
        sb.append(url);

        if (url.contains("?")){
            //如果包含并且是最后一位,就是第二种类型
            if (url.indexOf("?")== url.length()-1){
            }else{
                //如果包含?  并且不是最后一位
                sb.append("&");
            }
        }else{
            //不包含?  对应的是第一种类型
            sb.append("?");
        }
        //遍历map集合进行拼接,拼接的形式是key=values
        for(Map.Entry<String,String> entry:map.entrySet()){
            sb.append(entry.getKey())
                    .append("=")
                    .append(entry.getValue())
                    .append("&");
        }
        //如果存在&号,把最后一个&去掉
        if (sb.indexOf("&")!=-1){
           // lastIndexOf 最后一个
            sb.deleteCharAt(sb.lastIndexOf("&"));
        }

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

        OkHttpClient client = new OkHttpClient();
        Request build = new Request.Builder()
                .get()
                .url(sb.toString())
                .build();

        Call call = client.newCall(build);
        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 reutl = response.body().string();
               //请求成功之后解析,通过自己的回调接口将数据传输回去
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        Object o;
                        //如果是空的话
                        if (TextUtils.isEmpty(reutl)){
                            o=null;
                            Log.i(TAG,"为空!!!!!!!!!"+o);
                        }else{
                            o = GsonUtlis.getInstance().fromJson(reutl, cls);
                            Log.i(TAG,"不不不不不不为空!!!!!!!!!"+o);
                        }
                        callBack.onSuccess(tag,o);
                    }
                });
            }
        });
    }

}

/**
 * 模型层接口
 */

public interface CallBack {

    void onSuccess(String tag, Object o);
    void onFailed(String tag, Exception e);
}



presaenter层(p层):

package bawe.com.day_okhttp_recyclerview_lianxi.presaenter;

import java.util.HashMap;
import java.util.List;

import bawe.com.day_okhttp_recyclerview_lianxi.bean2.JsonRootBean;
import bawe.com.day_okhttp_recyclerview_lianxi.Http.CallBack;
import bawe.com.day_okhttp_recyclerview_lianxi.Http.HttpUtils;
import bawe.com.day_okhttp_recyclerview_lianxi.IView;
import bawe.com.day_okhttp_recyclerview_lianxi.bean2.Newslist;

/**
 * p层
 */

public class Presaenter {

    private IView iv;
    public void attachView(IView iv){
        this.iv=iv;
    }

    public void getNews(){

        HashMap<String, String > map = new HashMap<>();

//        map.put("type", "top");
//        map.put("key", "dbedecbcd1899c9785b95cc2d17131c5");
                map.put("num", "10");
        map.put("key", "4a82473783694ddebd495d47b16c906e");

        HttpUtils.getInstance().get("http://api.tianapi.com/meinv/",map, new CallBack() {
            @Override
            public void onSuccess(String tag, Object o) {
                JsonRootBean bean= (JsonRootBean) o;

                if (bean!=null){
                    List<Newslist> data = bean.getNewslist();
                    iv.success(tag,data);

                }
            }

            @Override
            public void onFailed(String tag, Exception e) {

                iv.failed(tag,e);
            }
        }, JsonRootBean.class,"news");
    }



    //定义一个方法让iv等于空      防止内存泄漏问题
    public void detachView() {
        if (iv != null) {
            iv = null;
        }

    }
}





RecyclerView适配器:

package bawe.com.day_okhttp_recyclerview_lianxi.Adpater;

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 java.util.List;

import bawe.com.day_okhttp_recyclerview_lianxi.R;
import bawe.com.day_okhttp_recyclerview_lianxi.bean2.Newslist;


/**
 * Created by 迷人的脚毛!! on 2017/11/9.
 */

public class RecyclerviewAdpader extends RecyclerView.Adapter<RecyclerviewAdpader.ViewHolder> {

    private Context context;
    private List<Newslist> list;

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

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = View.inflate(context, R.layout.recyclerview_itme, null);

        ViewHolder viewHolder = new ViewHolder(view);

        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        Glide.with(context).load(list.get(position).getPicUrl()).into(holder.img);
        holder.name.setText(list.get(position).getTitle());

    }

    @Override
    public int getItemCount() {

        if (list == null) {
            return 0;
        }

        return list.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder{

        private  ImageView img;
        private  TextView name ;
        public ViewHolder(View itemView) {
            super(itemView);
            //查找 控件
            img= (ImageView) itemView.findViewById(R.id.img_tu);
            name= (TextView) itemView.findViewById(R.id.tv_name);

        }
    }
}



单列模式 Gson  类(其实就是一个new  Gson的过程,然后设置成单例模式):

/**
 * Created by 迷人的脚毛!! on 2017/11/9.
 */

public class GsonUtlis {
    //Gson的单列模式
    private static Gson instance;
    private GsonUtlis(){

    }

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




2020 jeepxie.net webmaster#jeepxie.net
10 q. 0.009 s.
京ICP备10005923号