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

时间:2015-02-12 04:03:41

标签: android key sharedpreferences

在我的应用中,用户可以为多人添加姓名和年龄。最有可能的是它只会在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”。

然后我去尝试用另一个活动来访问它......

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

然后我会在添加下一个人之前更新计数器,将密钥更改为“Name2”“Age2”,依此类推。

每当我尝试将字符串设置为textview时,它们都显示为空白。这意味着它不是相同的String来访问密钥。 putString必须获取“Name1”,因为即使我尝试访问getString(“Name”,“”),它仍然是空白的。有什么我做错了或错过了。或者有更好的方法吗?感谢。

3 个答案:

答案 0 :(得分:1)

  

有什么我做错了或错过了。或者有更好的   这样做的方式?

如果SharedPreferences个键名是动态的,那么您应该使用SharedPreferences.getAll()返回所选首选项中可用的所有键:

Map<String, ?> allKeys = sharedPreferences.getAll();

现在遍历allKeys以检查关键名称并获取与关键字相关的Map.Entry的值,如:

for (Map.Entry<String, ?> entry : allKeys.entrySet()) {
    Log.v("TAG","Key Name :" entry.getKey());
    Log.v("TAG","Key Value :" entry.getValue());
} 

答案 1 :(得分:1)

进行更改后,您必须在共享首选项编辑器上调用apply()

...
myEditor.apply();

但是,共享首选项并不意味着存储与内容相关的数据。考虑使用更合适的解决方案,如数据库。

答案 2 :(得分:1)

        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.
相关问题