public interface IOrderApi {
@GET("empOrderList")
Observable getOrder(@Query("tel") String tel,
@Query("orderType") String orderType,
@Query("page") String page,
@Query("step") String step);
}
package cn.yuebai.yuebaidealer.api.impl;
import cn.yuebai.yuebaidealer.api.IOrderApi;
import cn.yuebai.yuebaidealer.bean.OrderBean;
import cn.yuebai.yuebaidealer.config.BaseApi;
import rx.Observable;
/**
* retrofit2-获取订单api
* User: ZhiyaZhao([email protected])
* Date: 2016-04-24
* parma: 09:00
*
* FIXME
*/
public class OrderApi extends BaseApi {
public static IOrderApi orderApi;
/**
* 获取数据
* @param tel
* @param orderType
* @param page
* @param step
* @return
*/
public static Observable getOrders(String tel, String orderType, String page, String step) {
getOrderApi();
return orderApi.getOrder(tel, orderType, page, step);
}
/**
* 获取创建api
* @return
*/
public static IOrderApi getOrderApi() {
if (orderApi == null) {
orderApi = createApi(IOrderApi.class);
}
return orderApi;
}
}
/**
* 订阅数据
*
* @param observer 观察者-缓存数据bean
* @param tel 电话号码
* @param ordertype 查询类型
* @param page 分页
* @return 在主线程, 订阅
*/
@Override
public Subscription subscribeData(Observer> observer, String tel, String ordertype, String page, File file) {
if (cache == null) {
cache = BehaviorSubject.create();
Observable.create(new Observable.OnSubscribe>() {
@Override
public void call(Subscriber super List> subscriber) {
List items = Database.getInstance().readItems(file);//本地文件读取
if (items == null || file.exists()) {
//本地缓存文件没有读取网络
Data.getInstence().setDataSource(AppConfig.DATA_SOURCE_NETWORK);//网络
loadFromNetwork(tel, ordertype, page, file);
} else {
Data.getInstence().setDataSource(AppConfig.DATA_SOURCE_DISK);//磁盘
subscriber.onNext(items);
}
}
})
.subscribeOn(Schedulers.io())
.subscribe(cache);
} else {
//从内存中读取
Data.getInstence().setDataSource(AppConfig.DATA_SOURCE_MEMORY);
}
return cache.observeOn(AndroidSchedulers.mainThread())
.subscribe(observer);
}
/**
* 从网络获取数据并存入本地文件
*
* @param tel
* @param ordertype
* @param page
*/
@Override
public void loadFromNetwork(String tel, String ordertype, String page, File file) {
OrderApi.getOrders(tel, ordertype, page, AppConfig.ORDER_STEP)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.filter(response -> response != null)
.filter(response -> response.getPageCount() > 0)
.map(OrderResultToItemsMapper.getInstance())
.doOnNext(new Action1>() {
@Override
public void call(List orderListDbBeen) {
Database.getInstance().writeItems(orderListDbBeen, file);
}
})
.subscribe(
new Action1>() {
@Override
public void call(List items) {
// mPassOnListener.onSuccess(items);
cache.onNext(items);
}
},
Throwable::printStackTrace);
}
@Override
public Subscription getOrders(String ordertype, File file) {
if (!HttpUtil.isNetworkAvailable(context)) {
Toast.makeText(context, "网络不通,请开启网络", Toast.LENGTH_SHORT).show();
return null;
} else {
return OrderModel.getInstence().subscribeData(new Observer>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
e.printStackTrace();
orderView.stopRefreshing();
Log.d("OrderPresenter--------", "获取失败...");
}
@Override
public void onNext(List orderList) {
orderView.stopRefreshing();
orderView.setAdapter(orderList);
}
}, orderView.getTel(), ordertype, "1", file);
}
}
activity
package cn.yuebai.yuebaidealer.view.fragment;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.io.File;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
import cn.yuebai.yuebaidealer.R;
import cn.yuebai.yuebaidealer.config.AppConfig;
import cn.yuebai.yuebaidealer.config.SharedPreferencesUtil;
import cn.yuebai.yuebaidealer.db.Data.OrderListDbBean;
import cn.yuebai.yuebaidealer.presenter.impl.OrderPresenter;
import cn.yuebai.yuebaidealer.view.IOrderView;
import cn.yuebai.yuebaidealer.view.adapter.OrderWaitAdapter;
/**
* A fragment representing a list of Items.
*
* interface.
*/
public class OrderWaitFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener, IOrderView {
@Bind(R.id.rv_order)
RecyclerView rvOrder;
@Bind(R.id.rl_order_swipe)
SwipeRefreshLayout rlOrderSwipe;
OrderWaitAdapter mAdapter = new OrderWaitAdapter();
File file = new File(Environment.getExternalStorageDirectory(), AppConfig.DIR_WAITING);
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_order_list, container, false);
ButterKnife.bind(this, view);
LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
//如果可以确定每个item的高度是固定的,设置这个选项可以提高性能
rvOrder.setHasFixedSize(true);
rvOrder.setLayoutManager(mLayoutManager);
rlOrderSwipe.setOnRefreshListener(this);
rvOrder.setAdapter(mAdapter);
load();
return view;
}
@Override
public String getTel() {
return (String) SharedPreferencesUtil.get(AppConfig.AUTO_LOGIN_SHARE, getActivity(), AppConfig.AUTO_LOGIN_USER_TEL_COOKIE, "");
}
@Override
public void stopRefreshing() {
rlOrderSwipe.setRefreshing(false);
}
@Override
public void setAdapter(List orderList) {
mAdapter.setItems(orderList);
}
@Override
public void onDestroyView() {
super.onDestroyView();
ButterKnife.unbind(this);
}
@Override
public void onResume() {
super.onResume();
load();
Log.d("OrderAssignFragment", "onresume.......");
}
/**
* 获取订单数据
*/
void load() {
rlOrderSwipe.setRefreshing(true);
unsubscribe();
OrderPresenter mOrderPresenter = new OrderPresenter(getActivity(), this);
mOrderPresenter.getOrders(AppConfig.ORDER_TYPE_WAITING, file);
}
@Override
public void onRefresh() {
// OrderModel.getInstence().loadFromNetwork(getTel(), AppConfig.ORDER_TYPE_WAITING, "1", file);
}
}
package cn.yuebai.yuebaidealer.view.adapter;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
import cn.yuebai.yuebaidealer.R;
import cn.yuebai.yuebaidealer.db.Data.OrderListDbBean;
public class OrderWaitAdapter extends RecyclerView.Adapter {
// public List datas;
List datas;
public OrderWaitAdapter(List dates) {
this.datas = dates;
}
public OrderWaitAdapter() {
}
//创建新View,被LayoutManager所调用
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_orderlist, parent, false);
return new ViewHolder(view);
}
//将数据与界面进行绑定的操作
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
OrderListDbBean listBean = datas.get(position);
holder.tvOrderWait.setText("等待服务");
Log.d("OrderWaitAdapter", listBean.getTaker());
holder.tvOrderStaff.setText(listBean.getTaker());
holder.tvOrderService.setText(listBean.getProductName());
holder.tvOrderCarinfo.setText(listBean.getCarNo() + "-" +
listBean.getBrandName() + listBean.getModelName() + "-" +
listBean.getColor());
holder.tvOrderAddress.setText(listBean.getAddressName());
holder.tvOrderTiming.setText(listBean.getTimezone());
holder.tvOrderCall.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d("OrderAdapter", "calllllllllllllllllllll");
}
});
}
public void setItems(List orderListDbBeen) {
this.datas = orderListDbBeen;
notifyDataSetChanged();
}
@Override
public int getItemCount() {
return datas == null ? 0 : datas.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
@Bind(R.id.tv_order_wait)
TextView tvOrderWait;
@Bind(R.id.tv_order_staff)
TextView tvOrderStaff;
@Bind(R.id.tv_order_service)
TextView tvOrderService;
@Bind(R.id.tv_order_carinfo)
TextView tvOrderCarinfo;
@Bind(R.id.tv_order_address)
TextView tvOrderAddress;
@Bind(R.id.tv_order_timing)
TextView tvOrderTiming;
@Bind(R.id.btn_order_call)
Button tvOrderCall;
ViewHolder(View view) {
super(view);
ButterKnife.bind(this, view);
}
}
}
package cn.yuebai.yuebaidealer.db;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.List;
import cn.yuebai.yuebaidealer.bean.OrderListDbBean;
/**
* 将订单存入文件
* User: ZhiyaZhao([email protected])
* Date: 2016-04-27
* parma: 10:01
* FIXME
*/
public class FileCache {
public static FileCache INSTANCE;
public File file;
// public String filename;
// File dataFile = new File(Environment.getExternalStorageDirectory(), filename);
Gson gson = new Gson();
public static FileCache getInstance() {
if (INSTANCE == null) {
INSTANCE = new FileCache();
}
return INSTANCE;
}
/**
* 读取文件
*
* @return返回集合实体对象
*/
public List readItems(File file) {
// 硬编码添加一些延迟,区分阅读从内存和磁盘读清楚
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
Reader reader = new FileReader(file);
// 将给定的 JSON 格式字符串转换为带泛型的集合对象
return gson.fromJson(reader, new TypeToken>() {
}.getType());
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
}
/**
* 写入文件
*
* @param items 网络获取的实体
*/
public void writeItems(List items, File file) {
String json = gson.toJson(items);
try {
if (!file.exists()) {
try {
file.createNewFile();
// file.setWritable(Boolean.TRUE);
} catch (IOException e) {
e.printStackTrace();
}
}
Writer writer = new FileWriter(file);
writer.write(json);
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 删除文件
*/
public void delete(File file) {
file.delete();
}
}
package cn.yuebai.yuebaidealer.db.Data;
import android.support.annotation.IntDef;
import android.util.Log;
import java.io.File;
import java.util.List;
import cn.yuebai.yuebaidealer.R;
import cn.yuebai.yuebaidealer.bean.OrderListDbBean;
import cn.yuebai.yuebaidealer.config.AppConfig;
import cn.yuebai.yuebaidealer.config.MyApplication;
import cn.yuebai.yuebaidealer.db.FileCache;
import rx.subjects.BehaviorSubject;
/**
* User: ZhiyaZhao([email protected])
* Date: 2016-04-27
* parma: 10:18
* FIXME
*/
public class Data {
public static Data instence;
private int dataSource;
BehaviorSubject> cache;
@IntDef({AppConfig.DATA_SOURCE_MEMORY, AppConfig.DATA_SOURCE_DISK, AppConfig.DATA_SOURCE_NETWORK})
@interface DataSource {
}
private Data() {
}
public static Data getInstence() {
if (instence == null) {
instence = new Data();
}
return instence;
}
/**
* 设置缓存数据存储方式
*
* @param dataSource 存储方式:内存,磁盘,网络
*/
public void setDataSource(@DataSource int dataSource) {
this.dataSource = dataSource;
}
/**
* 获取数据存储方式
*
* @return
*/
public String getDataSourceText() {
int dataSourceTextRes;
switch (dataSource) {
//内存
case AppConfig.DATA_SOURCE_MEMORY:
dataSourceTextRes = R.string.order_source_memory;
break;
//磁盘
case AppConfig.DATA_SOURCE_DISK:
dataSourceTextRes = R.string.order_source_disk;
break;
//网络
case AppConfig.DATA_SOURCE_NETWORK:
dataSourceTextRes = R.string.order_source_network;
break;
default:
dataSourceTextRes = R.string.order_source_network;
}
Log.d("Data-------------", MyApplication.getInstance().getString(dataSourceTextRes));
return MyApplication.getInstance().getString(dataSourceTextRes);
}
public void clearMemoryCache() {
cache = null;
}
public void clearMemoryAndDiskCache(File file) {
clearMemoryCache();
FileCache.getInstance().delete(file);
}
}
order
内存缓存类OrderResultToItemMapperpackage cn.yuebai.yuebaidealer.db.Data;
import java.util.ArrayList;
import java.util.List;
import cn.yuebai.yuebaidealer.bean.OrderBean;
import cn.yuebai.yuebaidealer.bean.OrderListDbBean;
import rx.functions.Func1;
/**
* 映射器
* User: ZhiyaZhao([email protected])
* Date: 2016-04-27
* parma: 10:40
* FIXME
*/
public class OrderResultToItemsMapper implements Func1> {
private static OrderResultToItemsMapper INSTANCE = new OrderResultToItemsMapper();
public OrderResultToItemsMapper() {
}
public static OrderResultToItemsMapper getInstance() {
return INSTANCE;
}
//OrderBean:外部json
//OrderBean.OrderListBean:订单实体bean
//OrderListDbBean:存入文件bean
@Override
public List call(OrderBean orderBean) {
List orderList = orderBean.getOrderList();//获取orderList
List orderListDb = new ArrayList<>(orderList.size());//将orderList数据复制给缓存文件orderList
if (orderList == null || orderList.size() == 0) {
orderListDb = new ArrayList() {
};
}
for (OrderBean.OrderListBean getOrder : orderList) {
OrderListDbBean item = new OrderListDbBean();
item.timezone = getOrder.getTimezone();
item.taker = getOrder.getTaker();
item.orderNo = getOrder.getOrderNo();
item.carNo = getOrder.getCarNo();
item.brandName = getOrder.getBrandName();
item.modelName = getOrder.getModelName();
item.color = getOrder.getColor();
item.productName = getOrder.getProductName();
item.customerDesc = getOrder.getCustomerDesc();
item.customerTel = getOrder.getCustomerTel();
item.addressName = getOrder.getAddressName();
item.waiting_minute = getOrder.getWaiting_minute();
item.statusCn = getOrder.getStatusCn();
orderListDb.add(item);
}
return orderListDb;
}
}