Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/184.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 在其他活动中编辑共享首选项_Android_Sharedpreferences_Android Context - Fatal编程技术网

Android 在其他活动中编辑共享首选项

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

如何编辑来自其他活动的SharedReference的值。我在上下文部分出错时尝试了这些代码

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();