Android--------在Fragment中通过MVP模式用Okhttp进行数据请求

时间:2024-03-13 19:25:20

1.定义一个里面有两个方法的接口(NetDataCallbact);

public interface NetDataCallback {
    void err(int code,String st);
    void callback(String str);
}

2.OkHttp网络请求的工具类(HttpUtils):


public class HttpUtils {
    private NetDataCallback netDataCallback;
     public void getdata(String url, final NetDataCallback netDataCallback) {
             //初始化一个 OkHttpClient 并且设置连接和读取超时时间
             OkHttpClient okhttp = new OkHttpClient.Builder()
                     .connectTimeout(10, TimeUnit.SECONDS)
                     .readTimeout(20, TimeUnit.SECONDS)
                     .build();
             //构造一个Request对象
             Request request = new Request.Builder().url(url).build();
             //通过request的对象去构造得到一个Call对象
             //Call call = okhttp.newCall(request);
         Call call = okhttp.newCall(request);
         //调用的是call.enqueue,将call加入调度队列,然后等待任务执行完成,我们在Callback中即可得到结果。
         call.enqueue(new Callback() {
             @Override
             public void onFailure(Call call, IOException e) {
                 netDataCallback.err(500,e.getMessage());
             }

             @Override
             public void onResponse(Call call, Response response) throws IOException {
            netDataCallback.callback(response.body().string());

             }
         });
         }
}

3.V层定义的一个里面两个方法的接口(Fm2view):


public interface Fm2View {
    void successfulCallback(String str);
    void errCallback(int code,String msg);
}

4.P层presenter定义的一个类 Fm2Presenter:


public class Fm2Presenter { private HttpUtils http; private Fm2View fv; public Fm2Presenter(Fm2View fv) { this.fv = fv; http=new HttpUtils(); } public void loaddatafromserver(String str){ http.getdata(str, new NetDataCallback() { @Override public void callback(String str) { fv.successfulCallback(str); } @Override public void err(int errcode, String errMsg) { fv.errCallback(errcode,errMsg); } }); } }

5.RecyclerView适配器类(Newsadapter):


public class Newsadapter extends RecyclerView.Adapter {
    private View view;
    private Context mcontext;
    private ArrayList<News.LayoutsBean> mlist=new ArrayList<>();

    public Newsadapter(Context mcontext) {
        this.mcontext = mcontext;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mcontext).inflate(R.layout.fragment2item, null);

        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
       ViewHolder viewholder =(ViewHolder) holder;
        viewholder.tv.setText(""+mlist.get(position).getName());
    }

    //手写的重置数据的方法
    public void setdata(ArrayList<News.LayoutsBean> list){
        if (list!=null&&list.size()>0){
            mlist.addAll(list);
        }

    }
    //手写的获得视图的方法
    public News.LayoutsBean getItem(int position){
        return mlist.get(position);

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

    public class ViewHolder extends RecyclerView.ViewHolder{
   private TextView tv;
        public ViewHolder(View itemView) {
            super(itemView);
            tv=(TextView)itemView.findViewById(R.id.fm2text_view);

        }
    }
}

6.Fragment界面(Fragment2):

public class Fragment2 extends Fragment implements Fm2View{
    private Fm2Presenter fp;
    private RecyclerView recy;
    private Newsadapter mnd;
    private String url="http://h5test.newaircloud.com/api/getLayouts?sid=xkycs&cid=10024&date=";
    private ArrayList<News.LayoutsBean> mlist=new ArrayList<>();
    private Handler hand=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Gson gson=new Gson();
            if (msg.what==1) {
                News news = gson.fromJson(msg.obj.toString(), News.class);
               mlist =(ArrayList<News.LayoutsBean>) news.getLayouts();

                mnd.setdata((ArrayList<News.LayoutsBean>) mlist);
                mnd.notifyDataSetChanged();
            }
        }
    };
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment2, container, false);
       recy=(RecyclerView)view.findViewById(R.id.rcv);

        initdata();
        //加载网络数据
        fp.loaddatafromserver(url);
        return view;
    }

    private void initdata() {
        fp=new Fm2Presenter(this);

        mnd=new Newsadapter(getActivity());
        recy.setLayoutManager(new LinearLayoutManager(getActivity()));
        recy.setAdapter(mnd);

    }

    //实现接口重写的两个方法
    @Override
    public void successfulCallback(String str) {
        Message msg = Message.obtain();
        msg.what=1;
        msg.obj=str;
        hand.sendMessage(msg);

    }

    @Override
    public void errCallback(int code, String msg) {

    }



}
Android--------在Fragment中通过MVP模式用Okhttp进行数据请求