安卓最新框架rxjava+okhttp+retrofit 上拉下拉滑动删除 从服务器获取数据 最全的案例

安卓最新框架rxjava+okhttp+retrofit 上拉下拉滑动删除 从服务器获取数据 最全的案例

用到的第三方
//图片加载
compile 'com.github.bumptech.glide:glide:3.7.0'
//retrofit
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
//okhttp
compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
compile 'com.squareup.okhttp3:okhttp:3.4.1'
//rxjava
compile 'io.reactivex:rxjava:1.2.5'
compile 'io.reactivex:rxandroid:1.2.1'

先上一波效果图:(注:APP滑动并不卡顿,而是gif图片生成卡顿)


图中的下拉刷新和滑动都是用的第三方库

//滑动库
compile 'com.yanzhenjie:recyclerview-swipe:1.1.4'
//下拉刷新库
compile 'com.scwang.smartrefresh:SmartRefreshLayout:1.0.5-alpha-2'
compile 'com.scwang.smartrefresh:SmartRefreshHeader:1.0.5-alpha-2'

如需了解原理可根据名称去搜索。

package com.lht.demo.util;
/**
 * Created by luck on 2017/12/12.
 */

public class Contanst {
    public static final String SERVER_URL="http://192.168.1.56:8080";//服务器地址
    public static final boolean DEBUG = Boolean.parseBoolean("true");
    public static final String SERVER_POST ="/AndroidServlet/servlet/UserServlet";//服务器接口的位置

}
package com.lht.demo.api.biz;
import com.lht.demo.App;
import com.lht.demo.api.interceptor.HttpInterceptor;
import com.lht.demo.util.Contanst;
import com.lht.demo.utils.StorageUtils;

import java.io.File;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import ren.yale.android.retrofitcachelib.RetrofitCache;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Wenki on
 */

public class APIBase {

    protected static Retrofit retrofit ;

    /**
     * 初始化Retrofit
     */
    public static void initRetrofit() {

        if (retrofit == null) {
            File cacheFile = StorageUtils.getHttpCacheStorage(App.getInstance());
            Cache cache = new Cache(cacheFile, 1024 * 1024 * 10)
                    ;
            OkHttpClient.Builder builder = new OkHttpClient.Builder()
                    .connectTimeout(10, TimeUnit.SECONDS)
                    .writeTimeout(60, TimeUnit.SECONDS)
                    .readTimeout(60, TimeUnit.SECONDS)
//                    .retryOnConnectionFailure(true) //错误重新请求
                    .cache(cache)
                  /* .addInterceptor(new ReceivedCookiesInterceptor(App.getInstance()))//注释的有的是cookie,还有一些配置参数,不影响连接服务器
                    .addInterceptor(new AddCookiesInterceptor(App.getInstance()))*/
//                    .addInterceptor(new ReceivedCookiesInterceptor())//持久化cookie
                    .addInterceptor(new HttpInterceptor())//参数
//                    .addInterceptor(new CacheForceInterceptorNoNet())//无网络缓存
//                    .addNetworkInterceptor(new CacheInterceptorOnNet())//拦截器
//                    .cookieJar( new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(App.getInstance())))
                    ;

            if (Contanst.DEBUG) {
                HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
                loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
                builder.addInterceptor(loggingInterceptor);
            }

            OkHttpClient okHttpClient = builder.build();
            retrofit = new Retrofit.Builder()
                    .baseUrl(Contanst.SERVER_URL)
                    .client(okHttpClient)
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .build();
            RetrofitCache.getInatance().addRetrofit(retrofit);
        }
    }

    public static Retrofit getRetrofit() {
        initRetrofit();
        return retrofit;
    }

}
package com.lht.demo.api;

import com.lht.demo.model.PageInfo;

/**
 * Created by luck on 2018/1/29.
 */

public class CallModel<T> {

    public int code;
    public String msg;
    public T body;
    public PageInfo pageInfo;

}
UserInfo对象表
package com.lht.demo.model;

import java.io.Serializable;

/**
 * Created by luck on 2018/1/29.
 */

public class UserInfo implements Serializable {

    private String id;
    private String name;
    private String msg;
    private String img;
    private boolean isDelete;
    private boolean isUpdate;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public String getImg() {
        return img;
    }

    public void setImg(String img) {
        this.img = img;
    }

    public boolean isDelete() {
        return isDelete;
    }

    public void setDelete(boolean delete) {
        isDelete = delete;
    }

    public boolean isUpdate() {
        return isUpdate;
    }

    public void setUpdate(boolean update) {
        isUpdate = update;
    }
}

调用方法:

 private void socketData(){
        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("");
        progressDialog.show();
        Map<String, Object> map = new HashMap<>();
        map.put("operation", "userArray");
        map.put("currentPage", currentPage);
        GlobalAPI.queryAppList(map, new HttpCallback<CallModel<List<UserInfo>>>() {
            @Override
            public void onSuccess(CallModel<List<UserInfo>> response) {
                userInfos.addAll(response.body);
                pageInfo = response.pageInfo;
                mAdapter.notifyDataSetChanged();
                progressDialog.dismiss();
            }
            @Override
            public void onError(int code, CallModel<List<UserInfo>> body) {
                DadaToast.showToast(body.msg);
                progressDialog.dismiss();
            }
            @Override
            public void onException(int code, Throwable t) {
            }
        });
    }

后台服务器代码
package com.lht.servlet;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.print.attribute.HashAttributeSet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

import com.google.gson.GsonBuilder;
import com.lht.modle.PageInfo;
import com.lht.modle.User;

public class UserServlet extends HttpServlet {

	
	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String operation = request.getParameter("operation");
		response.setHeader("Access-Control-Allow-Origin", "*");
		request.setCharacterEncoding("UTF-8");
		response.setContentType("application/json;charset=utf-8");
		
		Map<String,Object> map = new HashMap<String, Object>();
		if(StringUtils.isNotBlank(operation)){
			if(operation.equals("login")){
				login(request, response);
			}else if(operation.equals("userArray")){
				userArray(request, response);
			}
		}else{
			map.put("msg", "服务器找不到相应的接口");
			map.put("code", -1);
			response.getWriter().write(toJson(map));
		}
		
	}
	
	/**
	 * 登录
	 * @param request
	 * @param response
	 */
	private void login(HttpServletRequest request,HttpServletResponse response){
		Map<String,Object> map = new HashMap<String, Object>();
		try{
			String name = request.getParameter("username");
			
			String password = request.getParameter("password");
			if(name!=null&&name.equals("test") && password!=null && password.equals("admin")){
				map.put("code", 0);
			}else{
				map.put("msg", "用户名或密码错误");
				map.put("code", 1);
			}
			response.getWriter().write(toJson(map));
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	
	private void userArray(HttpServletRequest request,HttpServletResponse response){
		List<User> users = new ArrayList<User>();
		int pageSize = 13;//每页显示的条数
		int pageCount = 3;//总页数
		int totalCount = pageCount * pageSize;//总条数
		int currentPage =  Integer.valueOf(request.getParameter("currentPage"));
		for (int i = 1; i <= pageSize; i++) {
			boolean isDelete = false;
			boolean isUpdate = false;
			if(i %2 == 0){
				isDelete = true;
				isUpdate = false;
			}else if(i %3 == 0){
				isDelete = isUpdate = true;
			}
			String img = "/AndroidServlet/images/img_"+i+".png";
			users.add(new User("100"+i,"张靖"+i,"随风而飘",img,isDelete,isUpdate));
		}
		
		Map<String,Object> map = new HashMap<String, Object>();
		
//		List<User> users = new ArrayList<User>();
//		users.add(new User("1001","张靖","随风而飘","images/img_1",true,true));
//		users.add(new User("1002","陈实","随风而飘","images/img_2",false,true));
//		users.add(new User("1003","张靖","随风而飘","image/img_3",false,false));
//		users.add(new User("1004","autumn1","随风而飘","image/img_4",true,false));
//		users.add(new User("1005","刘静","随风而飘","image/img_5",true,false));
//		users.add(new User("1006","诸葛亮","随风而飘","image/img_6",true,false));
//		users.add(new User("1007","谢诗诗","随风而飘","image/img_7",true,false));
//		users.add(new User("1008"," 李彤","随风而飘","image/img_8",true,true));
		//页数信息
		PageInfo pageInfo = new PageInfo();
		pageInfo.setPageCount(pageCount);
		pageInfo.setCurrentPage(currentPage);
		pageInfo.setTotalCount(totalCount);
		pageInfo.setPageSize(pageSize);
		
		map.put("code", 0);
		map.put("pageInfo", pageInfo);
		map.put("body", users);
		try{
			response.getWriter().write(toJson(map));
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	
	/**
	 * 对象转换JSON
	 */
	public static String toJson(Object target) {
		String result = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss")
				.create().toJson(target); // JSON.toJSONString(target,
											// SerializerFeature.WriteMapNullValue);
		System.out.println(result);
		return result;
	}

	

}

下载链接:https://download.csdn.net/download/qq_25007459/10486609




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值