Android 如何在SharedReferences中传递值并在新活动中存储在数组中

Android 如何在SharedReferences中传递值并在新活动中存储在数组中,android,Android,我在listview中有一个城市列表。单击列表项后,我想将此值存储在SharedReferences中,并进入新活动。在此活动中,我想在数组中查看此值。我想在每台设备上都设置一个世界时钟。使用SharedReferences的好处是,它们在应用程序的上下文中是全局可访问的,您不需要“传递”它们。此外,您可以使用SharedReferences的putStringSet方法很好地处理这个问题。在onClick方法中,只需按如下方式保存您的城市: Set<String> cityList

我在listview中有一个城市列表。单击列表项后,我想将此值存储在SharedReferences中,并进入新活动。在此活动中,我想在数组中查看此值。我想在每台设备上都设置一个世界时钟。

使用
SharedReferences
的好处是,它们在应用程序的上下文中是全局可访问的,您不需要“传递”它们。此外,您可以使用
SharedReferences
putStringSet
方法很好地处理这个问题。在
onClick
方法中,只需按如下方式保存您的城市:

Set<String> cityList = new HashSet<String>();
cities.add("City1");
cities.add("City2");
// Repeat for all cities in your list...
SharedPreferences sharedPreferences = getSharedPreferences("yourPreferences", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences .edit();
editor.putStringSet("cityList", cityList);
editor.commit();

您尝试了什么?使用intent.putextra()将值从活动传递到另一个活动。在这种情况下,不要使用共享首选项。此答案将对您有所帮助。
SharedPreferences sharedPreferences = getSharedPreferences("yourPreferences", Activity.MODE_PRIVATE);
Set<String> cityList = sharedPreferences.getInt("cityList", new Set<String>());