【问题标题】:Editing shared preference in other activity在其他活动中编辑共享偏好
【发布时间】:2017-04-16 13:17:49
【问题描述】:

如何从其他 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);
}

【问题讨论】:

    标签: android sharedpreferences android-context


    【解决方案1】:

    试试这个。 从第一个活动传递上下文。

    调用共享首选项

    SharedPreferences sharedPreferences = context.getSharedPreferences("myPrefs", Context.MODE_PRIVATE);
    

    调用编辑器

    SharedPreferences.Editor editor = context.getSharedPreferences("myPrefs", Context.MODE_PRIVATE).edit();
    

    【讨论】:

      【解决方案2】:

      您可以按如下方式使用 SharedPreferences。由于 sharedpreferences 是持久的,因此您可以在应用程序的任何位置使用相同的实现来访问它。

      SharedPreference sharedPreferences = getApplicationContext().getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);
      sharedPreferences.edit().putString("key", value).apply();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多