从另一个活动获取SharedPreferences值

时间:2013-11-19 10:20:21

标签: android sharedpreferences

如何从其他活动中读取SharedPreferences值?

当我选择哪个活动首先开始工作时,我有了setting.calss ...

如何阅读其他活动的偏好设置?

    final SharedPreferences settings = getPreferences(MODE_PRIVATE);
    int choice = settings.getInt("language", -1);

打开Dialog 3活动:

    String[] activities = { "Activity 1", "Activity 2", "Activity 3" };

的OnClick:

            @Override
            public void onClick(DialogInterface dialog, int which) {
                SharedPreferences.Editor editor = settings.edit();
                editor.putInt("language", which);
                editor.commit();
                launchActivity(which);
            }
            }).show();
    } else {
        // start the activity and close this activity
        launchActivity(choice);
    }
}

1 个答案:

答案 0 :(得分:6)

代码背后;

SharedPreferences prefs = this.getSharedPreferences("title",Context.MODE_PRIVATE);
String LanSettining = prefs.getString("language", null);

您还可以使用以下代码:

集:

SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = settings.edit(); 
                        editor.putString("language", language);
                        editor.commit();

读:

SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
String language = settings.getString("language", "");