android中如何在共享首选项中存储和加载布尔数组
朋友可以任何人来检查此代码,以存储共享首选项中的布尔数组,该代码不起作用android中如何在共享首选项中存储和加载布尔数组,android,android-layout,android-activity,android-preferences,Android,Android Layout,Android Activity,Android Preferences,朋友可以任何人来检查此代码,以存储共享首选项中的布尔数组,该代码不起作用 toggleButtonArray=new Boolean[47]; for(int j=0;j<47;j++) { toggleButtonArray[j]=true; } SharedPreferences prefs_tbutton = getApplicationContext().getSharedPreferences("TogglePreferenc
toggleButtonArray=new Boolean[47];
for(int j=0;j<47;j++)
{
toggleButtonArray[j]=true;
}
SharedPreferences prefs_tbutton = getApplicationContext().getSharedPreferences("TogglePreference", 0);
SharedPreferences.Editor editor = prefs_tbutton.edit();
editor.putInt("tbPreferenceArray" +"_size", toggleButtonArray.length);
for(int i=0;i<toggleButtonArray.length;i++)
{
editor.putBoolean("tbPreferenceArray" + "_" + i, toggleButtonArray[i]);
Toast.makeText(getApplicationContext(), "preference saved",Toast.LENGTH_LONG).show();
}
editor.commit();
我建议您将其序列化为jsonUse Context.MODE_PRIVATE,而不是SharedReference中的0,并删除getApplicationContext()。您的
size
和arrayName
有哪些值?@George:size=47,arrayName是toggleButtonArray[]@A。您能举个例子吗
public Boolean[] loadArray(String arrayName, Context mContext) {
SharedPreferences prefs_tbutton = mContext.getSharedPreferences("TogglePreference", 0);
int size = prefs_tbutton.getInt(arrayName + "_size", 0);
Boolean array[] = new Boolean[size];
for(int i=0;i<size;i++)
array[i] = prefs_tbutton.getBoolean(arrayName + "_" + i, false);
Log.e("ARRAY LOADING","SEEKING");
return array;
}
public class TimerService extends Service {
public Boolean[] tbPreferenceArray;
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "Service onStartCommand");
new Thread(new Runnable() {
@Override
public void run() {
tbPreferenceArray=loadArray("tbPreferenceArray",getApplicationContext());