【问题标题】:Using Android SharedPreferences or Internal Storage to store values of EditText fields locally使用 Android SharedPreferences 或 Internal Storage 在本地存储 EditText 字段的值
【发布时间】:2014-02-11 16:52:53
【问题描述】:

我目前正在大学做一个项目,我们正在为学生创建应用程序。

该应用程序的一部分正在简化对学生电子邮件的访问,因为我们当前的大学网站有点到处都是。

基本上我要做的是将用户的电子邮件和密码存储到我拥有的 EditTexts 中。

仅当用户选择存储数据的选项时才应存储数据。

此外,如果用户已经存储了数据,它应该跳过登录页面并直接进入 Web 视图。

有没有人有关于如何做到这一点的任何例子或任何提示?

我查看了几种不同的方法来做到这一点,但没有一个解释看起来很直接,而且很多教程都使用了我不知道如何转换的值。

*请注意,我对 Android 开发比较陌生,因为我今年才开始学习!

谢谢!

T.J.

【问题讨论】:

    标签: java android sdk android-ndk


    【解决方案1】:

    您可以将其保存到 sharedPreferences 中。你可以这样做:

    /** Constant to identify your sharedPref */
    public static final String MY_SHARED_PREFERENCES    = "mySharedPrefInstance";
    public static final String USER_TAG                 = "sharedPrefsUserTag";
    
    // Get shared preferences
    SharedPreferences sharedPref = getSharedPreferences(MY_SHARED_PREFERENCES, MODE_PRIVATE);
    
    // Check if sharedPreferences already contain this user
    if (sharedPref.getString(USER_TAG) == textView.gettext()) {
        // The user is already saved
    } else {
        // Save a string obj
    sharedPref.edit().putString(USER_TAG, editTextUser.getText());
    // Save password too
    sharedPref.edit().putString(PWD_TAG, editTextPwd.getText());
    
    // Maybe, you would to encrypt the pwd (I recommend this) 
    // So, for example:
    sharedPref.edit().putString(PWD_TAG, MD5( editTextPwd.getText() ) );
    
    // Commit changes
    sharedPref.commit();
    
    }
    
    /** Encrypt params string with MD5 algorithm */
    public static String MD5(String md5) {
        try {
            java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
            byte[] array = md.digest(md5.getBytes());
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < array.length; ++i) {
                sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1,3));
            }
            return sb.toString();
        } catch (java.security.NoSuchAlgorithmException e) { }
        return null;
    }
    

    如果您提供代码,就可以轻松地为您提供更好的帮助! 希望对您有所帮助。

    【讨论】:

      【解决方案2】:

      最好在设备上使用 SQLite 数据库。这样,如果应用程序根据需要进行扩展,可以通过相应地添加表或列来轻松扩展它。然后它还可以用于存储多个帐户,以便您可以在设备本身上进行登录验证。

      查看这些示例以获得使用 SQLite 数据库的帮助:

      Example 1 with Vogella

      Example 2 with Android Hive

      如果您先看一下 Android Hive,它会很好地解释它是如何工作的,就像 Vogella 向您展示了如何在您的代码中实现它一样。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-07-28
        • 2013-05-12
        • 2014-03-05
        • 1970-01-01
        • 2014-07-18
        • 1970-01-01
        • 2021-05-30
        • 2014-03-01
        相关资源
        最近更新 更多