您可以将它们存储为用句点/逗号分隔的字符串。但是在纬度和经度的情况下,您不应该使用句点,因为它们有句点 (latitude = 27 . 345)
例如
String aLocation = latitude + "," + longitude//store this to sharedpreference
这对于经度和纬度来说不是问题,因为没有逗号(但有句点)会与您的限制器冲突。
在检索位置时,您可以将其拆分并获得相应的经度和纬度。
String[] locationArray = pref.getString(KEY_LOCATION, "").split(",");
String retrievedLat = locationArray[0];
String retrievedLong = locationArray[1];//you may need to use trim() method
您也可以将其转换为 JSON 并保存。但我更喜欢上面的方法,因为它更容易,不会给你的场景带来任何问题。
但如果您需要存储带有特殊字符(如句点)的字符串,则需要将其设为 JSON,因为它可能与您的限制器冲突
所以你可以这样做:
public void addToPref(LatLng location){//I'm supposing you are using LatLang class
String aLocation = location.getLatitude() + "," + location.getLongitude();
//and save to shared preference
}
更新:
如果您想输入多个位置,则需要使用 JSON(首选),但第一种方法更容易。 见下文
1. Get string from preference
2. Concatenate it with the new location
喜欢:
oldLocation,newLocation,newerLocation
附:您可能有每个位置的经度和纬度,因此字符串必须像
{lat1,long1}:{lat2,lat2}:{lat3,long3}
在这种情况下,您需要有多个限制器并做(相应地拆分)。
使用 split(":") 方法将为您提供多个位置。
并使用 split(",") 进一步拆分它,这将为您提供相应的纬度和经度。