sharedpreferences存储本地数据

来源:互联网 发布:app直播源码下载 编辑:程序博客网 时间:2024/05/16 08:36

首先需要自己分装一个工具类SharedPreferenceUtil

package com.example.administrator.blackstore.mvp.view.friend;import android.content.Context;import android.content.SharedPreferences;import android.content.SharedPreferences.Editor;import java.util.Set;/* * 保存数据的类 */public class SharedPreferenceUtil {   private final static String PREFERENCE_NAME = "login_message";   private static SharedPreferences preferences;   private static Editor editor;   public static final String LOGIN_STR = "loginstr";   public static final String DISTANCE = "updatedistance";   public static final String FIRST_FLASH = "isFirstIn";   public static final String DEVICETOKEN = "deviceToken";   public static void initPreference(Context context) {      preferences = context.getSharedPreferences(PREFERENCE_NAME,            Context.MODE_PRIVATE);      editor = preferences.edit();   }      public static void putInt(String key, int value) {      editor.putInt(key, value).commit();   }   public static int getInt(String key, int defValue) {      return preferences.getInt(key, defValue);   }   public static void putLong(String key, long value) {      editor.putLong(key, value).commit();   }   public static long getLong(String key, long defValue) {      return preferences.getLong(key, defValue);   }   public static void putString(String key, String value) {      try {         editor.putString(key, value).commit();      } catch (Exception e) {         e.printStackTrace();      }   }   public static void putStringSet(String key, Set<String> value){//    return editor.putStringSet(key,value);      editor.putStringSet(key,value).commit();   }   public static Set<String> getStringSet(String key,Set<String> defValue){      return preferences.getStringSet(key,defValue);   }   public static String getString(String key, String defValue) {      try {         return preferences.getString(key, defValue);      } catch (Exception e) {         e.printStackTrace();      }      return preferences.getString(key, defValue);   }   public static void putBoolean(String key, boolean value) {      editor.putBoolean(key, value).commit();   }   public static boolean getBoolean(String key, boolean defValue) {      return preferences.getBoolean(key, defValue);   }   public static boolean remove(String key) {      return editor.remove(key).commit();   }   public static boolean contains(String key) {      return preferences.contains(key);   }}
把实体类粘贴到项目中,然后在程序入口applisction的oncreate的方法里面初始化SharedPerfencers

SharedPreferenceUtil.initPreference(appContext);
//初始化以后,就可以保存了

保存的方法

SharedPreferenceUtil.putInt("user_id",0);SharedPreferenceUtil.putString("shareid_shop",shareid);
还可以保存集合,但是只能保存Set,不能保存list,保存Set的方法同上

在需要的地方取数据的时候

SharedPreferenceUtil.getInt("user_id", 0);//后面的为默认值






阅读全文
0 0
原创粉丝点击