java在Android中检索SharedReference
我正在构建我的第一个多活动应用程序。我在Activity1中有一些由用户定义的地理坐标,这些坐标保存到SharedPreferences
:
// these strings are used when saving the users' preferred location
private static final String POINT_LATITUDE_KEY = "POINT_LATITUDE_KEY";
private static final String POINT_LONGITUDE_KEY = "POINT_LONGITUDE_KEY";
private static final String TAG = "Activity1";
// actually saves the coordinates to the preferences
private void saveCoordinatesInPreferences(float latitude, float longitude) {
SharedPreferences prefs =
this.getSharedPreferences(getClass().getSimpleName(),
Context.MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = prefs.edit();
prefsEditor.putFloat(POINT_LATITUDE_KEY, latitude);
prefsEditor.putFloat(POINT_LONGITUDE_KEY, longitude);
//Log.i(TAG, "latitude is: " + latitude);
//Log.i(TAG, "longitude is: " + longitude);
prefsEditor.commit();
}
这些共享参考坐标随后需要由Activity2使用。我找不到它们。这是我为检索而编写的一个方法。我的变量latitude
未写入log
private static final String TAG = "Activity2";
protected void getLatLongPref() {
// adapted from http://mrbool.com/安卓-shared-preferences-managing-files-using-internal-external-storage/30508
// accessed April 10, 2015
SharedPreferences pref = getApplicationContext().getSharedPreferences("POINT_LATITUDE_KEY", MODE_PRIVATE);
float latitudeUser = pref.getFloat("POINT_LATITUDE_KEY", 0); // getting users chosen latitude
Log.i(TAG, "latitude is: " + latitudeUser);
}
你认为我做错了什么
# 1 楼答案
您对这两个SharedReference使用了错误的上下文和首选项名称。将第一个更改为:
# 2 楼答案
更改第一个代码段如下:
。。。你的第二个是这样的:
基本上,这两种情况都必须相同。另见this