简体   繁体   English

在共享首选项中存储字符串时如何写而不覆盖

[英]How to write and not overwrite when storing strings in shared preferences android

Storing Strings : 存储字符串:

Encryption encryption = Encryption.getDefault("Key", "Salt", new byte[16]);
                String encryptedP = encryption.encryptOrNull(Password);
                String encryptedU = encryption.encryptOrNull(Username);    
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
            Editor edit = prefs.edit();
            edit.putString("Password", encryptedP);
            edit.putString("Username", encryptedU);
            edit.commit(); 

Retrieving Strings : 检索字符串:

Encryption encryption = Encryption.getDefault("Key", "Salt", new byte[16]);
    String encryptedP = encryption.encryptOrNull(Password);
    String encryptedU = encryption.encryptOrNull(Username);
    SharedPreferences sPrefs = PreferenceManager.getDefaultSharedPreferences(LoginActivity.this);
    String UsernamePref = sPrefs.getString("Username", "");
    String PasswordPref = sPrefs.getString("Password", "");
    if(encryptedU.equals(UsernamePref) &&  (encryptedP.equals(PasswordPref))) {  if((NewPassword.matches (ConfirmPassword))) {
                Editor edit = sPrefs.edit();
                edit.putString("Password", encryptedN);
                edit.commit();          

When retrieving, unless i am retrieving the last strings stored, it will not succeed as it will not look on all lines. 检索时,除非我正在检索存储的最后一个字符串,否则它将不会成功,因为它将不会出现在所有行上。 Only the first line, how do i change this so that it scans every line before closing file ? 仅第一行,我如何更改此设置,以便它在关闭文件之前扫描每一行? Thanks 谢谢

Edit : Okay so i just realised its overwriting each time, not actually storing it onto a new line, which is why it can't retrieve "old strings", new question. 编辑:好的,所以我每次都意识到它的覆盖,而不是实际将其存储到新行中,这就是为什么它无法检索“旧字符串”,新问题。 How do i store and not overwrite each time i create a new user ? 每次创建新用户时,如何存储而不覆盖?

This "error" is because you are not storing the preferences properly: 该“错误”是因为您没有正确存储首选项:

you need to commit the preferences in the editor 您需要在编辑器中提交首选项

do: 做:

SharedPreferences spref = getSharedPreferences("your_prefs_name", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = spref.edit();
editor.putString("myTextViewValue", prefVal); 
editor.commit(); // HERE add this line!!!

I think it would be better if you used a database. 我认为如果您使用数据库会更好。 Using shared prefs to store a large amount of data needs a lot of complicated code. 使用共享首选项存储大量数据需要大量复杂的代码。

Every time you need to store a lot of entries of the same kind of data, in this case, passwords and usernames, you should use a database instead of shared prefs. 每次需要存储大量相同类型数据的条目(在这种情况下,是密码和用户名)时,都应使用数据库而不是共享首选项。

I know that setting up an SQLite database in android is very annoying and requires a lot of code. 我知道在android中设置SQLite数据库非常烦人,需要大量代码。 So to simplify things a bit, I recommend the SugarORM library. 因此,为简化起见,我建议使用SugarORM库。 It is an object relational mapping (ORM) library that just simplifies your experience in using an SQLite database 它是一个对象关系映射(ORM)库,仅简化了您使用SQLite数据库的经验

Basically, you create a table in the database by creating a class that extends SugarRecord 基本上,您可以通过创建扩展SugarRecord的类在数据库中创建表

public class User extends SugarRecord<User> {
    public String username;
    public String password;

    public User () {} // parameterless constructor is required
    public User (String username, String password) {
        this.username = username;
        this.password = password;
    }
}

When you want to save a new user to the database, it is as simple as 要将新用户保存到数据库时,它很简单

User u = new User("Sweeper", "123456");
u.save();

You can use methods such as listAll , find , findById to query the database! 您可以使用listAllfindfindById来查询数据库! One to many relationships are supported! 支持一对多关系!

You can find more information on the website. 您可以在网站上找到更多信息。

To store records in the SharedPreferences for each user you can modify the preferences key. 要将记录存储在每个用户的SharedPreferences ,您可以修改首选项键。 It will prevent overwriting the values. 这将防止覆盖值。

For instance 例如

String getFormattedName(String username, String value) {
    return String.format("%s_%s", username, value);
}

Then you can store the records like this: 然后您可以像这样存储记录:

edit.putString(getFormattedName(encryptedU, "Password"), encryptedP);
edit.putString(getFormattedName(encryptedU, "Username"), encryptedU);

and retrieve: 并检索:

String UsernamePref = sPrefs.getString(getFormattedName(encryptedU, "Username"), "");
String PasswordPref = sPrefs.getString(getFormattedName(encryptedU, "Password"), "");

So the key will be like 123123_Username . 因此,密钥将类似于123123_Username Of cource you can modify the pattern as you need. 当然,您可以根据需要修改模式。

package com.example.preferences;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.annotation.NonNull;

public class DumbPref {
    private SharedPreferences mPreferences;

    public DumbPref(@NonNull Context context, @NonNull String name) {
        mPreferences = context.getSharedPreferences(name, Context.MODE_PRIVATE);
    }

    @SuppressLint("CommitPrefEdits")
    public void addUser(@NonNull String name, @NonNull String password) {
        SharedPreferences.Editor editor = mPreferences.edit();
        editor.putBoolean(makeKey(name, password), true);
        editor.commit();
    }

    public boolean isAuthenticated(String name, String password) {
        return mPreferences.getBoolean(makeKey(name, password), false);
    }

    private static String makeKey(String name, String password) {
        return name + "_" + password;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM