Kahn Mun
Kahn Mun

Reputation: 23

SharedPreferences with multiple files

I'm trying to write my first program, and am now learning and writing the part where I save general information and user information via SharedPreferences.

Used the documentation and wrote the first part for saving general information and everything worked great. I could write and read values perfectly.

I expanded to store user information in a second file, and it seems to write, but i always get the default value. If I switch to using the general information file instead of user file, it works.

I think I'm doing something wrong in how I am using GetSharedPreferences() where it is limiting me to using just 1 file like it says for GetPreferences().

The general settings I am storing in a file named "Data", and user settings I am saving in file User1, User2, etc for each user

Below is my code.

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        // If first time running app, create Guest user
        int intNumOfUsers=Integer.valueOf(funcReadData("Data","INT","NumOfUsers"));
        if (intNumOfUsers==0)
        {
            String strTest=funcReadData("User1","STR","User");
            subWriteData("Data","INT","NumOfUsers","1");
            subWriteData("User1","STR","Name","Guest");
            subWriteData("User1","STR","Pass","Guest");
        }

        // Determine if user needs to login before continuing
        if (Boolean.valueOf(funcReadData("Data", "BLN", "StayLoggedIn")))
        {
            subLoadMain();
            finish();
        }

    }

In above onStart, when the app is run the first time, it reads from "Data" file to get value of intNumOfUsers and if 0, it creates a default one by changing intNUmOfUsers to 1, and then creating a guest User/Pass in "User1" file.

The value to "Data" file saves and can be read perfectly, but the value to "User1" doesn't seem to save since I only get default value when I read it.

I use below common procedure to read and write data so no mistake with differences in code for each case exists.

 public void subWriteData(String strFile, String strType, String strKey, String strValue)
    {
        SharedPreferences prefs = getSharedPreferences(strFile, MODE_PRIVATE);

        SharedPreferences.Editor editor=prefs.edit();

        Log.d("WD","WRITE-"+strFile+"-"+strType+"-"+strKey+"-"+strValue);
        switch (strType)
        {
            case "STR":
                editor.putString(strKey, strValue);

                break;
            case "INT":
                editor.putInt(strKey,Integer.valueOf(strValue));
                break;
            case "BLN":
                editor.putBoolean(strKey,Boolean.valueOf(strValue));
                break;
            case "LNG":
                editor.putLong(strKey,Long.valueOf(strValue));
                break;
            case "FLT":
                editor.putFloat(strKey, Float.valueOf(strValue));
                break;
        }

        editor.commit();


    }

    public String funcReadData(String strFile, String strType, String strKey) {

        String strValue = "";

        SharedPreferences prefs = getSharedPreferences("Data", MODE_PRIVATE);

        switch (strType)
        {
            case "STR":
                strValue = prefs.getString(strKey, "");
                break;
            case "INT":
                strValue = String.valueOf(prefs.getInt(strKey, 0));
                break;
            case "BLN":
                strValue = String.valueOf(prefs.getBoolean(strKey, false));
                break;
            case "LNG":
                strValue = String.valueOf(prefs.getLong(strKey, 0));
                break;
            case "FLT":
                strValue = String.valueOf(prefs.getFloat(strKey, 0));
                break;
        }
        Log.d("WD","READ"+"-"+strFile+"-"+strType+"-"+strKey+"-"+strValue);
        return strValue;
    }

And below is just more code where I see if i can find user details and match against given information or create new user etc

    public void subCreateLogin(View view)
    {
        Boolean boolUserFound=false;
        Boolean boolUserLoggedIn=false;
        int intNumOfUsers;
        CheckBox chkStayLoggedIn = (CheckBox) findViewById(R.id.chkStayLoggedIn);

        EditText txtUser = (EditText)findViewById(R.id.txtUser);
        if (txtUser.getText().length()==0 )
        {
            Toast.makeText(Login.this, "Please enter a valid username", Toast.LENGTH_SHORT).show();
        }
        else
        {
            EditText txtPass = (EditText)findViewById(R.id.txtPass);
            if (txtPass.getText().length()==0 )
            {
                Toast.makeText(Login.this, "Password field cannot be empty", Toast.LENGTH_SHORT).show();
            }
            else
            {
                intNumOfUsers=Integer.valueOf(funcReadData("Data","INT","NumOfUsers"));
                if (intNumOfUsers>1)
                {
                    int Lvar;
                    String txtData;
                    for (Lvar = 1; Lvar <= intNumOfUsers; Lvar++)
                    {

                        txtData = funcReadData(("User"+Lvar).toString(), "STR","Name");
                        if (txtData.toUpperCase().equals(txtUser.getText().toString().toUpperCase()))
                        {
                            boolUserFound=true;
                            txtData = funcReadData(("User"+Lvar).toString(), "STR",  "Pass");
                            if (txtData.equals(txtPass.getText().toString()))
                            {
                                boolUserLoggedIn=true;
                                subWriteData("Data","STR","LastUser", txtUser.getText().toString());
                                if (chkStayLoggedIn.isChecked())
                                {
                                    subWriteData("Data","BLN","StayLoggedIn","true");
                                }

                            }
                            else
                            {
                                Toast.makeText(Login.this, "Incorrect password. Please try again.", Toast.LENGTH_SHORT).show();
                            }

                        }
                    }
                }

                if (!boolUserFound)
                {
                    // First new user, create his details
                    intNumOfUsers++;
                    subWriteData("Data","INT","NumOfUsers",String.valueOf(intNumOfUsers));
                    subWriteData(("User"+intNumOfUsers).toString(), "STR", "Name", txtUser.getText().toString());
                    subWriteData(("User"+intNumOfUsers).toString(),"STR","Pass",txtPass.getText().toString());
                    subWriteData("Data","STR","LastUser", txtUser.getText().toString());

                    //boolUserFound=true;
                    boolUserLoggedIn=true;
                    if (chkStayLoggedIn.isChecked())
                    {
                        subWriteData("Data","BLN","StayLoggedIn","true");
                    }

                }
            }
        }

        if (boolUserLoggedIn)
        {
            subLoadMain();
            finish();
        }
    }

So anything that reads/write to "Data" is fine, but to "User1", "User2" etc never seems to work. How do I enable the ability to save multiple preferences files?

Thanks!

Upvotes: 0

Views: 201

Answers (1)

Mo1989
Mo1989

Reputation: 2494

in your read data function while getting the shared prefs you have specified the file name as Data instead of passing in the file name while in writing you use the passed in filename.

Upvotes: 1

Related Questions