编辑其他 activity 中的共享首选项
Editing shared preference in other activity
如何从其他 Activity 编辑 sharedPreference 的值。我通过在上下文部分收到错误来尝试此代码。
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);
}
试试这个。
从第一个 activity.
传递上下文
调用共享首选项
SharedPreferences sharedPreferences = context.getSharedPreferences("myPrefs", Context.MODE_PRIVATE);
调用编辑器
SharedPreferences.Editor editor = context.getSharedPreferences("myPrefs", Context.MODE_PRIVATE).edit();
您可以按如下方式使用 SharedPreferences。由于 sharedpreferences 是持久的,您可以在应用程序的任何地方使用相同的实现来访问它。
SharedPreference sharedPreferences = getApplicationContext().getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);
sharedPreferences.edit().putString("key", value).apply();
如何从其他 Activity 编辑 sharedPreference 的值。我通过在上下文部分收到错误来尝试此代码。
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);
}
试试这个。 从第一个 activity.
传递上下文调用共享首选项
SharedPreferences sharedPreferences = context.getSharedPreferences("myPrefs", Context.MODE_PRIVATE);
调用编辑器
SharedPreferences.Editor editor = context.getSharedPreferences("myPrefs", Context.MODE_PRIVATE).edit();
您可以按如下方式使用 SharedPreferences。由于 sharedpreferences 是持久的,您可以在应用程序的任何地方使用相同的实现来访问它。
SharedPreference sharedPreferences = getApplicationContext().getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);
sharedPreferences.edit().putString("key", value).apply();