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


当前回答

我想在这里补充一点,当使用SharedPreferences时,这个问题的大多数代码片段都有类似MODE_PRIVATE的东西。MODE_PRIVATE意味着无论您写入这个共享首选项的是什么,都只能由您的应用程序读取。

Whatever key you pass to getSharedPreferences() method, android creates a file with that name and stores the preference data into it. Also remember that getSharedPreferences() is supposed to be used when you intend to have multiple preference files for your application. If you intend to use single preference file and store all key-value pairs into it then use the getSharedPreference() method. Its weird why everyone (including myself) simply uses getSharedPreferences() flavor without even understanding the difference between the above two.

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

其他回答

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

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.
editor.putString("text", mSaved.getText().toString());

这里,mSaved可以是任何TextView或EditText,从中我们可以提取一个字符串。您可以简单地指定一个字符串。这里的text将是键,它持有从mSaved (TextView或EditText)获得的值。

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

此外,不需要使用包名保存首选项文件,即“com.example.app”。你可以提到自己喜欢的名字。希望这能有所帮助!

存储在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”为sharedpreferences名称,“name”为输入值。如果value不存在,则返回null

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

使用SharedPreference实例,可以使用getInt(String key, int defVal)检索任意首选项的int值。在这种情况下,我们更倾向于使用计数器。

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

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

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
    }
}

main。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>

您可以使用以下方法保存值:

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是用来保存特定值的键。谢谢。