【问题标题】:Android Shared preferences for creating one time activity (example) [closed]用于创建一次性活动的 Android 共享首选项(示例)[关闭]
【发布时间】:2014-05-26 07:57:26
【问题描述】:

我有三个活动 A、B 和 C,其中 A 和 B 是表格,并且在填写表格数据并将其保存在数据库 (SQLITE) 中之后。我正在使用从 A 到 B 然后从 B 到 C 的意图。我想要的是每次打开我的应用程序时,我都希望 C 作为我的主屏幕,而不是 A 和 B。

我想共享偏好可以解决这个问题,但我找不到一个很好的例子来给我一个起点。任何帮助将不胜感激。

【问题讨论】:

标签: android android-activity sharedpreferences


【解决方案1】:

在 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.apply();

从偏好中检索数据:

SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE); 
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

【讨论】:

  • 考虑使用 apply() 代替; commit 立即将其数据写入持久存储,而 apply 将在后台处理它。
  • apply() 是异步调用以执行磁盘 I/O,而 commit() 是同步的。所以避免从 UI 线程调用commit()
  • 谢谢,我在多个项目中使用了你的代码
【解决方案2】:

创建共享首选项

SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE); 
Editor editor = pref.edit();

将数据存储为 KEY/VALUE 对

editor.putBoolean("key_name1", true);           // Saving boolean - true/false
editor.putInt("key_name2", "int value");        // Saving integer
editor.putFloat("key_name3", "float value");    // Saving float
editor.putLong("key_name4", "long value");      // Saving long
editor.putString("key_name5", "string value");  // Saving string

// Save the changes in SharedPreferences
editor.apply(); // commit changes

获取 SharedPreferences 数据

// 如果键的值不存在,则返回第二个参数值 - 在这种情况下为 null

boolean userFirstLogin= pref.getBoolean("key_name1", true);  // getting boolean
int pageNumber=pref.getInt("key_name2", 0);             // getting Integer
float amount=pref.getFloat("key_name3", null);          // getting Float
long distance=pref.getLong("key_name4", null);          // getting Long
String email=pref.getString("key_name5", null);         // getting String

从 SharedPreferences 中删除键值

editor.remove("key_name3"); // will delete key key_name3
editor.remove("key_name4"); // will delete key key_name4

// Save the changes in SharedPreferences
editor.apply(); // commit changes

清除 SharedPreferences 中的所有数据

 editor.clear();
 editor.apply(); // commit changes

【讨论】:

  • pref.getBoolean("key_name1", null);它不能为空。如果没有存储任何内容,则需要一个默认值。
  • 你最好使用 apply() 而不是 commit()。 apply() 是异步的,您将在后台线程上运行它
  • 如果 key_name3 或 key_name4 为空会崩溃
  • 我有一个存储用户信息的注册页面,我有一个用户使用该信息登录的登录页面。我有两个课程,我在一个课程中获取信息,我想在其他课程中使用该信息。当我在我的代码中使用上述代码时。我取空指针异常。有像我这样的用法吗? @KrauszLórántSzilveszter
【解决方案3】:

如何初始化?

// 0 - for private mode`
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); 

Editor editor = pref.edit();

如何在共享首选项中存储数据?

editor.putString("key_name", "string value"); // Storing string

editor.putInt("key_name", "int value"); //Storing integer

别忘了申请:

editor.apply();

如何从共享首选项中检索数据?

pref.getString("key_name", null); // getting String

pref.getInt("key_name", 0); // getting Integer

希望这对你有帮助:)

【讨论】:

  • 如果您在活动、片段或公共类中访问,初始化很重要
【解决方案4】:

您可以创建自定义的 SharedPreference 类

public class YourPreference {   
    private static YourPreference yourPreference;
    private SharedPreferences sharedPreferences;

    public static YourPreference getInstance(Context context) {
        if (yourPreference == null) {
            yourPreference = new YourPreference(context);
        }
        return yourPreference;
    }

    private YourPreference(Context context) {
        sharedPreferences = context.getSharedPreferences("YourCustomNamedPreference",Context.MODE_PRIVATE);
    }

    public void saveData(String key,String value) {
        SharedPreferences.Editor prefsEditor = sharedPreferences.edit();
        prefsEditor .putString(key, value);
        prefsEditor.commit();           
    }

    public String getData(String key) {
        if (sharedPreferences!= null) {
           return sharedPreferences.getString(key, "");
        }
        return "";         
    }
}

你可以像这样得到 YourPrefrence 实例:

YourPreference yourPrefrence = YourPreference.getInstance(context);
yourPreference.saveData(YOUR_KEY,YOUR_VALUE);

String value = yourPreference.getData(YOUR_KEY);

【讨论】:

  • 字符串值 = yourPreference.getData(YOUR_KEY);错误:无法在静态上下文中引用非静态内容
  • 你的 Context 实例给了我 null 所以我把 sharedPreferences = context.getSharedPreferences("YourCustomNamedPreference",Context.MODE_PRIVATE); try catch 块中的这一行及其工作,但问题是为什么它给出 null?
  • 我在我的项目中使用这个类并在 BaseActivity 中初始化我的 sharedpreferences,并在其他活动(splashScreen & login & main Activity)中使用以检查用户登录状态并退出应用程序。但这不适用于 android 8 退出!你有什么建议吗?
【解决方案5】:

我只是发现上面所有的例子都太混乱了,所以我自己写了。如果你知道自己在做什么,代码片段很好,但像我这样不知道的人呢?

想要一个剪切-n-粘贴解决方案吗?好吧,就在这里!

创建一个新的 java 文件并将其命名为 Keystore。然后粘贴这段代码:

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;

public class Keystore { //Did you remember to vote up my example?
    private static Keystore store;
    private SharedPreferences SP;
    private static String filename="Keys";

private Keystore(Context context) {
    SP = context.getApplicationContext().getSharedPreferences(filename,0);
}

public static Keystore getInstance(Context context) {
    if (store == null) {
        Log.v("Keystore","NEW STORE");
        store = new Keystore(context);
    }
    return store;
}

public void put(String key, String value) {//Log.v("Keystore","PUT "+key+" "+value);
    Editor editor = SP.edit();
    editor.putString(key, value);
    editor.commit(); // Stop everything and do an immediate save!
    // editor.apply();//Keep going and save when you are not busy - Available only in APIs 9 and above.  This is the preferred way of saving.
}

public String get(String key) {//Log.v("Keystore","GET from "+key);
    return SP.getString(key, null);

}

public int getInt(String key) {//Log.v("Keystore","GET INT from "+key);
    return SP.getInt(key, 0);
}

public void putInt(String key, int num) {//Log.v("Keystore","PUT INT "+key+" "+String.valueOf(num));
    Editor editor = SP.edit();

    editor.putInt(key, num);
    editor.commit();
}


public void clear(){ // Delete all shared preferences
    Editor editor = SP.edit();

    editor.clear();
    editor.commit();
}

public void remove(){ // Delete only the shared preference that you want
    Editor editor = SP.edit();

    editor.remove(filename);
    editor.commit();
}
}

现在保存该文件并忘记它。你已经完成了。现在回到你的活动并像这样使用它:

public class YourClass extends Activity{

private Keystore store;//Holds our key pairs

public YourSub(Context context){
    store = Keystore.getInstance(context);//Creates or Gets our key pairs.  You MUST have access to current context!

    int= store.getInt("key name to get int value");
    string = store.get("key name to get string value");

    store.putInt("key name to store int value",int_var);
    store.put("key name to store string value",string_var);
    }
}

【讨论】:

  • 我在我的项目中使用这个类并在 BaseActivity 中初始化我的 sharedpreferences,并在其他活动(splashScreen & login & main Activity)中使用以检查用户登录状态并退出应用程序。但这不适用于 android 8 退出!你有什么建议吗?
【解决方案6】:

Shared Preferences 是 XML 文件,用于将私有原始数据存储在键值对中。数据类型包括 Booleansfloatsintslongsstrings

当我们想要保存一些可在整个应用程序中访问的数据时,一种方法是将其保存在全局变量中。但是一旦应用程序关闭,它就会消失。另一种推荐的方法是保存在SharedPreference。保存在 SharedPreferences 文件中的数据可在整个应用程序中访问,并且即使在应用程序关闭或重新启动后仍然存在。

SharedPreferences 将数据保存在键值对中,并且可以以相同的方式访问。

您可以使用两种方法创建SharedPreferences的对象,

1).getSharedPreferences():使用此方法您可以创建多个 SharedPreferences.and 它的第一个参数名称为SharedPreferences

2).getPreferences() :使用此方法您可以创建单个SharedPreferences

存储数据

添加变量声明/创建首选项文件

public static final String PREFERENCES_FILE_NAME = "MyAppPreferences";

检索文件名句柄(使用 getSharedPreferences)

SharedPreferences settingsfile= getSharedPreferences(PREFERENCES_FILE_NAME,0);

打开编辑器并添加键值对

SharedPreferences.Editor myeditor = settingsfile.edit(); 
myeditor.putBoolean("IITAMIYO", true); 
myeditor.putFloat("VOLUME", 0.7)
myeditor.putInt("BORDER", 2)
myeditor.putLong("SIZE", 12345678910L)
myeditor.putString("Name", "Amiyo")
myeditor.apply(); 

不要忘记使用myeditor.apply() 应用/保存,如上所示。

检索数据

 SharedPreferences mysettings= getSharedPreferences(PREFERENCES_FILE_NAME, 0);
IITAMIYO = mysettings.getBoolean("IITAMIYO", false); 
//returns value for the given key. 
//second parameter gives the default value if no user preference found
// (set to false in above case)
VOLUME = mysettings.getFloat("VOLUME", 0.5) 
//0.5 being the default value if no volume preferences found
// and similarly there are get methods for other data types

【讨论】:

    【解决方案7】:
    public class Preferences {
    
    public static final String PREF_NAME = "your preferences name";
    
    @SuppressWarnings("deprecation")
    public static final int MODE = Context.MODE_WORLD_WRITEABLE;
    
    public static final String USER_ID = "USER_ID_NEW";
    public static final String USER_NAME = "USER_NAME";
    
    public static final String NAME = "NAME";
    public static final String EMAIL = "EMAIL";
    public static final String PHONE = "PHONE";
    public static final String address = "address";
    
    public static void writeBoolean(Context context, String key, boolean value) {
        getEditor(context).putBoolean(key, value).commit();
    }
    
    public static boolean readBoolean(Context context, String key,
            boolean defValue) {
        return getPreferences(context).getBoolean(key, defValue);
    }
    
    public static void writeInteger(Context context, String key, int value) {
        getEditor(context).putInt(key, value).commit();
    
    }
    
    public static int readInteger(Context context, String key, int defValue) {
        return getPreferences(context).getInt(key, defValue);
    }
    
    public static void writeString(Context context, String key, String value) {
        getEditor(context).putString(key, value).commit();
    
    }
    
    public static String readString(Context context, String key, String defValue) {
        return getPreferences(context).getString(key, defValue);
    }
    
    public static void writeFloat(Context context, String key, float value) {
        getEditor(context).putFloat(key, value).commit();
    }
    
    public static float readFloat(Context context, String key, float defValue) {
        return getPreferences(context).getFloat(key, defValue);
    }
    
    public static void writeLong(Context context, String key, long value) {
        getEditor(context).putLong(key, value).commit();
    }
    
    public static long readLong(Context context, String key, long defValue) {
        return getPreferences(context).getLong(key, defValue);
    }
    
    public static SharedPreferences getPreferences(Context context) {
        return context.getSharedPreferences(PREF_NAME, MODE);
    }
    
    public static Editor getEditor(Context context) {
        return getPreferences(context).edit();
    }
    
    }
    

    ****使用首选项写入值:-****

    Preferences.writeString(getApplicationContext(),
                        Preferences.NAME, "dev");
    

    ****使用首选项读取值使用:-****

    Preferences.readString(getApplicationContext(), Preferences.NAME,
                        "");
    

    【讨论】:

      【解决方案8】:

      创建SharedPreference 的最佳方法是为了全局使用,您需要创建一个如下所示的类:

      public class PreferenceHelperDemo {
          private final SharedPreferences mPrefs;
      
          public PreferenceHelperDemo(Context context) {
              mPrefs = PreferenceManager.getDefaultSharedPreferences(context);
          }
      
          private String PREF_Key= "Key";
      
          public String getKey() {
              String str = mPrefs.getString(PREF_Key, "");
              return str;
          }
      
          public void setKey(String pREF_Key) {
              Editor mEditor = mPrefs.edit();
              mEditor.putString(PREF_Key, pREF_Key);
              mEditor.apply();
          }
      
      }
      

      【讨论】:

      • PreferenceManager.getDefaultSharedPreferences 已弃用
      【解决方案9】:
      SharedPreferences mPref;
      SharedPreferences.Editor editor;
      
      public SharedPrefrences(Context mContext) {
          mPref = mContext.getSharedPreferences(Constant.SharedPreferences, Context.MODE_PRIVATE);
          editor=mPref.edit();
      }
      
      public void setLocation(String latitude, String longitude) {
          SharedPreferences.Editor editor = mPref.edit();
          editor.putString("latitude", latitude);
          editor.putString("longitude", longitude);
          editor.apply();
      }
      
      public String getLatitude() {
          return mPref.getString("latitude", "");
      }
      
      public String getLongitude() {
          return mPref.getString("longitude", "");
      }
      
      public void setGCM(String gcm_id, String device_id) {
           editor.putString("gcm_id", gcm_id);
          editor.putString("device_id", device_id);
          editor.apply();
      }
      
      public String getGCMId() {
          return mPref.getString("gcm_id", "");
      }
      
      public String getDeviceId() {
          return mPref.getString("device_id", "");
      }
      
      
      public void setUserData(User user){
      
          Gson gson = new Gson();
          String json = gson.toJson(user);
          editor.putString("user", json);
          editor.apply();
      }
      public User getUserData(){
          Gson gson = new Gson();
          String json = mPref.getString("user", "");
          User user = gson.fromJson(json, User.class);
          return user;
      }
      
      public void setSocialMediaStatus(SocialMedialStatus status){
      
          Gson gson = new Gson();
          String json = gson.toJson(status);
          editor.putString("status", json);
          editor.apply();
      }
      public SocialMedialStatus getSocialMediaStatus(){
          Gson gson = new Gson();
          String json = mPref.getString("status", "");
          SocialMedialStatus status = gson.fromJson(json, SocialMedialStatus.class);
          return status;
      }
      

      【讨论】:

        【解决方案10】:

        写入共享首选项

        SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putInt(getString(R.string.saved_high_score), newHighScore);
         editor.commit(); 
        

        从共享首选项中读取

        SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
        int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
        long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);
        

        【讨论】:

        • 使用 getSharedPreferences("MyPref", MODE_PRIVATE);而不是:getPreferences(Context.MODE_PRIVATE);因为数据仅对您正在进行的活动有效。这是因为在此活动中,文件名位于活动名称上,因此如果您从另一个活动中调用此首选项,则数据将有所不同。
        【解决方案11】:
        SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putInt(getString(R.string.saved_high_score), newHighScore);
        editor.commit();
        

        【讨论】:

        • 欢迎来到 Stack Overflow!请解释如何使用您提供的代码及其工作原理。谢谢!
        【解决方案12】:

        你也可以看看我过去的sample project,就是为此目的而写的。我在本地保存一个名称,并在用户请求或应用启动时检索它。

        但是,此时最好使用commit(而不是apply)来持久化数据。更多信息here

        【讨论】:

          【解决方案13】:
          Initialise here..
           SharedPreferences msharedpref = getSharedPreferences("msh",
                              MODE_PRIVATE);
                      Editor editor = msharedpref.edit();
          
          store data...
          editor.putString("id",uida); //uida is your string to be stored
          editor.commit();
          finish();
          
          
          fetch...
          SharedPreferences prefs = this.getSharedPreferences("msh", Context.MODE_PRIVATE);
                  uida = prefs.getString("id", "");
          

          【讨论】:

            【解决方案14】:
                    // Create object of SharedPreferences.
                    SharedPreferences sharedPref = getSharedPreferences("mypref", 0);
            
                    //now get Editor
                    SharedPreferences.Editor editor = sharedPref.edit();
            
                    //put your value
                    editor.putString("name", required_Text);
            
                    //commits your edits
                    editor.commit();
            
                   // Its used to retrieve data
                   SharedPreferences sharedPref = getSharedPreferences("mypref", 0);
                   String name = sharedPref.getString("name", "");
            
                   if (name.equalsIgnoreCase("required_Text")) {
                      Log.v("Matched","Required Text Matched");
                      } else {
                           Log.v("Not Matched","Required Text Not Matched"); 
                             }
            

            【讨论】:

              【解决方案15】:

              Shared Preferences 很容易学习,所以看看这个 关于sharedpreference的简单教程

              import android.os.Bundle;
              import android.preference.PreferenceActivity;
              
                  public class UserSettingActivity extends PreferenceActivity {
              
                  @Override
                  public void onCreate(Bundle savedInstanceState) {
                  super.onCreate(savedInstanceState);
              
                    addPreferencesFromResource(R.xml.settings);
              
                  }
              }
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2012-09-08
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2017-04-11
                相关资源
                最近更新 更多