【问题标题】:How to assign initial value to a String in Android如何在Android中为字符串分配初始值
【发布时间】:2016-07-28 11:02:24
【问题描述】:

我不知道我必须在哪里设置这个变量的初始值:

mySharedPreferences.putStringValue("hello", "400");

如果每次打开应用程序都更改它,它不会被重置。

谢谢!!

【问题讨论】:

    标签: android string sharedpreferences


    【解决方案1】:

    最好的方法是在 get 方法上“设置”默认值,而不是在应用程序第一次启动时设置它。

    mySharedPreferences.getString("hello", "400");
    

    通过这种方式,android 会检查是否设置了值。如果没有,它将回退到默认的“400”。

    查看文档: https://developer.android.com/reference/android/content/SharedPreferences.html#getString(java.lang.String, java.lang.String)

    【讨论】:

      【解决方案2】:

      在应用标签中

         <application
          android:name=".YourApplication"
          android:allowBackup="true"
          android:hardwareAccelerated="true"
          android:icon="@drawable/ic_launcher"
          android:label="@string/app_name"
          android:theme="@style/AppTheme">
      

      在应用程序的 onCreate 方法中。这是最好的地方。它将在您的应用创建时执行。

      public class YourApplication extends Application {
      
      public static Boolean sAppOpened = false;
      
      
      @Override
      public void onCreate() {
          super.onCreate();
         //Write your code here
        sAppOpened = true; 
      
      
      ....
      }
      
      ...
      }
      

      【讨论】:

        【解决方案3】:

        像这样在类范围内声明您的 SHARED PREFERENCE 文件名 -
        public static final String SHARED_PREFERENCES = "SHARED_PREF";

        您可以在 OnCreate 方法中使用它。

        SharedPreferences sharedpreferences = getSharedPreferences(SHARED_PREFERENCES, Context.MODE_PRIVATE);
        Editor editor = sharedpreferences.edit();
        editor.putString("key", "value");
        editor.commit();
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-08-22
          • 1970-01-01
          • 2011-11-25
          • 2012-12-03
          • 2014-09-24
          • 1970-01-01
          • 2015-09-16
          相关资源
          最近更新 更多