繁体   English   中英

Android SharedPreferences重置为默认值。 重新启动应用程序后

[英]Android SharedPreferences is reset to default values. After restarting app

有时,重新启动应用程序后,会在API级别> 13的设备上重置共享首选项。共享首选项是在应用程序的开头(应用程序的第一个活动)设置的。

码:

Public void saveCountry(Context context, String countryCode) {

   SharedPreferences settingsActivity  = context.getSharedPreferences("preferences", Context.MODE_PRIVATE);
   SharedPreferences.Editor editor = settingsActivity.edit();
   editor.putString("key_country", countryCode);
   editor.commit();

   setDefaultChannels(context);
}

public String getCountry(Context mContext) {

   SharedPreferences settingsActivity  = mContext.getSharedPreferences("preferences", Context.MODE_PRIVATE);

   String country = settingsActivity.getString("key_country", null);
   return country;
}

我不知道我在做什么错,为什么会这样。 在收到对detailactivity的推送通知后,我特别注意到了这一点。

您是否在应用程序的开头这样调用保存方法?

    public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main); 

    saveCountry(); 

因为如果你是,你是在启动时每次调用它,那么该国将与任何数据被覆盖countryCode等于在启动时,这可能是什么。 因此,也许您应该有一些仅在首次运行时才调用的代码。

这是我在应用程序中实现它的方式。

    boolean firstRun;
    final SharedPreferences firstRunPref = getSharedPreferences(PREFS_NAME, 0);
    firstRun = firstRunPref.getBoolean("firstRun", true);

    if(firstRun==true){

    saveCountry();

    SharedPreferences.Editor editor3 = firstRunPref.edit();
        editor3.putBoolean("firstRun", false);
        editor3.commit(); 
    } 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM