[英]How to save a string in sharedPreferences
我有一個應用程序,我需要在共享首選項中保存一個字符串,這樣用戶就已經打開了該應用程序一次並注冊了他的電子郵件,他不必再次進入同一屏幕,而直接進入主屏幕。
我的班級偏好設置助手
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在MainActivity中保存和檢索sharedPreferences值
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");
}
}
我在尋找適合自己條件的答案,但沒有找到並原諒我的英語
您需要一個固定鍵來保存和讀取您的首選項,而您忘記應用對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;
}
正如其他人在評論中提到的那樣,您需要用於存儲值的鍵,但我也看到您沒有將值保存在saveData方法中。
您需要輸入以下內容:
editor.apply()
后
editor.putString("", TEXT);
在saveData方法中
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.