android - 共享首选项不再保存
问题描述
我有一个将 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);
//按下按钮,一个新对象被添加到items
ArrayList。我现在只是放入一个空白对象。问题来了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);
}
}
关于为什么不保存的任何想法?
解决方案
好的,看起来saveList(items, key);
应该是saveList(items, extraString);
现在可以了。
推荐阅读
- javascript - 创建了一个 Angular Provider,现在得到了 StaticInjectorError
- php - 我想制作一个接收发布请求并将数据写入文件的 php 页面,以下内容不起作用
- python - 在字典中使用 head 访问数据框
- python-2.7 - UDP 服务器套接字无法解析所有接收到的数据
- webpack - 后端使用虚拟主机的 Webpack 4 Dev Server 配置
- amazon-web-services - AWS JIRA CloudFormation
- sql-server - 在连接表的任一侧启用级联删除
- apache-kafka - Kafka 巡航控制 - NumValidWindows: (0/0) (NaN%), NumValidPartitions: 0/844 (0.000%)
- c - C structure and malloc function
- amazon-web-services - 满足条件时以编程方式向 CloudWatch 发出警报