Search code examples
javaandroidandroid-sharedpreferences

How to get multiple values from sharedPreferences on Android?


I'm registering a user on my test app and save all my data to the persistent storage using sharedPreferences, but I would like to fetch those values after logging in by calling the getData method which has to return all data that have been saved for current registered user which will consist of his name, username, and date of birth. So I thought of using a map since it's a dictionary kinda in java.

But I'm not sure whether I did the right thing in my catch inside the getData.

Bellow is my code:

public class AddUser {

    private static String NAME_KEY;
    private static String DOB_KEY;
    private static String USERNAME_KEY;
    private static String PASSWORD_KEY;

    Map<String,String> values = new HashMap<String,String>();

    public static void saveData(Context context, String name, String dob, String username, String password){
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString(NAME_KEY, name);
        editor.putString(DOB_KEY, dob);
        editor.putString(USERNAME_KEY, username);
        editor.putString(PASSWORD_KEY, password);
        editor.commit();
    }

    public Map<String, String> getData(Context context, String name, String dob, String username){
        SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
        try{
            sharedPrefs.getString(NAME_KEY, name);
            sharedPrefs.getString(USERNAME_KEY, username);
            sharedPrefs.getString(DOB_KEY, dob);
            values = (Map<String, String>) sharedPrefs;
            return values;
        } catch(Exception e) {
            e.printStackTrace();
            return values;
        }
    }
}

My goal is to get the returned values name, username and date of birth and display them on different fields I would like to.


Solution

  • public Map<String, String> getData(Context context) { //other paramaters are only usefull if you want provide default values
        SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
        Map<String, String> userDetails = new HashMap<String,String>(); //create the map with String->String
    
        String name = sharedPrefs.getString(NAME_KEY, null); //get the value
        userDetails.put(NAME_KEY, name); //put it in the map
        String username = sharedPrefs.getString(USERNAME_KEY, null);
        userDetails.put(USERNAME_KEY, username);
        String dob = sharedPrefs.getString(DOB_KEY, null);
        userDetails.put(DOB_KEY, dob);
    
        return userDetails; //return the map
    }
    

    In this case I would suggest you to use a class instead of a Map. These values are related to each other.