Android中网络请求数据以及其他数据本地缓存
在很多开发的过程中我们需要联网进行数据请求,有时候一部分数据很长时间都是固定不变的这时候我们就想把这些数据进行本地缓存.之前一看见过很多的框架里面写着网络数据请求进行缓存.很多数据缓存都是对网络请求下来的json数据进行存储,这样如果下次读取数据的时候还要进行解析一遍.今天我们来讲一个非常便捷式的数据对象存储,就是讲网络请求到的json串解析成对象后将该对象直接存储下次直接读取就好了.
1 首先定义一个类
切记这个类一定要
implements Serializable
public class BeanInfo implements Serializable {
private String name; //姓名
private String age; //年龄
public String getName() {
return name;
}
public BeanInfo setName(String name) {
this.name = name;
return this;
}
public String getAge() {
return age;
}
public BeanInfo setAge(String age) {
this.age = age;
return this;
}
}
2 点击读取输入框数据存储到本地按钮的点击事件
private void setLocalData() {
beanInfo = new BeanInfo();
beanInfo.setName(ed_name.getText().toString());
beanInfo.setAge(ed_age.getText().toString());
File path = getApplicationContext().getFilesDir(); //获取存储的路径
File file = new File(path + "/citylist.txt");
try {
FileOutputStream fileOutputStream = new FileOutputStream(file);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(beanInfo);
objectOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
3,点击从本地文件读取数据展示的点击事件
private void getLocalData() {
File path = getApplicationContext().getFilesDir();
File file = new File(path + "/citylist.txt");
if (file.exists()) {
try {
FileInputStream fis = new FileInputStream(path + "/citylist.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
BeanInfo beanInfo = (BeanInfo) ois.readObject();
tv_text.setText("姓名:" + beanInfo.getName() + "\n" + "年龄:" + beanInfo.getAge());
ois.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
4,最终结果验证
:最后为了方便封装一个工具类(废话不多说直接上代码)
public class LocalDataCache {
/**
* 两个小时后为时间超时
*/
public static final long CACHE_DURATION = 1000 * 60 * 60 * 2;//2小时
private static MessageDigest messageDigest;
/**
* 获取缓存在本地的数据
*
* @param fileName 保存的文件名
* @return
*/
public static Object getLocalData(String fileName) {
Log.e("wxf", "开始从本地缓存获取数据");
File path = TangoApplication.getContext().getFilesDir();
Log.e("wxf",path.getAbsolutePath());
File file = new File(path + "/" + Md5(fileName)+".config");
file.getAbsolutePath();
Log.e("wxf", file.getAbsolutePath());
if (file.exists()) {
if (isValid(file)) {
try {
Log.e("wxf", "从本地加载数据");
FileInputStream fin = new FileInputStream(file);
ObjectInputStream oin = new ObjectInputStream(fin);
Object object = oin.readObject();
oin.close();
return object;
} catch (Exception e) {
e.printStackTrace();
LogUtils.e("wxf", "获取数据异常" + e.toString());
}
}
}
return null;
}
/**
* 保存数据
*
* @param object 保存数据的对象
* @param fileName 保存的文件名
*/
public static void save(Object object, String fileName) {
Log.e("wxf", "开始缓存数据到本地");
File path = TangoApplication.getContext().getFilesDir();
File file = new File(path + "/" + Md5(fileName)+".config");
if (file.exists()) {
file.delete();
}
try {
FileOutputStream fos = new FileOutputStream(file, false);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(object);
oos.flush();
oos.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
LogUtils.e("wxf","缓存数据异常"+e.toString());
}
}
/**
* 判断该文件是否有效
*
* @param file
* @return
*/
private static boolean isValid(File file) {
//文件存在了多长时间
long existDuration = System.currentTimeMillis() - file.lastModified();
return existDuration <= CACHE_DURATION;
}
public static String Md5(String message){
StringBuilder sb = new StringBuilder();
try {
//algorithm: 加密的方式
if (messageDigest==null){
messageDigest = MessageDigest.getInstance("MD5");
}
//1.将数据转化成byte数组,并对byte数组进行第一次加密,返回的就是加密过的byte数组
byte[] digest = messageDigest.digest(message.getBytes());
for (int i = 0; i < digest.length; i++) {
//2.将加密过的byte数组的元素和255进行与运算
//-128 - 127
int result = digest[i] & 0xff;
//因为得到int类型的值,可能会比较大,将int类型的值转化成十六进制的字符串
String hexString = Integer.toHexString(result);
if (hexString.length()<2) {
//System.out.print("0");
sb.append("0");
}
//System.out.println(hexString);
sb.append(hexString);
}
return sb.toString();
} catch (NoSuchAlgorithmException e) {
//找不到算法的异常
e.printStackTrace();
}
return null;
}
}
此处MD5文件名加密
如果用直接复制过去就ok.