mvp请求网络数据

M层

package com.example.xx.zkmn2.model;

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

import com.example.xx.zkmn2.callback.CallBack;
import com.example.xx.zkmn2.utils.GsonUtils;
import com.example.xx.zkmn2.utils.LoggingInterceptor;

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

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 作者:戈鹏
 * on 2017/11/9 21:40
 */

public class HttpUtils {

    private static final String TAG = "HttpUtils";
    private static volatile HttpUtils instance;

    Handler handler=new Handler();

    public 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 cla, final String tag){

        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("?");
        }

        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.Builder().addInterceptor(new LoggingInterceptor()).build();

        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();
                Log.e(TAG, "onResponse: result--"+result);
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        Object o;
                        if (TextUtils.isEmpty(result)) {
                            o = null;
                        } else {
                            o = GsonUtils.getInstance().fromJson(result, cla);
                        }
                        //Log.e(TAG, "onResponse: bean--"+);
                        callBack.onSuccess(tag, o);
                    }
                });
            }
        });

    }
}

P层

package com.example.xx.zkmn2.presenter;


import android.util.Log;

import com.example.xx.zkmn2.bean.MusicBean;
import com.example.xx.zkmn2.bean.UserBean;
import com.example.xx.zkmn2.callback.CallBack;
import com.example.xx.zkmn2.callback.INewView;
import com.example.xx.zkmn2.model.HttpUtils;

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

/**
 * 作者:戈鹏
 * on 2017/11/9 22:49
 */

public class NewsPresenter {
    private static final String TAG = "NewsPresenter";
    private INewView inv;
    public void attachView(INewView inv){
        this.inv=inv;

    }

    public void get(Map<String,String> map){

        HttpUtils.getInstance().get("http://tingapi.ting.baidu.com/v1/restserver/ting", map, new CallBack() {


            @Override
            public void onSuccess(String tag, Object o) {
                MusicBean musicBean= (MusicBean) o;

                if(musicBean!=null){
                    List<UserBean> results=new ArrayList<UserBean>();
                    List<MusicBean.SongListBean> song_list = musicBean.getSong_list();
                    for (MusicBean.SongListBean i: song_list) {
                        UserBean userBean = new UserBean(i.getPic_small(), i.getTitle(), i.getAuthor());

                        results.add(userBean);
                        Log.e(TAG, "onSuccess: result"+userBean.toString() );
                    }
                    inv.success(tag,results);
                }
            }

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


    }

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

}


M层

package com.example.xx.zkmn2.frag;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.example.xx.zkmn2.R;
import com.example.xx.zkmn2.adapter.XrvAdapter;
import com.example.xx.zkmn2.bean.UserBean;
import com.example.xx.zkmn2.callback.INewView;
import com.example.xx.zkmn2.presenter.NewsPresenter;
import com.jcodecraeer.xrecyclerview.XRecyclerView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 作者:戈鹏
 * on 2017/11/12 17:49
 */

public class Frag2List extends Fragment implements XRecyclerView.LoadingListener, INewView, XrvAdapter.OnItemClick {
    private View view;
    private XRecyclerView xRecyclerView;
    private NewsPresenter presenter;
    private List<UserBean> listuser=new ArrayList<>();
    private XrvAdapter xrvAdapter;
    int page=1;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.list_frag, container, false);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        xRecyclerView = view.findViewById(R.id.xrecyclerview);

        xRecyclerView.setLoadingListener(this);
        xRecyclerView.setPullRefreshEnabled(true);
        xRecyclerView.setLoadingMoreEnabled(true);

        presenter = new NewsPresenter();
        presenter.attachView(this);
        Map<String,String> map = new HashMap<>();
        map.put("method", "baidu.ting.billboard.billList");
        map.put("type", "1");
        map.put("size", "10");
        map.put("offset", "0");
        presenter.get(map);


        xrvAdapter = new XrvAdapter(getActivity(), listuser);

        xrvAdapter.setOnItemClick(this);

        LinearLayoutManager manager=new LinearLayoutManager(getActivity());
        xRecyclerView.setLayoutManager(manager);

        xRecyclerView.setAdapter(xrvAdapter);


    }


    @Override
    public void onRefresh() {
        listuser.clear();
        page=1;
        Map<String,String> map = new HashMap<>();
        map.put("method", "baidu.ting.billboard.billList");
        map.put("type", "1");
        map.put("size", "10");
        map.put("offset", "0");
        presenter.get(map);
        xRecyclerView.refreshComplete();
    }

    @Override
    public void onLoadMore() {
        page++;
        Map<String,String> map = new HashMap<>();
        map.put("method", "baidu.ting.billboard.billList");
        map.put("type", page+"");
        map.put("size", "10");
        map.put("offset", "0");
        presenter.get(map);
        xRecyclerView.refreshComplete();
    }

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

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

    //点击事件
    @Override
    public void onItem(int position) {
        Toast.makeText(getActivity(),"点击实际"+position,Toast.LENGTH_SHORT).show();
    }
}

两个接口

public interface INewView {
    void success(String tag, List<UserBean> news);
    void failed(String tag, Exception e);
}

public interface CallBack {
    void onSuccess(String tag, Object o);
    void onFailed(String tag, Exception e);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值