使用这个:
int x[] = { 1,2,3,4,5 };
String willSave = "";
for(int i=0 ; i<x.length ; i++){
willSave += String.valueOf(x[i]) + ";";
}
saveString(getBaseContext(), "Values", "LastScores", willSave);
// Checking the last cached values
String cachedValues = loadString(getBaseContext(), "Values", "LastScores");
String splitted[] = cachedValues.split(";");
int lastValues[] = new int[splitted.length];
for(int i=0 ; i<splitted.length ; i++){
lastValues[i] = Integer.parseInt(splitted[i]);
}
函数saveString 和loadString:
public void saveString(Context c, String prefName, String key, String value){
SharedPreferences settings = c.getSharedPreferences(prefName, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(key, value);
editor.commit();
}
public String loadString(Context c, String prefName, String key){
SharedPreferences settings = c.getSharedPreferences(prefName, 0);
return new String(settings.getString(key, ""));
}
这段代码这样做:首先将您的int 数组转换为String,因为您无法将数组保存到sharedPrefs。然后将这个缓存的String 再次转换为int 数组。