Android 在其他活动中编辑共享首选项
如何编辑来自其他活动的SharedReference的值。我在上下文部分出错时尝试了这些代码Android 在其他活动中编辑共享首选项,android,sharedpreferences,android-context,Android,Sharedpreferences,Android Context,如何编辑来自其他活动的SharedReference的值。我在上下文部分出错时尝试了这些代码 if(stars == 2){ SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences.Editor editor = scorepref.edit(); editor.putInt("keyhelloworl
if(stars == 2){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = scorepref.edit();
editor.putInt("keyhelloworld", stars);
editor.commit();
Intent fromHW = new Intent(HelloWorldGameActivity.this, LessonActivity.class);
startActivity(fromHW);
}
试试这个。
从第一个活动传递上下文
调用共享首选项
SharedPreferences sharedPreferences = context.getSharedPreferences("myPrefs", Context.MODE_PRIVATE);
打电话给编辑
SharedPreferences.Editor editor = context.getSharedPreferences("myPrefs", Context.MODE_PRIVATE).edit();
您可以按如下方式使用SharedReference。由于SharedReferences是持久的,因此可以在应用程序中的任何位置使用相同的实现来访问它
SharedPreference sharedPreferences = getApplicationContext().getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);
sharedPreferences.edit().putString("key", value).apply();