Search code examples
javaandroidsharedpreferences

How can I get username and password from SharedPreferences in Android?


I am trying to recover the username and password to be able to start a session. These are the users of the sharedPreferences.

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
    <string name="admin">1234</string>
    <string name="user">user0987</string>
</map>

And this is the method

login.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        SharedPreferences sp1 = MainActivity.this.getSharedPreferences("data", Context.MODE_PRIVATE);
        String user = sp1.getString(userInput.getText().toString(), "User not found");
        String pass = sp1.getString(passwordInput.getText().toString(), "Password is not correct");
        
        if(user.equals(userInput.getText().toString()){
            Toast.makeText(MainActivity.this, "User Exists", Toast.LENGTH_SHORT).show();
        } else{
            Toast.makeText(MainActivity.this, "User not found", Toast.LENGTH_SHORT).show();
        }

    }
});

This is the code that puts data in SharedPreferences

register.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
       
        String user = userInput.getText().toString();
        String pass = passwordInput.getText().toString();

        if(user.isEmpty()){
            error.show();
        } else if (pass.isEmpty()){
            error2.show();
        } else{
            SharedPreferences sp=getSharedPreferences("data", Context.MODE_PRIVATE);
            SharedPreferences.Editor Ed=sp.edit();
            Ed.putString(user,pass);
            Ed.commit();
            Toast.makeText(MainActivity.this, "Register completed", Toast.LENGTH_SHORT).show();
        }

    }
});

Solution

  • Please try to use next code when you retrieve data from SP:

    SharedPreferences sp1 = MainActivity.this.getSharedPreferences("data", Context.MODE_PRIVATE);
    String pass = sp1.getString(userInput.getText().toString(), null);
    if (pass != null) {
        Toast.makeText(MainActivity.this, "User Exists", Toast.LENGTH_SHORT).show();
    } else{
        Toast.makeText(MainActivity.this, "User not found", Toast.LENGTH_SHORT).show();
    }
    

    You are saving data in form of "user:pasword", so you need to get it the same way, using user name as the key.