问题描述
- Sharedprefences存储字符数组
-
用Sharedprefences存储字符数组,存储信息为名字,把所有的名字都保存起来,我是新手,希望有例子,谢谢~
解决方案
SharedPreferences sp = getSharedPreferences(PREFERENCES_NAME, Context.MODE_APPEND);
Set setUser = sp.getStringSet("setUser", new HashSet());//引号用的是key,自定义的,相当于一个目录
Editor editor = sp.edit();
setUser.add(userName);//userName 就是你要保存的名字信息
editor.commit();
调用的话跟上面第二句一样。
解决方案二:
/***
- 该类定义了需要保存的登录用户信息
- @author hyylj
- */
public class AccountInfoKeeper {private static final String PREFERENCES_NAME = "com_jingweibo_auther_info";
// extends to auth info
private static final String KEY_AUTH_ID = "auth_id";
private static final String KEY_AUTH_PROFILE = "auth_profile";
private static final String KEY_AUTH_NAME = "auth_name";
private static final String KEY_AUTH_DESCRIPTION = "auth_description";public static void writeAuthInfoToken(Context context,AccountInfoBean token) {
if(null == context || null == token){ return; } SharedPreferences sp = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_APPEND); Editor editor = sp.edit(); if(null != token.getAutherId()){ editor.putString(KEY_AUTH_ID, token.getAutherId()); } if(null != token.getAutherName()){ editor.putString(KEY_AUTH_NAME, token.getAutherName()); } if(null != token.getAutherProfile()){ editor.putString(KEY_AUTH_PROFILE, token.getAutherProfile()); } if(null != token.getAutherDescription()){ editor.putString(KEY_AUTH_DESCRIPTION, token.getAutherDescription()); } editor.commit();
}
public static AccountInfoBean readAuthInfoToken(Context context){
if(null == context){ return null; } SharedPreferences sp = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_APPEND); AccountInfoBean token = new AccountInfoBean(); token.setAutherId(sp.getString(KEY_AUTH_ID, "")); token.setAutherName(sp.getString(KEY_AUTH_NAME, "")); token.setAutherProfile(sp.getString(KEY_AUTH_PROFILE, "")); token.setAutherDescription(sp.getString(KEY_AUTH_DESCRIPTION, "")); return token;
}
public static void clear(Context context){
if(null == context){
return;
}SharedPreferences sp = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_APPEND); Editor ed =sp.edit(); ed.clear(); ed.commit();
}
}
解决方案三:
sharedPreference本身是key-value存储的字典结构,你的需求的话可以考虑使用json或者像我下面的代码这样自定义规则字符串。
为了方便package和unpackage我这里使用了guava。
String[] strNames = {"hyy","kevin","joe","lily","mike"};
//package
Joiner stringJoiner = Joiner.on("|").skipNulls();
String savedStr = stringJoiner.join(strNames);
System.out.println(savedStr);
//save savedStr in sharedpreference
//unpackage
Splitter stringSplitter = Splitter.on("|");
stringSplitter.trimResults();
Iterable unpackageResult = stringSplitter.split(savedStr);
System.out.println(unpackageResult);
解决方案四:
没懂意思,自己太菜鸟了