0

我使用以下方法创建了 SharedPreference obj: 注意:在相同的 pref 文件名下创建多个首选项

public static Sting name = "abx"; //pref file name
          spo = context.getsharedpreference(name , mode_private);
          editor = spo.edit(); //get the editor associated with pref obj

         Map<String, String> test= new HashMap<String, String>();//create a map
    test.put("1", "abc");//fill the values
    test.put("2", "efg");//used map because values are stored in key -value pairs
    test.put("3", "ghj");
       for (String s : test.keySet()) {
        // use the name as the key, and the icon as the value
        editor.putString(s, nameIcons.get(s));//use the key as preference name
    }

    editor.commit();//commit the preferences

我有疑问,如果我错了,请纠正我,创建名为“abz”的 SharedPreference 文件,并在此文件中将首选项值存储为键值对,或者如果编辑器 obj 为每个键创建新的首选项文件,有什么用在创建共享首选项对象时提供首选项文件名?

4

2 回答 2

1

本质上,您可以为给定的应用程序创建多个首选项文件。可以想象这样做有几个原因,最好是如果您有多个帐户。您可以将一组首选项标记为“account1”和另一组“account2”。只需跟踪您所在的帐户,您就可以共享代码而没有大量复杂性。

除非您专门使用此功能,否则我建议您使用context.getApplicationContext().getPackageName()该名称,因为它应该几乎无处不在。

于 2012-11-26T13:39:01.680 回答
0

基本上每个循环内部会发生什么:- 首选项中只会存储一个值,而不是使用代码中为地图中的每个值提供的名称创建 SharedPreferance 文件。

在创建 sharedPreferance 期间使用 Giving File name,以便可以在应用程序的其他部分检索它并可以访问其值。

于 2012-11-26T13:49:50.267 回答