首页 > 解决方案 > 共享首选项不再保存

问题描述

我有一个将 ListView 对象保存到 ArrayList 并在 OnCreate 时加载它们的活动。

我昨晚测试了它,它工作得很好,但是当我今天再次测试它时,它正在加载它已经从昨天保存的内容,但它不再保存新的列表项。

这是我的代码:

public class SubActivity extends AppCompatActivity {

Button addItem;
ImageButton back;
Button saveListBtn;
private ListView listViewer;
ArrayList<ItemObjects> items = new ArrayList<ItemObjects>();
private String key = "arg";

//从给定的 kay: 值对中检索保存的首选项。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fragment1_item_screen);
    Bundle extra = getIntent().getExtras();
    String extraString = extra.getString(key);

//这会从 sharedPreferences 加载项目并且工作正常。

    if(loadList(extraString) != null){
        items = loadList(extraString);
    }

//用正确的信息加载listView。

    final ItemObjectsAdapter adapter = new ItemObjectsAdapter(this, 
 items);
    listViewer = (ListView) findViewById(R.id.itemListView);
    listViewer.setAdapter(adapter);

//按下按钮,一个新对象被添加到itemsArrayList。我现在只是放入一个空白对象。问题来了saveList(items, key)。它似乎无法正常工作,但昨天确实如此,因为每次我加载活动时,都会从 sharedPreferences 加载 4 个列表项,但是,我似乎无法再保存了。

    addItem = (Button) findViewById(R.id.addItemBtn);
    addItem.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            ItemObjects blank = new ItemObjects("", "", "", "");
            items.add(blank);
            saveList(items, key);
            adapter.notifyDataSetChanged();
        }
    });

//这是我保存项目列表的代码。请注意,这昨天有效,我还没有改变任何东西。

private void saveList(ArrayList<ItemObjects> list, String key) {
    SharedPreferences appSharedPrefs = PreferenceManager
            .getDefaultSharedPreferences(this.getApplicationContext());
    SharedPreferences.Editor prefsEditor = appSharedPrefs.edit();
    Gson gson = new Gson();
    String json = gson.toJson(list);
    prefsEditor.putString(key, json);
    prefsEditor.apply();
}

//这只是从 sharedPreferences 加载项目的代码,似乎工作正常。

private ArrayList<ItemObjects> loadList(String key) {
    SharedPreferences prefs = 
PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext());
    Gson gson = new Gson();
    String json = prefs.getString(key, null);
    Type type = new TypeToken<ArrayList<ExerciseObjects>>() {}.getType();
    return gson.fromJson(json, type);
}
}

关于为什么不保存的任何想法?

标签: androidlistviewarraylistsharedpreferences

解决方案


好的,看起来saveList(items, key);应该是saveList(items, extraString);

现在可以了。


推荐阅读