LocalDataManager本地数据缓存管理类使用(SharedPreferences)
一、作用:
用于缓存数据到本地,数据一般是bean对象。
二、使用:
1.导包
implementation 'com.squareup.retrofit2:converter-gson:2.1.0'
2.数据的存储
//数据的保存
Book book= new Book();
new LocalDataMananger(activity).save(book);
//数据的提取
Book b = new LocalDataMananger(activity).<Book>get(Book.class);
String name = b.getName();
三、注意:
还没想到...
四、代码:
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import com.google.gson.Gson;
public class LocalDataManager {
private Context context;
private SharedPreferences sharedPreferences;
public LocalDataManager(Context context) {
this.context = context;
sharedPreferences = context.getSharedPreferences("loc_data", Context.MODE_PRIVATE);
}
public void save(Object object) {
save(object.getClass().getName(), new Gson().toJson(object));
}
public void save(String key, String v) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, v);
editor.commit();
}
public <T extends Object> T get(Class clz) {
String data = get(clz.getName());
if (data.length() == 0) return null;
return (T) new Gson().fromJson(data, clz);
}
public String get(String key) {
return sharedPreferences.getString(key, "");
}
}