从类中某处声明的字符串变量中提取字符串资源?

时间:2016-11-25 14:41:38

标签: java android xml

我在一个字符串中的随机变量中获取我的值作为cityname: -

 public static String cityName;
LocationManager locationManager = (LocationManager)
        getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new MyLocationListener();

private class MyLocationListener implements LocationListener {
    @Override
    public void onLocationChanged(Location loc) {
        String longitude = "Longitude: " + loc.getLongitude();
        Log.v(TAG, longitude);
        String latitude = "Latitude: " + loc.getLatitude();
        Log.v(TAG, latitude);
        locationManager.requestLocationUpdates(
                LocationManager.GPS_PROVIDER, 5000, 10, locationListener);
        Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
        List<Address> addresses;
        try {
            addresses = gcd.getFromLocation(loc.getLatitude(),
                    loc.getLongitude(), 1);
            if (addresses.size() > 0) {
                System.out.println(addresses.get(0).getLocality());
                cityName = addresses.get(0).getLocality();
            }
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }

我希望将值作为xml中的字符串资源来到cityname,是否可能以某种方式?

1 个答案:

答案 0 :(得分:1)

我想你想在应用程序的其他地方使用cityname,这就是为什么你要将它存储在字符串res文件中。因此,如果您想在其他地方使用cityname,请尝试将其存储在sharedpreferences或文件中以便以后使用。 Becoz无法在strings.xml文件中动态存储字符串

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); prefs.edit().putString("defaultCityName", cityName).apply();

并使用此

public static String getPreferredLocation(Context context) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); String defaultCityName = prefs.getString("defaultCityName","testCity"); return prefs.getString(context.gettring(R.string.pref_location_key‌​}, defaultCityName); }