【问题标题】:How to use SharedPreferences in Android to store, fetch and edit values [closed]如何在 Android 中使用 SharedPreferences 来存储、获取和编辑值 [关闭]
【发布时间】:2011-04-07 03:50:36
【问题描述】:

我想存储一个时间值,需要检索和编辑它。我如何使用SharedPreferences 来做到这一点?

【问题讨论】:

标签: android sharedpreferences


【解决方案1】:

要获取共享首选项,请使用以下方法 在您的活动中:

SharedPreferences prefs = this.getSharedPreferences(
      "com.example.app", Context.MODE_PRIVATE);

阅读偏好:

String dateTimeKey = "com.example.app.datetime";

// use a default value using new Date()
long l = prefs.getLong(dateTimeKey, new Date().getTime()); 

编辑和保存首选项

Date dt = getSomeDate();
prefs.edit().putLong(dateTimeKey, dt.getTime()).apply();

android sdk 的示例目录包含一个检索和存储共享首选项的示例。它位于:

<android-sdk-home>/samples/android-<platformversion>/ApiDemos directory

编辑==>

我注意到,在此处写下commit()apply() 之间的区别也很重要。

commit() 如果值保存成功则返回true,否则返回false。它同步将值保存到 SharedPreferences。

apply() 是在 2.3 中添加的,无论成功还是失败都不返回任何值。它会立即将值保存到 SharedPreferences,但会启动 asynchronous 提交。 更多细节是here

【讨论】:

  • 所以下次用户运行我的应用程序时,存储的值已经存在,我可以获取它......对吗?
  • (对任何阅读以上内容的人)是的,它是任意的。此示例仅使用键“com.example.app.datetime”将当前日期保存为首选项。
  • this.getSharedPreferences 给我以下错误:The method getSharedPreferences(String, int) is undefined for the type MyActivity
  • SharedPreferences.Editor.apply() 于 2010 年 11 月在 Gingerbread 中引入(发布此答案后)。尽可能使用它而不是 commit(),因为 apply() 更有效。
  • Editor.apply() 需要 API 级别 9 或以上。下面使用 Editor.commit()
【解决方案2】:

将值存储在共享首选项中:

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Name","Harneet");
editor.apply();

从共享首选项中检索值:

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String name = preferences.getString("Name", "");
if(!name.equalsIgnoreCase(""))
{
    name = name + "  Sethi";  /* Edit the value here*/
}

【讨论】:

  • 我最喜欢这个答案,因为它使用 getDefaultSharedPreferences。对于大多数用户来说,这将简化事情,因为可以在整个应用程序中访问相同的首选项,您不必担心命名首选项文件。更多信息在这里:stackoverflow.com/a/6310080/1839500
  • 我同意...我在拔掉头发试图弄清楚为什么我无法使用接受的答案中的方法从另一个活动中访问我的共享首选项后发现了这一点。 非常感谢!
  • 如何使用它来保存和加载Map&lt;DateTime, Integer&gt;
【解决方案3】:

编辑来自sharedpreference的数据

 SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
 editor.putString("text", mSaved.getText().toString());
 editor.putInt("selection-start", mSaved.getSelectionStart());
 editor.putInt("selection-end", mSaved.getSelectionEnd());
 editor.apply();

sharedpreference检索数据

SharedPreferences prefs = getPreferences(MODE_PRIVATE); 
String restoredText = prefs.getString("text", null);
if (restoredText != null) 
{
  //mSaved.setText(restoredText, TextView.BufferType.EDITABLE);
  int selectionStart = prefs.getInt("selection-start", -1);
  int selectionEnd = prefs.getInt("selection-end", -1);
  /*if (selectionStart != -1 && selectionEnd != -1)
  {
     mSaved.setSelection(selectionStart, selectionEnd);
  }*/
}

编辑

我从 API Demo 示例中获取了这个 sn-p。它有一个EditText 框。在这个context 中,它不是必需的。我的评论是一样的。

【讨论】:

  • +1,但使用 getPreferences(MODE_PRIVATE);而不是 getPreferences(0);为了可读性。
  • 这里的 mSaved 是什么?我需要保存 2 个字符串值。
  • 我也想知道 mSaved 是什么。 Nvm 我认为它的编辑框
  • -1 在 getInt 中是什么意思??
  • 如果sharedpreferences中不存在key(selection-start),则返回默认值。可以是任何值,仅供参考。
【解决方案4】:

要写:

SharedPreferences preferences = getSharedPreferences("AUTHENTICATION_FILE_NAME", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Authentication_Id",userid.getText().toString());
editor.putString("Authentication_Password",password.getText().toString());
editor.putString("Authentication_Status","true");
editor.apply();

阅读:

SharedPreferences prfs = getSharedPreferences("AUTHENTICATION_FILE_NAME", Context.MODE_PRIVATE);
String Astatus = prfs.getString("Authentication_Status", "");

【讨论】:

  • MODE_WORLD_WRITEABLE 已弃用。
【解决方案5】:

最简单的方法:

保存:

getPreferences(MODE_PRIVATE).edit().putString("Name of variable",value).commit();

检索:

your_variable = getPreferences(MODE_PRIVATE).getString("Name of variable",default value);

【讨论】:

  • 我在活动之间尝试过这个,但没有奏效。 var name 中是否需要包含包结构?
  • 要在活动之间使用此结构,请将 getPreferences(MODE_PRIVATE) 替换为 PreferenceManager.getDefaultSharedPreferences(your ativity)
  • 使用 apply() 代替 commit()
【解决方案6】:

单例共享首选项类。将来可能对其他人有所帮助。

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;

public class SharedPref
{
    private static SharedPreferences mSharedPref;
    public static final String NAME = "NAME";
    public static final String AGE = "AGE";
    public static final String IS_SELECT = "IS_SELECT";

    private SharedPref()
    {

    }

    public static void init(Context context)
    {
        if(mSharedPref == null)
            mSharedPref = context.getSharedPreferences(context.getPackageName(), Activity.MODE_PRIVATE);
    }

    public static String read(String key, String defValue) {
        return mSharedPref.getString(key, defValue);
    }

    public static void write(String key, String value) {
        SharedPreferences.Editor prefsEditor = mSharedPref.edit();
        prefsEditor.putString(key, value);
        prefsEditor.commit();
    }

    public static boolean read(String key, boolean defValue) {
        return mSharedPref.getBoolean(key, defValue);
    }

    public static void write(String key, boolean value) {
        SharedPreferences.Editor prefsEditor = mSharedPref.edit();
        prefsEditor.putBoolean(key, value);
        prefsEditor.commit();
    }

    public static Integer read(String key, int defValue) {
        return mSharedPref.getInt(key, defValue);
    }

    public static void write(String key, Integer value) {
        SharedPreferences.Editor prefsEditor = mSharedPref.edit();
        prefsEditor.putInt(key, value).commit();
    }
}

只需在MainActivity 上拨打SharedPref.init() 一次

SharedPref.init(getApplicationContext());

写入数据

SharedPref.write(SharedPref.NAME, "XXXX");//save string in shared preference.
SharedPref.write(SharedPref.AGE, 25);//save int in shared preference.
SharedPref.write(SharedPref.IS_SELECT, true);//save boolean in shared preference.

读取数据

String name = SharedPref.read(SharedPref.NAME, null);//read string in shared preference.
int age = SharedPref.read(SharedPref.AGE, 0);//read int in shared preference.
boolean isSelect = SharedPref.read(SharedPref.IS_SELECT, false);//read boolean in shared preference.

【讨论】:

  • Hii @Magesh Pandian ,我已经使用了上面的代码。当第一次运行应用程序时,那次我正在读取 userId 的值,但不知道为什么这是读取值“16”,因为它应该是空白的。请重播。提前致谢
【解决方案7】:

在 Preference 中设置值:

// MY_PREFS_NAME - a static String variable like: 
//public static final String MY_PREFS_NAME = "MyPrefsFile";
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
 editor.putString("name", "Elena");
 editor.putInt("idName", 12);
 editor.commit();

从偏好中检索数据:

SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE); 
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
  String name = prefs.getString("name", "No name defined");//"No name defined" is the default value.
  int idName = prefs.getInt("idName", 0); //0 is the default value.
}

更多信息:

Using Shared Preferences

Shared Preferences

【讨论】:

  • 什么是 MyPrefsFile?偏好活动的xml?
【解决方案8】:

存储信息

SharedPreferences preferences = getSharedPreferences(PREFS_NAME,Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("username", username.getText().toString());
editor.putString("password", password.getText().toString());
editor.putString("logged", "logged");
editor.commit();

重置您的偏好

SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.commit();

【讨论】:

    【解决方案9】:

    如果您正在与团队中的其他开发人员一起制作一个大型应用程序,并且打算在没有分散的代码或不同的 SharedPreferences 实例的情况下将所有内容组织好,您可以执行以下操作:

    //SharedPreferences manager class
    public class SharedPrefs {
    
        //SharedPreferences file name
        private static String SHARED_PREFS_FILE_NAME = "my_app_shared_prefs";
    
        //here you can centralize all your shared prefs keys
        public static String KEY_MY_SHARED_BOOLEAN = "my_shared_boolean";
        public static String KEY_MY_SHARED_FOO = "my_shared_foo";
    
        //get the SharedPreferences object instance
        //create SharedPreferences file if not present
    
    
        private static SharedPreferences getPrefs(Context context) {
            return context.getSharedPreferences(SHARED_PREFS_FILE_NAME, Context.MODE_PRIVATE);
        }
    
        //Save Booleans
        public static void savePref(Context context, String key, boolean value) {
            getPrefs(context).edit().putBoolean(key, value).commit();       
        }
    
        //Get Booleans
        public static boolean getBoolean(Context context, String key) {
            return getPrefs(context).getBoolean(key, false);
        }
    
        //Get Booleans if not found return a predefined default value
        public static boolean getBoolean(Context context, String key, boolean defaultValue) {
            return getPrefs(context).getBoolean(key, defaultValue);
        }
    
        //Strings
        public static void save(Context context, String key, String value) {
            getPrefs(context).edit().putString(key, value).commit();
        }
    
        public static String getString(Context context, String key) {
            return getPrefs(context).getString(key, "");
        }
    
        public static String getString(Context context, String key, String defaultValue) {
            return getPrefs(context).getString(key, defaultValue);
        }
    
        //Integers
        public static void save(Context context, String key, int value) {
            getPrefs(context).edit().putInt(key, value).commit();
        }
    
        public static int getInt(Context context, String key) {
            return getPrefs(context).getInt(key, 0);
        }
    
        public static int getInt(Context context, String key, int defaultValue) {
            return getPrefs(context).getInt(key, defaultValue);
        }
    
        //Floats
        public static void save(Context context, String key, float value) {
            getPrefs(context).edit().putFloat(key, value).commit();
        }
    
        public static float getFloat(Context context, String key) {
            return getPrefs(context).getFloat(key, 0);
        }
    
        public static float getFloat(Context context, String key, float defaultValue) {
            return getPrefs(context).getFloat(key, defaultValue);
        }
    
        //Longs
        public static void save(Context context, String key, long value) {
            getPrefs(context).edit().putLong(key, value).commit();
        }
    
        public static long getLong(Context context, String key) {
            return getPrefs(context).getLong(key, 0);
        }
    
        public static long getLong(Context context, String key, long defaultValue) {
            return getPrefs(context).getLong(key, defaultValue);
        }
    
        //StringSets
        public static void save(Context context, String key, Set<String> value) {
            getPrefs(context).edit().putStringSet(key, value).commit();
        }
    
        public static Set<String> getStringSet(Context context, String key) {
            return getPrefs(context).getStringSet(key, null);
        }
    
        public static Set<String> getStringSet(Context context, String key, Set<String> defaultValue) {
            return getPrefs(context).getStringSet(key, defaultValue);
        }
    }
    

    在您的活动中,您可以通过这种方式保存 SharedPreferences

    //saving a boolean into prefs
    SharedPrefs.savePref(this, SharedPrefs.KEY_MY_SHARED_BOOLEAN, booleanVar);
    

    您可以通过这种方式检索您的 SharedPreferences

    //getting a boolean from prefs
    booleanVar = SharedPrefs.getBoolean(this, SharedPrefs.KEY_MY_SHARED_BOOLEAN);
    

    【讨论】:

      【解决方案10】:

      在任何应用程序中,都有可以通过PreferenceManager 实例及其相关方法getDefaultSharedPreferences(Context) 访问的默认首选项。

      使用SharedPreference 实例,可以使用getInt(String key, int defVal) 检索任何首选项的int 值。我们对这种情况感兴趣的偏好是 counter 。

      在我们的例子中,我们可以在我们的例子中使用 edit() 修改 SharedPreference 实例并使用 putInt(String key, int newVal) 我们增加了我们的应用程序的计数,该计数超出了应用程序并相应地显示。

      为了进一步演示,请重新启动应用程序,您会注意到每次重新启动应用程序时计数都会增加。

      PreferencesDemo.java

      代码:

      package org.example.preferences;
      import android.app.Activity;
      import android.content.SharedPreferences;
      import android.os.Bundle;
      import android.preference.PreferenceManager;
      import android.widget.TextView;
      
      public class PreferencesDemo extends Activity {
         /** Called when the activity is first created. */
          @Override
          public void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.main);
      
              // Get the app's shared preferences
              SharedPreferences app_preferences = 
              PreferenceManager.getDefaultSharedPreferences(this);
      
              // Get the value for the run counter
              int counter = app_preferences.getInt("counter", 0);
      
              // Update the TextView
              TextView text = (TextView) findViewById(R.id.text);
              text.setText("This app has been started " + counter + " times.");
      
              // Increment the counter
              SharedPreferences.Editor editor = app_preferences.edit();
              editor.putInt("counter", ++counter);
              editor.commit(); // Very important
          }
      }
      

      ma​​in.xml

      代码:

      <?xml version="1.0" encoding="utf-8"?>
      <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:orientation="vertical"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" >
      
              <TextView
                  android:id="@+id/text"  
                  android:layout_width="fill_parent" 
                  android:layout_height="wrap_content" 
                  android:text="@string/hello" />
      </LinearLayout>
      

      【讨论】:

        【解决方案11】:

        SharedPreferences如何存储登录值的简单解决方案。

        您可以扩展MainActivity 类或其他类,您将在其中存储“您想要保留的东西的价值”。将其放入 writer 和 reader 类:

        public static final String GAME_PREFERENCES_LOGIN = "Login";
        

        这里InputClass 是输入类,OutputClass 是输出类。

        // This is a storage, put this in a class which you can extend or in both classes:
        //(input and output)
        public static final String GAME_PREFERENCES_LOGIN = "Login";
        
        // String from the text input (can be from anywhere)
        String login = inputLogin.getText().toString();
        
        // then to add a value in InputCalss "SAVE",
        SharedPreferences example = getSharedPreferences(GAME_PREFERENCES_LOGIN, 0);
        Editor editor = example.edit();
        editor.putString("value", login);
        editor.commit();
        

        现在你可以在其他地方使用它,比如其他类。以下是OutputClass

        SharedPreferences example = getSharedPreferences(GAME_PREFERENCES_LOGIN, 0);
        String userString = example.getString("value", "defValue");
        
        // the following will print it out in console
        Logger.getLogger("Name of a OutputClass".class.getName()).log(Level.INFO, userString);
        

        【讨论】:

          【解决方案12】:

          存储在 SharedPreferences 中

          SharedPreferences preferences = getSharedPreferences("temp", getApplicationContext().MODE_PRIVATE);
          Editor editor = preferences.edit();
          editor.putString("name", name);
          editor.commit();
          

          在 SharedPreferences 中获取

          SharedPreferences preferences=getSharedPreferences("temp", getApplicationContext().MODE_PRIVATE);
          String name=preferences.getString("name",null);
          

          注意:“temp”是共享首选项名称,“name”是输入值。如果值没有退出,则返回 null

          【讨论】:

          • 非常好用且易于使用。但这里是 Context.MODE_PRIVATE 而不是 getApplicationContext().MODE_PRIVATE
          【解决方案13】:

          编辑

          SharedPreferences pref = getSharedPreferences("YourPref", MODE_PRIVATE);
          SharedPreferences.Editor editor = pref.edit();
          editor.putString("yourValue", value);
          editor.commit();
          

          阅读

          SharedPreferences pref = getSharedPreferences("YourPref", MODE_PRIVATE);
          value= pref.getString("yourValue", "");
          

          【讨论】:

            【解决方案14】:

            将值存储在共享首选项中:

            SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
            SharedPreferences.Editor editor = sp.edit();
            editor.putString("Name","Jayesh");
            editor.commit();
            

            从共享首选项中检索值:

            SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
            String name = sp.getString("Name", ""); // Second parameter is the default value.
            

            【讨论】:

              【解决方案15】:
              editor.putString("text", mSaved.getText().toString());
              

              这里,mSaved 可以是任何TextViewEditText,我们可以从中提取字符串。您可以简单地指定一个字符串。这里的文本将是保存从mSavedTextViewEditText)获得的值的键。

              SharedPreferences prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
              

              此外,无需使用包名称(即“com.example.app”)保存首选项文件。您可以提及自己喜欢的名字。希望这会有所帮助!

              【讨论】:

                【解决方案16】:

                SharedPreferences 的基本思想是将内容存储在 XML 文件中。

                1. 声明你的xml文件路径。(如果你没有这个文件,Android会创建它。如果你有这个文件,Android会访问它。)

                  SharedPreferences prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
                  
                2. 将值写入共享首选项

                  prefs.edit().putLong("preference_file_key", 1010101).apply();
                  

                  preference_file_key 是共享首选项文件的名称。 1010101 是您需要存储的值。

                  apply() 最后是保存更改。如果您收到来自apply() 的错误,请将其更改为commit()。所以这个替代句子是

                  prefs.edit().putLong("preference_file_key", 1010101).commit();
                  
                3. 从共享首选项中读取

                  SharedPreferences sp = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
                  long lsp = sp.getLong("preference_file_key", -1);
                  

                  如果preference_file_key 没有值,lsp 将是-1。如果 'preference_file_key' 有值,它将返回 this 的值。

                整个编写代码是

                    SharedPreferences prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);    // Declare xml file
                    prefs.edit().putLong("preference_file_key", 1010101).apply();    // Write the value to key.
                

                阅读的代码是

                    SharedPreferences sf = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);    // Declare xml file
                    long lsp = sp.getLong("preference_file_key", -1);    // Read the key and store in lsp
                

                【讨论】:

                • Editor.apply() 需要 API 级别 9 或以上。下面使用 Editor.commit()
                【解决方案17】:

                您可以使用此方法节省价值:

                public void savePreferencesForReasonCode(Context context,
                    String key, String value) {
                    SharedPreferences sharedPreferences = PreferenceManager
                    .getDefaultSharedPreferences(context);
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putString(key, value);
                    editor.commit();
                    }
                

                使用这种方法,您可以从 SharedPreferences 中获取价值:

                public String getPreferences(Context context, String prefKey) {
                  SharedPreferences sharedPreferences = PreferenceManager
                 .getDefaultSharedPreferences(context);
                 return sharedPreferences.getString(prefKey, "");
                }
                

                这里prefKey 是您用来保存特定值的键。谢谢。

                【讨论】:

                • 布尔值呢?
                • 使用这一行保存:editor.putString(key, value);使用这一行: Boolean yourLocked = prefs.getBoolean("locked", false);
                【解决方案18】:

                保存

                PreferenceManager.getDefaultSharedPreferences(this).edit().putString("VarName","your value").apply();
                

                检索:

                String name = PreferenceManager.getDefaultSharedPreferences(this).getString("VarName","defaultValue");
                

                默认值是:如果此首选项不存在,则返回的值。

                您可以使用 getActivity()getApplicationContext( ) 在 一些情况

                【讨论】:

                【解决方案19】:

                人们推荐使用 SharedPreferences 的方法有很多种。我做了一个demo project here。示例中的关键点是使用 ApplicationContext 和单个 sharedpreferences 对象。这演示了如何使用具有以下功能的 SharedPreferences:-

                • 使用 singelton 类访问/更新 SharedPreferences
                • 无需始终为读/写 SharedPreferences 传递上下文
                • 它使用 apply() 而不是 commit()
                • apply() 是异步保存,不返回任何内容,它首先更新内存中的值,然后将更改写入磁盘 异步。
                • commit() 是同步保存,它根据结果返回真/假。更改会同步写入磁盘
                • 适用于 android 2.3+ 版本

                使用示例如下:-

                MyAppPreference.getInstance().setSampleStringKey("some_value");
                String value= MyAppPreference.getInstance().getSampleStringKey();
                

                Get source code here & 详细的 API 可以在 developer.android.com 上找到here

                【讨论】:

                【解决方案20】:

                最佳实践

                创建以 PreferenceManager 命名的 Interface

                // Interface to save values in shared preferences and also for retrieve values from shared preferences
                public interface PreferenceManager {
                
                    SharedPreferences getPreferences();
                    Editor editPreferences();
                
                    void setString(String key, String value);
                    String getString(String key);
                
                    void setBoolean(String key, boolean value);
                    boolean getBoolean(String key);
                
                    void setInteger(String key, int value);
                    int getInteger(String key);
                
                    void setFloat(String key, float value);
                    float getFloat(String key);
                
                }
                

                如何与Activity / Fragment一起使用:

                public class HomeActivity extends AppCompatActivity implements PreferenceManager{
                
                    @Override
                    protected void onCreate(Bundle savedInstanceState) {
                        super.onCreate(savedInstanceState);
                        setContentView(R.layout_activity_home);
                    }
                
                    @Override
                    public SharedPreferences getPreferences(){
                        return getSharedPreferences("SP_TITLE", Context.MODE_PRIVATE);
                    }
                
                    @Override
                    public SharedPreferences.Editor editPreferences(){
                        return getPreferences().edit();
                    }
                
                    @Override
                    public void setString(String key, String value) {
                        editPreferences().putString(key, value).commit();
                    }
                
                    @Override
                    public String getString(String key) {
                        return getPreferences().getString(key, "");
                    }
                
                    @Override
                    public void setBoolean(String key, boolean value) {
                        editPreferences().putBoolean(key, value).commit();
                    }
                
                    @Override
                    public boolean getBoolean(String key) {
                        return  getPreferences().getBoolean(key, false);
                    }
                
                    @Override
                    public void setInteger(String key, int value) {
                        editPreferences().putInt(key, value).commit();
                    }
                
                    @Override
                    public int getInteger(String key) {
                        return getPreferences().getInt(key, 0);
                    }
                
                    @Override
                    public void setFloat(String key, float value) {
                        editPreferences().putFloat(key, value).commit();
                    }
                
                    @Override
                    public float getFloat(String key) {
                        return getPreferences().getFloat(key, 0);
                    }
                }
                

                注意:将 SharedPreference 的键替换为 SP_TITLE

                示例:

                shareperence中存储字符串

                setString("my_key", "my_value");
                

                shareperence获取字符串

                String strValue = getString("my_key");
                

                希望这会对你有所帮助。

                【讨论】:

                • 我是使用相同的共享首选项对象来存储所有内容,还是为每个不同的数据创建新的共享首选项对象?
                • @Ruchir Baronia,不需要创建不同的对象,顺便说一下,您不需要初始化共享首选项的对象。您可以通过以上方式保存。让我知道我是否有任何需要。
                • 好的,谢谢。你能帮我解决这个问题吗? stackoverflow.com/questions/35235759/…
                • @Ruchir Baronia,你可以取消线程。希望这对您有所帮助。
                • 哦,很抱歉,我问错了问题。我是想问这个,关于共享偏好:) stackoverflow.com/questions/35244256/issue-with-if-statement/…
                【解决方案21】:

                我为 sharedpreferences 编写了一个辅助类:

                import android.content.Context;
                import android.content.SharedPreferences;
                
                /**
                 * Created by mete_ on 23.12.2016.
                 */
                public class HelperSharedPref {
                
                Context mContext;
                
                public HelperSharedPref(Context mContext) {
                    this.mContext = mContext;
                }
                
                /**
                 *
                 * @param key Constant RC
                 * @param value Only String, Integer, Long, Float, Boolean types
                 */
                public void saveToSharedPref(String key, Object value) throws Exception {
                    SharedPreferences.Editor editor = mContext.getSharedPreferences(key, Context.MODE_PRIVATE).edit();
                    if (value instanceof String) {
                        editor.putString(key, (String) value);
                    } else if (value instanceof Integer) {
                        editor.putInt(key, (Integer) value);
                    } else if (value instanceof Long) {
                        editor.putLong(key, (Long) value);
                    } else if (value instanceof Float) {
                        editor.putFloat(key, (Float) value);
                    } else if (value instanceof Boolean) {
                        editor.putBoolean(key, (Boolean) value);
                    } else {
                        throw new Exception("Unacceptable object type");
                    }
                
                    editor.commit();
                }
                
                /**
                 * Return String
                 * @param key
                 * @return null default is null
                 */
                public String loadStringFromSharedPref(String key) throws Exception {
                    SharedPreferences prefs = mContext.getSharedPreferences(key, Context.MODE_PRIVATE);
                    String restoredText = prefs.getString(key, null);
                
                    return restoredText;
                }
                
                /**
                 * Return int
                 * @param key
                 * @return null default is -1
                 */
                public Integer loadIntegerFromSharedPref(String key) throws Exception {
                    SharedPreferences prefs = mContext.getSharedPreferences(key, Context.MODE_PRIVATE);
                    Integer restoredText = prefs.getInt(key, -1);
                
                    return restoredText;
                }
                
                /**
                 * Return float
                 * @param key
                 * @return null default is -1
                 */
                public Float loadFloatFromSharedPref(String key) throws Exception {
                    SharedPreferences prefs = mContext.getSharedPreferences(key, Context.MODE_PRIVATE);
                    Float restoredText = prefs.getFloat(key, -1);
                
                    return restoredText;
                }
                
                /**
                 * Return long
                 * @param key
                 * @return null default is -1
                 */
                public Long loadLongFromSharedPref(String key) throws Exception {
                    SharedPreferences prefs = mContext.getSharedPreferences(key, Context.MODE_PRIVATE);
                    Long restoredText = prefs.getLong(key, -1);
                
                    return restoredText;
                }
                
                /**
                 * Return boolean
                 * @param key
                 * @return null default is false
                 */
                public Boolean loadBooleanFromSharedPref(String key) throws Exception {
                    SharedPreferences prefs = mContext.getSharedPreferences(key, Context.MODE_PRIVATE);
                    Boolean restoredText = prefs.getBoolean(key, false);
                
                    return restoredText;
                }
                
                }
                

                【讨论】:

                  【解决方案22】:

                  将值存储在共享首选项中:

                  SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
                  SharedPreferences.Editor editor = sp.edit();
                  editor.putString("Name","Jayesh");
                  editor.commit();
                  

                  从共享首选项中检索值:

                  SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
                  String name = sp.getString("Name", "");
                  

                  【讨论】:

                    【解决方案23】:

                    使用这个例子简单明了并检查

                    <?xml version="1.0" encoding="utf-8"?>
                    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
                       package="com.example.sairamkrishna.myapplication" >
                    
                       <application
                          android:allowBackup="true"
                          android:icon="@mipmap/ic_launcher"
                          android:label="@string/app_name"
                          android:theme="@style/AppTheme" >
                    
                          <activity
                             android:name=".MainActivity"
                             android:label="@string/app_name" >
                    
                             <intent-filter>
                                <action android:name="android.intent.action.MAIN" />
                                <category android:name="android.intent.category.LAUNCHER" />
                             </intent-filter>
                    
                          </activity>
                    
                       </application>
                    </manifest>
                    
                    public class MainActivity extends AppCompatActivity {
                       EditText ed1,ed2,ed3;
                       Button b1;
                    
                       public static final String MyPREFERENCES = "MyPrefs" ;
                       public static final String Name = "nameKey";
                       public static final String Phone = "phoneKey";
                       public static final String Email = "emailKey";
                    
                       SharedPreferences sharedpreferences;
                    
                       @Override
                       protected void onCreate(Bundle savedInstanceState) {
                          super.onCreate(savedInstanceState);
                          setContentView(R.layout.activity_main);
                    
                          ed1=(EditText)findViewById(R.id.editText);
                          ed2=(EditText)findViewById(R.id.editText2);
                          ed3=(EditText)findViewById(R.id.editText3);
                    
                          b1=(Button)findViewById(R.id.button);
                          sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
                    
                          b1.setOnClickListener(new View.OnClickListener() {
                             @Override
                             public void onClick(View v) {
                                String n  = ed1.getText().toString();
                                String ph  = ed2.getText().toString();
                                String e  = ed3.getText().toString();
                    
                                SharedPreferences.Editor editor = sharedpreferences.edit();
                    
                                editor.putString(Name, n);
                                editor.putString(Phone, ph);
                                editor.putString(Email, e);
                                editor.commit();
                                Toast.makeText(MainActivity.this,"Thanks",Toast.LENGTH_LONG).show();
                             }
                          });
                       }
                    
                    }
                    

                    【讨论】:

                      【解决方案24】:

                      使用此simple library,您可以通过以下方式调用 SharedPreferences..

                      TinyDB tinydb = new TinyDB(context);
                      
                      tinydb.putInt("clickCount", 2);
                      
                      tinydb.putString("userName", "john");
                      tinydb.putBoolean("isUserMale", true); 
                      
                      tinydb.putList("MyUsers", mUsersArray);
                      tinydb.putImagePNG("DropBox/WorkImages", "MeAtlunch.png", lunchBitmap);
                      
                      //These plus the corresponding get methods are all Included
                      

                      【讨论】:

                        【解决方案25】:

                        我想在这里补充一点,当使用 SharedPreferences 时,这个问题的大多数 sn-ps 都会有类似 MODE_PRIVATE 的内容。好吧,MODE_PRIVATE 意味着您写入此共享首选项的任何内容都只能由您的应用程序读取。

                        无论您传递给 getSharedPreferences() 方法的任何键,android 都会创建一个具有该名称的文件并将首选项数据存储到其中。 另请记住,当您打算为您的应用程序拥有多个首选项文件时,应该使用 getSharedPreferences()。如果您打算使用单个首选项文件并将所有键值对存储到其中,请使用 getSharedPreference() 方法。奇怪的是为什么每个人(包括我自己)都只是使用 getSharedPreferences() 风格,甚至不了解上述两者之间的区别。

                        以下视频教程应该会有所帮助 https://www.youtube.com/watch?v=2PcAQ1NBy98

                        【讨论】:

                          【解决方案26】:

                          简单无忧 :: “Android-SharedPreferences-Helper”库

                          迟到总比没有好:我创建了the "Android-SharedPreferences-Helper" library 来帮助降低使用SharedPreferences 的复杂性和工作量。它还提供了一些扩展功能。它提供的一些东西如下:

                          • 单线初始化和设置
                          • 轻松选择是使用默认首选项还是自定义首选项文件
                          • 每种数据类型的预定义(数据类型默认值)和可自定义(您可以选择)默认值
                          • 只需一个额外的参数即可设置不同的默认值以供一次性使用
                          • 您可以像注册默认类一样注册和取消注册 OnSharedPreferenceChangeListener
                          dependencies {
                              ...
                              ...
                              compile(group: 'com.viralypatel.sharedpreferenceshelper', name: 'library', version: '1.1.0', ext: 'aar')
                          }
                          

                          SharedPreferencesHelper 对象的声明:(推荐在课堂上 等级)

                          SharedPreferencesHelper sph; 
                          

                          SharedPreferencesHelper 对象的实例化:(推荐在 onCreate() 方法)

                          // use one of the following ways to instantiate
                          sph = new SharedPreferencesHelper(this); //this will use default shared preferences
                          sph = new SharedPreferencesHelper(this, "myappprefs"); // this will create a named shared preference file
                          sph = new SharedPreferencesHelper(this, "myappprefs", 0); // this will allow you to specify a mode
                          

                          将价值观融入共同偏好中

                          相当简单!与默认方式不同(使用 SharedPreferences 类时),您无需每次都调用 .edit().commit()

                          sph.putBoolean("boolKey", true);
                          sph.putInt("intKey", 123);
                          sph.putString("stringKey", "string value");
                          sph.putLong("longKey", 456876451);
                          sph.putFloat("floatKey", 1.51f);
                          
                          // putStringSet is supported only for android versions above HONEYCOMB
                          Set name = new HashSet();
                          name.add("Viral");
                          name.add("Patel");
                          sph.putStringSet("name", name);
                          

                          就是这样!您的值存储在共享首选项中。

                          从共享偏好中获取价值

                          同样,只需使用键名调用一个简单的方法。

                          sph.getBoolean("boolKey");
                          sph.getInt("intKey");
                          sph.getString("stringKey");
                          sph.getLong("longKey");
                          sph.getFloat("floatKey");
                          
                          // getStringSet is supported only for android versions above HONEYCOMB
                          sph.getStringSet("name");
                          

                          它还有很多其他的扩展功能

                          GitHub Repository Page上查看扩展功能、使用和安装说明等详细信息。

                          【讨论】:

                          • 我是使用相同的共享首选项对象来存储所有内容,还是为每个不同的数据创建新的共享首选项对象?
                          • 你应该尽可能使用相同的。这就是制作这个库的全部意义所在。
                          • 嘿,我有一个关于共享首选项的问题。你介意回答吗? stackoverflow.com/questions/35713822/…
                          【解决方案27】:

                          我创建了一个 Helper 类来简化我的生活。这是一个通用类,有很多应用程序中常用的方法,如共享首选项、电子邮件有效性、日期时间格式。在你的代码中复制这个类,并在你需要的地方访问它的方法。

                           import android.app.AlertDialog;
                           import android.app.ProgressDialog;
                           import android.content.Context;
                           import android.content.DialogInterface;
                           import android.content.SharedPreferences;
                           import android.support.v4.app.FragmentActivity;
                           import android.view.inputmethod.InputMethodManager;
                           import android.widget.EditText;
                           import android.widget.Toast;
                          
                           import java.text.ParseException;
                           import java.text.SimpleDateFormat;
                           import java.util.Date;
                           import java.util.Random;
                           import java.util.regex.Matcher;
                           import java.util.regex.Pattern;
                           import java.util.regex.PatternSyntaxException;
                          
                          /**
                          * Created by Zohaib Hassan on 3/4/2016.
                          */
                           public class Helper {
                          
                          private static ProgressDialog pd;
                          
                          public static void saveData(String key, String value, Context context) {
                              SharedPreferences sp = context.getApplicationContext()
                                      .getSharedPreferences("appData", 0);
                              SharedPreferences.Editor editor;
                              editor = sp.edit();
                              editor.putString(key, value);
                              editor.commit();
                          }
                          
                          public static void deleteData(String key, Context context){
                              SharedPreferences sp = context.getApplicationContext()
                                      .getSharedPreferences("appData", 0);
                              SharedPreferences.Editor editor;
                              editor = sp.edit();
                              editor.remove(key);
                              editor.commit();
                          
                          }
                          
                          public static String getSaveData(String key, Context context) {
                              SharedPreferences sp = context.getApplicationContext()
                                      .getSharedPreferences("appData", 0);
                              String data = sp.getString(key, "");
                              return data;
                          
                          }
                          
                          
                          
                          
                          public static long dateToUnix(String dt, String format) {
                              SimpleDateFormat formatter;
                              Date date = null;
                              long unixtime;
                              formatter = new SimpleDateFormat(format);
                              try {
                                  date = formatter.parse(dt);
                              } catch (Exception ex) {
                          
                                  ex.printStackTrace();
                              }
                              unixtime = date.getTime();
                              return unixtime;
                          
                          }
                          
                          public static String getData(long unixTime, String formate) {
                          
                              long unixSeconds = unixTime;
                              Date date = new Date(unixSeconds);
                              SimpleDateFormat sdf = new SimpleDateFormat(formate);
                              String formattedDate = sdf.format(date);
                              return formattedDate;
                          }
                          
                          public static String getFormattedDate(String date, String currentFormat,
                                                                String desiredFormat) {
                              return getData(dateToUnix(date, currentFormat), desiredFormat);
                          }
                          
                          
                          
                          
                          public static double distance(double lat1, double lon1, double lat2,
                                                        double lon2, char unit) {
                              double theta = lon1 - lon2;
                              double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2))
                                      + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2))
                                      * Math.cos(deg2rad(theta));
                              dist = Math.acos(dist);
                              dist = rad2deg(dist);
                              dist = dist * 60 * 1.1515;
                              if (unit == 'K') {
                                  dist = dist * 1.609344;
                              } else if (unit == 'N') {
                                  dist = dist * 0.8684;
                              }
                              return (dist);
                          }
                          
                          /* ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: */
                          /* :: This function converts decimal degrees to radians : */
                          /* ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: */
                          private static double deg2rad(double deg) {
                              return (deg * Math.PI / 180.0);
                          }
                          
                          /* ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: */
                          /* :: This function converts radians to decimal degrees : */
                          /* ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: */
                          private static double rad2deg(double rad) {
                              return (rad * 180.0 / Math.PI);
                          }
                          
                          public static int getRendNumber() {
                              Random r = new Random();
                              return r.nextInt(360);
                          }
                          
                          public static void hideKeyboard(Context context, EditText editText) {
                              InputMethodManager imm = (InputMethodManager) context
                                      .getSystemService(Context.INPUT_METHOD_SERVICE);
                              imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
                          }
                          
                          public static void showLoder(Context context, String message) {
                              pd = new ProgressDialog(context);
                          
                              pd.setCancelable(false);
                              pd.setMessage(message);
                              pd.show();
                          }
                          
                          public static void showLoderImage(Context context, String message) {
                              pd = new ProgressDialog(context);
                              pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                              pd.setCancelable(false);
                              pd.setMessage(message);
                              pd.show();
                          }
                          
                          public static void dismissLoder() {
                              pd.dismiss();
                          }
                          
                          public static void toast(Context context, String text) {
                          
                              Toast.makeText(context, text, Toast.LENGTH_LONG).show();
                          }
                          /*
                               public static Boolean connection(Context context) {
                              ConnectionDetector connection = new ConnectionDetector(context);
                              if (!connection.isConnectingToInternet()) {
                          
                                  Helper.showAlert(context, "No Internet access...!");
                                  //Helper.toast(context, "No internet access..!");
                                  return false;
                              } else
                                  return true;
                          }*/
                          
                          public static void removeMapFrgment(FragmentActivity fa, int id) {
                          
                              android.support.v4.app.Fragment fragment;
                              android.support.v4.app.FragmentManager fm;
                              android.support.v4.app.FragmentTransaction ft;
                              fm = fa.getSupportFragmentManager();
                              fragment = fm.findFragmentById(id);
                              ft = fa.getSupportFragmentManager().beginTransaction();
                              ft.remove(fragment);
                              ft.commit();
                          
                          }
                          
                          public static AlertDialog showDialog(Context context, String message) {
                              AlertDialog.Builder builder = new AlertDialog.Builder(context);
                              builder.setMessage(message);
                          
                              builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                          
                                  @Override
                                  public void onClick(DialogInterface dialog, int id) {
                                      // TODO Auto-generated method stub
                          
                                  }
                              });
                          
                              return builder.create();
                          }
                          
                          public static void showAlert(Context context, String message) {
                              AlertDialog.Builder builder = new AlertDialog.Builder(context);
                              builder.setTitle("Alert");
                              builder.setMessage(message)
                                      .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                                          public void onClick(DialogInterface dialog, int id) {
                                              dialog.dismiss();
                                          }
                                      }).show();
                          }
                          
                          public static boolean isURL(String url) {
                              if (url == null)
                                  return false;
                          
                              boolean foundMatch = false;
                              try {
                                  Pattern regex = Pattern
                                          .compile(
                                                  "\\b(?:(https?|ftp|file)://|www\\.)?[-A-Z0-9+&#/%?=~_|$!:,.;]*[A-Z0-9+&@#/%=~_|$]\\.[-A-Z0-9+&@#/%?=~_|$!:,.;]*[A-Z0-9+&@#/%=~_|$]",
                                                  Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
                                  Matcher regexMatcher = regex.matcher(url);
                                  foundMatch = regexMatcher.matches();
                                  return foundMatch;
                              } catch (PatternSyntaxException ex) {
                                  // Syntax error in the regular expression
                                  return false;
                              }
                          }
                          
                          public static boolean atLeastOneChr(String string) {
                              if (string == null)
                                  return false;
                          
                              boolean foundMatch = false;
                              try {
                                  Pattern regex = Pattern.compile("[a-zA-Z0-9]",
                                          Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
                                  Matcher regexMatcher = regex.matcher(string);
                                  foundMatch = regexMatcher.matches();
                                  return foundMatch;
                              } catch (PatternSyntaxException ex) {
                                  // Syntax error in the regular expression
                                  return false;
                              }
                          }
                          
                          public static boolean isValidEmail(String email, Context context) {
                              String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
                              CharSequence inputStr = email;
                              Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
                              Matcher matcher = pattern.matcher(inputStr);
                              if (matcher.matches()) {
                                  return true;
                              } else {
                                  // Helper.toast(context, "Email is not valid..!");
                          
                                  return false;
                              }
                          }
                          
                          public static boolean isValidUserName(String email, Context context) {
                              String expression = "^[0-9a-zA-Z]+$";
                              CharSequence inputStr = email;
                              Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
                              Matcher matcher = pattern.matcher(inputStr);
                              if (matcher.matches()) {
                                  return true;
                              } else {
                                  Helper.toast(context, "Username is not valid..!");
                                  return false;
                              }
                          }
                          
                          public static boolean isValidDateSlash(String inDate) {
                              SimpleDateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy");
                              dateFormat.setLenient(false);
                              try {
                                  dateFormat.parse(inDate.trim());
                              } catch (ParseException pe) {
                                  return false;
                              }
                              return true;
                          }
                          
                          public static boolean isValidDateDash(String inDate) {
                              SimpleDateFormat dateFormat = new SimpleDateFormat("dd-mm-yyyy");
                              dateFormat.setLenient(false);
                              try {
                                  dateFormat.parse(inDate.trim());
                              } catch (ParseException pe) {
                                  return false;
                              }
                              return true;
                          }
                          
                          public static boolean isValidDateDot(String inDate) {
                              SimpleDateFormat dateFormat = new SimpleDateFormat("dd.mm.yyyy");
                              dateFormat.setLenient(false);
                              try {
                                  dateFormat.parse(inDate.trim());
                              } catch (ParseException pe) {
                                  return false;
                              }
                              return true;
                          }
                          
                          }
                          

                          【讨论】:

                            【解决方案28】:
                            SharedPreferences.Editor editor = getSharedPreferences("identifier", 
                            MODE_PRIVATE).edit();
                            //identifier is the unique to fetch data from your SharedPreference.
                            
                            
                            editor.putInt("keyword", 0); 
                            // saved value place with 0.
                            //use this "keyword" to fetch saved value again.
                            editor.commit();//important line without this line your value is not stored in preference   
                            
                            // fetch the stored data using ....
                            
                            SharedPreferences prefs = getSharedPreferences("identifier", MODE_PRIVATE); 
                            // here both identifier will same
                            
                            int fetchvalue = prefs.getInt("keyword", 0);
                            // here keyword will same as used above.
                            // 0 is default value when you nothing save in preference that time fetch value is 0.
                            

                            您需要在 AdapterClass 或任何其他中使用 SharedPreferences。 那时只需使用此声明并使用上面相同的 ass。

                            SharedPreferences.Editor editor = context.getSharedPreferences("idetifier", 
                            Context.MODE_PRIVATE).edit();
                            SharedPreferences prefs = context.getSharedPreferences("identifier", Context.MODE_PRIVATE);
                            
                            //here context is your application context
                            

                            对于字符串或布尔值

                            editor.putString("stringkeyword", "your string"); 
                            editor.putBoolean("booleankeyword","your boolean value");
                            editor.commit();
                            

                            获取与上面相同的数据

                            String fetchvalue = prefs.getString("keyword", "");
                            Boolean fetchvalue = prefs.getBoolean("keyword", "");
                            

                            【讨论】:

                              【解决方案29】:

                              2.for 存储在共享偏好中

                              SharedPreferences.Editor editor = 
                              getSharedPreferences("DeviceToken",MODE_PRIVATE).edit();
                                                  editor.putString("DeviceTokenkey","ABABABABABABABB12345");
                              editor.apply();
                              

                              2.用于检索相同用途

                                  SharedPreferences prefs = getSharedPreferences("DeviceToken", 
                               MODE_PRIVATE);
                                String deviceToken = prefs.getString("DeviceTokenkey", null);
                              

                              【讨论】:

                                【解决方案30】:

                                在这里,我创建了一个 Helper 类来使用 android 中的首选项。

                                这是辅助类:

                                public class PrefsUtil {
                                
                                public static SharedPreferences getPreference() {
                                    return PreferenceManager.getDefaultSharedPreferences(Applicatoin.getAppContext());
                                }
                                
                                public static void putBoolean(String key, boolean value) {
                                    getPreference().edit().putBoolean(key, value)
                                            .apply();
                                }
                                
                                public static boolean getBoolean(String key) {
                                    return getPreference().getBoolean(key, false);
                                }
                                
                                public static void putInt(String key, int value) {
                                
                                    getPreference().edit().putInt(key, value).apply();
                                
                                }
                                
                                public static void delKey(String key) {
                                
                                    getPreference().edit().remove(key).apply();
                                
                                }
                                
                                }
                                

                                【讨论】:

                                  猜你喜欢
                                  • 1970-01-01
                                  • 2014-07-18
                                  • 2014-03-30
                                  • 1970-01-01
                                  • 1970-01-01
                                  • 1970-01-01
                                  • 2018-08-21
                                  • 2021-06-29
                                  • 1970-01-01
                                  相关资源
                                  最近更新 更多