简体   繁体   English

使用SharedPreferences在Android应用程序中保存String [] []数组

[英]Save String[][] array in android application with SharedPreferences

I have read the related posts in this topic and I can not solve my problem. 我已经阅读了本主题的相关文章,但无法解决我的问题。 Please take a look at my code and let me know where the problem is. 请查看我的代码,让我知道问题出在哪里。

I want to create a String[10][2] array in my application, so whenever my application starts, it retrieves this array and works around it. 我想在我的应用程序中创建一个String [10] [2]数组,因此,每当我的应用程序启动时,它都会检索该数组并对其进行处理。 The array consists of username and a password corresponding to that username. 该数组由用户名和与该用户名对应的密码组成。 I want to create new password for new user and retrieve password for already registered user. 我想为新用户创建新密码,并为已经注册的用户检索密码。

public class PasswordGeneration extends Activity {

    private static final String charSet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()_+=-/?";
    private static Random rnd = new Random();
    private String[][] globDataBase = new String[10][2];
    private String password;
    private String temp;
    ImageButton buttonBack;
    TextView setPass;
    String name,genePass;





    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        setContentView(R.layout.pass_result);
        buttonBack=(ImageButton)findViewById(R.id.widget54);
        setPass = (TextView)findViewById(R.id.widget51);

        Bundle bundle = getIntent().getExtras();
        name=bundle.getString("name");
        name = "Amir";//for testing, this line should be omitted for real application
        globDataBase = loadDataBase(this);
        genePass = passwordGeneration(name, 12);
        setPass.setText(genePass);


        buttonBack.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                finish();

            }
        });


    }



    public String passwordGeneration(String name, int len) {

        for(int i = 0; i < 10; i++){
            if(globDataBase[i][0] == name){
                return globDataBase[i][1];

            }

        }
                StringBuilder sb = new StringBuilder(len);
                for(int j = 0; j < len; j++ )
                sb.append(charSet.charAt(rnd.nextInt(charSet.length())));
                password =  sb.toString();
                setDataBase(name, password);
                return password;
    }

    public void setDataBase(String name, String password){

        for (int i = 0; i < 10; i++){
            if(globDataBase[i][0] == null){
                globDataBase[i][0] = name;
                globDataBase[i][1] = password;
                break;
            }
        }
        saveDataBase(globDataBase, this);
        return;

    }

    public boolean saveDataBase(String[][] db, Context mContext){
        SharedPreferences prefs = mContext.getSharedPreferences("dataBase", 0);
        Editor editor = prefs.edit();
        for(int i = 0; i < 10; i++){
            for(int j = 0; j < 2; j++){
                editor.putString("dataBase", db[i][j]);
            }
        }
        return editor.commit();
    }

    public String[][] loadDataBase(Context mContext){
        SharedPreferences prefs = mContext.getSharedPreferences("dataBase", 0);
        String[][] dataBase = new String[10][2];
        for(int i = 0; i < 10; i++){
            for(int j = 0; j < 2; j++){
            dataBase[i][j] = prefs.getString("dataBase", null);
            }
        }
        return dataBase;
    }
}

When I run my application, I get password for username = "Amir", and when I run the application again, I expect to get the same password, but I get a new one for the same name "Amir". 当我运行我的应用程序时,我得到了用户名=“ Amir”的密码,当我再次运行该应用程序时,我希望获得相同的密码,但是我得到了一个新名称相同的“ Amir”。 I can not figure out where the problem is. 我不知道问题出在哪里。

for(int i = 0; i < 10; i++){
            for(int j = 0; j < 2; j++){
                editor.putString("dataBase", db[i][j]);
            }
        }

this is wrong because you are basically looping and overriding the value for the key "dataBase". 这是错误的,因为您基本上是在循环并覆盖键“数据库”的值。

I would suggest you to find another way to save the data. 我建议您找到另一种保存数据的方法。 If you still want to use shared preferences you maybe will end up to create several keys for each element like this: 如果仍然要使用共享首选项,则可能最终会为每个元素创建多个键,如下所示:

for(int i = 0; i < 10; i++){
            for(int j = 0; j < 2; j++){
                editor.putString("dataBase["+i+"]["+j+"]", db[i][j]);
            }
        }

so you will create entries like "dataBase[0][1]" and then you need the logic to retrieve them... but again, to me looks like a not optimal solution 因此您将创建“ dataBase [0] [1]”之类的条目,然后需要逻辑来检索它们……但是,对我来说,这似乎不是一个最佳解决方案

It seems you may not know how to use key-value container.See the code blew: 似乎您可能不知道如何使用键值容器。请参阅以下代码:

//it errors
editor.putString("dataBase", db[i][j]);

After you save your name and password 保存名称和密码后

editor.putString("dataBase", "Amir");
editor.putString("dataBase", "Amirpwd");

you will get "Amirpwd" 你会得到“ Amirpwd”

prefs.getString("dataBase", null)//it returns "Amirpwd"

Solution: 解:

editor.putString("Amir", "Amirpwd");

you will get the correct pwd 您将获得正确的密码

String pwd = prefs.getString("Amir", null)//it returns "Amirpwd"

Another good method is to serialize your array to string (for example to JSON string) and put it to preferences with method putString. 另一个好的方法是将数组序列化为字符串(例如,转换为JSON字符串),然后使用putString方法将其置于首选项。

When you will need to get it you can deserialize serialized string. 当需要获取它时,可以反序列化序列化的字符串。

You can use JSONArray class for serialization. 您可以使用JSONArray类进行序列化。

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

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