How to save a string in sharedPreferences

时间:2019-01-07 13:38:34

标签: java android sharedpreferences

I have an application where I need to save a string in a sharedpreferences so that the user has already opened the application once and registered his email he does not have to go through the same screen again and instead go to the home screen directly.

My Class PreferencesHelpers

public class PreferencesHelpers {

private static final String SHARED_PREFS = "sharedPrefs";
private static final String TEXT = "ahhsaushhuuashu"; //I want to save this string

public String text;


public static void saveData(Context context) {
    SharedPreferences sharedPreferences = context.getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();

    editor.putString("", TEXT);

}

public static String loadData(Context context) {
    SharedPreferences sharedPreferences = context.getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
    String text = sharedPreferences.getString("ahhsaushhuuashu", "");
    return text;
   }

}

MyLogic in MainActivity to save and retrieve sharedPreferences value

  if (!preferencesHelpers.loadData(getApplicationContext()).contains("ahhsaushhuuashu")) {
                webView.loadUrl(URL_);
                preferencesHelpers.saveData(getApplicationContext());
            } else {
                switch (urlMessage) {
                    case "REDR":
                        webView.loadUrl(URL + "cira");
                        break;
                    default:
                        webView.loadUrl(URL + "?UDI=" + getInstance().getRegistrationManager().getSystemToken() + "&dev=" + getInstance().getRegistrationManager().getDeviceId() + "&source=app");
                }
            }

I looked for an answer that fit my condition but I did not find and forgive me for my English

2 个答案:

答案 0 :(得分:2)

您需要一个固定键来保存和读取您的首选项,而您忘记应用对SharedPreference的修改。

您需要这样做:

private static final String SHARED_PREFS = "sharedPrefs";
private static final String TEXT = "ahhsaushhuuashu";
private static final String KEY = "myKey";

public static void saveData(Context context) {
    SharedPreferences sharedPreferences = context.getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString(KEY, TEXT);
    editor.apply();
}

public static String loadData(Context context) {
    SharedPreferences sharedPreferences = context.getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
    String text = sharedPreferences.getString(KEY, "");
    return text;
}

答案 1 :(得分:0)

正如其他人在评论中所述,您需要用于存储值的键,但我也看到您没有将值保存在 saveData 方法中。

您需要输入以下行:

editor.apply()

之后

editor.putString("", TEXT);

使用 saveData 方法