我有三个活动A, B和C,其中A和B是表单,并在数据库(SQLite)中填充和保存表单数据后。我使用意图从A到B,然后从B到C,我想要的是,每次我打开我的应用程序时,我想要C作为我的主屏幕,而不再是A和B。

我想共享偏好可以解决这个问题,但我找不到一个好的例子来给我一个起点。


当前回答

在“偏好”中设置值:

// 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.

更多信息:

使用共享首选项

共同的喜好

其他回答

如何初始化?

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

Editor editor = pref.edit();

如何在共享偏好中存储数据?

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

OR

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

别忘了申请:

editor.apply();

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

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

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

希望这对你有帮助:)

共享首选项是XML文件,用于以键-值对存储私有原始数据。数据类型包括布尔型、浮点型、整型、长型和字符串。

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

SharedPreferences以键值对的方式保存数据,可以以相同的方式访问。

你可以使用两个方法创建SharedPreferences对象,

1). getsharedpreferences():使用这个方法你可以创建多个SharedPreferences。它的第一个参数名为SharedPreferences。

2). getpreferences():使用这个方法你可以创建Single 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(); 

不要忘记如上所示使用meditor .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
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;
}

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

想要一个剪切-粘贴的解决方案?好了,就是这里!

创建一个新的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);
    }
}

写入共享首选项

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);