如何在 sharedPreferences 中保存字符串 [英] How to save a string in sharedPreferences

查看:65
本文介绍了如何在 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.

我的班级偏好助手

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

我寻找了适合我情况的答案,但我没有找到并原谅我的英语

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

推荐答案

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

You need a fixed key to save and read your preference and you forgot to apply the modifications of the 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;
}

这篇关于如何在 sharedPreferences 中保存字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆