gpt4 book ai didi

android - 添加值后增加共享首选项键

转载 作者:行者123 更新时间:2023-11-29 17:41:46 26 4
gpt4 key购买 nike

在我的应用中,用户可以为多个人添加姓名和年龄。很可能只有 2 或 3 个左右。我想将它们存储在共享首选项中。我设置了一个计数器来跟踪存储了多少人以及管理哪个键对应哪个值。我接受了 edittext 输入并将其放入一个字符串中,然后像这样将其放入共享首选项中,添加到计数器上,这样我就知道那是第一个人,并且会访问具有“name1”的人。

//this is in the class
public int count = 1;

//this is in the main
SharedPreferences sharedPreferences = getSharedPreferences("registerData", Context.MODE_PRIVATE);
SharedPreferences.Editor myEditor = sharedPreferences.edit();

myEditor.putString("Name"+count, name);
myEditor.putString("Age"+count, age);

除非我记错了,否则应该将字符串“name”放入“Name1”中。

然后我去尝试在另一个 Activity 中使用...访问它

SharedPreferences sharedPreferences = getSharedPreferences("registerData", Context.MODE_PRIVATE);
String name = sharedPreferences.getString("Name"+count,"");
String age = sharedPreferences.getString("Age"+count,"");

然后我会在添加下一个人之前更新计数器,将 key 更改为“Name2”“Age2”等等。

每当我尝试将字符串设置为 TextView 时,它们都显示为空白。这意味着访问 key 的字符串不同。 putString 必须获取“Name1”,因为即使我尝试访问 getString("Name",""),它仍然是空白的。有没有我做错或遗漏的事情。或者有更好的方法吗?谢谢。

最佳答案

        SharedPreferences sharedPreferences = getSharedPreferences("registerData",Context.MODE_PRIVATE);
SharedPreferences.Editor myEditor = sharedPreferences.edit();

myEditor.putString("Name"+count, name);
myEditor.putString("Age"+count, age);
myEditor.apply();//returns nothing,don't forgot to commit changes

你也可以用

      myEditor.commit() //returns true if the save works, false otherwise.

关于android - 添加值后增加共享首选项键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28469085/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com