想必大家都知道安卓的存储,那么安卓有多少种存储方式那?
下面就为大家讲一讲安卓的五种存储方式的一种SharedPreferences,这篇博客我会针对SharedPreferences的封装进行讲解,
对你日后做项目会有一定的帮助;
android有哪五种存储方式那:
应用场景:
保存少量的数据,且这些数据的格式非常简单:字符串型、基本类型的值。比如应用程序的各种配置信息
原理:保存基于XML文件存储的key-value键值对数据,通常用来存储一些简单的配置信息。通过DDMS的File Explorer面板,展开文件浏览树,很明显SharedPreferences数据总是存储在/data/data/<package name>/shared_prefs目录下。
SharedPreferences对象本身只能获取数据而不支持存储和修改,存储修改是通过SharedPreferences.edit()获取的内部接口Editor对象实现。
SharedPreferences本身是一 个接口,程序无法直接创建SharedPreferences实例,只能通过Context提供的getSharedPreferences(String name, int mode)方法来获取SharedPreferences实例。
如何在项目中封装一个SharedPreferences那,我直接写代码了;
创建SharedPreferences工具类
public class SharePrefUtil {
public static final String SP_NAME = "login";
public static void setData(Context context, String key, String value) {
SharedPreferences sharedPreferences = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
// editor.apply();
editor.commit();
}
public static void setData(Context context, String key, int value) {
Log.e("sharedPreferences", key + "|" + value);
SharedPreferences sharedPreferences = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(key, value);
// editor.apply();
editor.commit();
}
public static void setData(Context context, String key, float value) {
SharedPreferences sharedPreferences = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putFloat(key, value);
// editor.apply();
editor.commit();
}
public static void setData(Context context, String key, boolean value) {
SharedPreferences sharedPreferences = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(key, value);
// editor.apply();
editor.commit();
}
public static String getData(Context context, String key) {
return MyApp.getContext().getSharedPreferences(SP_NAME, Context.MODE_PRIVATE).getString(key, "");
}
public static boolean getDataB(Context context, String key) {
return context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE).getBoolean(key, false);
}
public static int getIntData(Context context, String key) {
return context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE).getInt(key, 0);
}
}
下面是如何使用:
创建一个bean类,(例如:Uesr)
使用工具类
private String imgurl;
public String getimgurl(Context context) {
if (StringUtils.isEmpty(imgurl)) {
return MyApp.getContext().getSharedPreferences("login", Context.MODE_PRIVATE).getString("imgurl", "");
}
return imgurl;
}
public void setimgurl(Context context, String imgurl) {
this.imgurl = imgurl;
SharePrefUtil.setData(MyApp.getContext(), "imgurl", imgurl);
}
如何封装和使用讲解完了,在项目中直接COPY代码就可以使用了,很方便,很简洁,希望对你能有所帮助;