Set default values for the SharedPreferences for the whole aplication

吃可爱长大的小学妹 提交于 2020-01-07 09:56:22

问题


I have the application with coding key, that should be visible from all parts of the application. It has to have a default value and an ability to be changed from one of the activities. How can I set this default value?


回答1:


To save default value you have Two options . 1. SharedPreference 2. Database.

Try with SharedPreference

Create Helper class.

public class SharedPreferencesHelper {
    private static final String TAG = "SharedPreferencesHelper";
    Context context;
    SharedPreferences sharedPreferences;
    public SharedPreferencesHelper(Context context) {
        this.context = context;
        sharedPreferences = context.getSharedPreferences("loginDetails",Context.MODE_PRIVATE);
    }

    /**
     * To set login details
     * @param userName : username to set
     * @param password : password to set
     */
    public void setLoginDetails(String userName, String password) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("userName",userName);
        editor.putString("password",password);
        editor.commit();
    }

    /**
     * To check and get login details
     * @param userName : name to validate
     * @param password : password to validate
     * @return true : if valid user
     *         false : if valid password
     */
    public boolean isValidUser(String userName, String password) {
        // to get username
        Log.d(TAG, "username = " + sharedPreferences.getString("userName", null));
        Log.d(TAG, "password = " + sharedPreferences.getString("password", null));

        if(sharedPreferences.getString("userName",null).equals(userName) && sharedPreferences.getString("password",null).equals(password))
            return true;
        else
            return false;
    }

}

To access from any where in application (activity / fragment)

SharedPreferencesHelper sharedPreferencesHelper = new SharedPreferencesHelper(this);
sharedPreferencesHelper.setLoginDetails("admin","admin");
sharedPreferencesHelper.isValidUser("admin","admin");

This may help you.




回答2:


Let's say this is your shared preferences:

SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());

you can set the default value like this:

String username = sharedPreferences.getString("USER_NAME", "DEFAULT_VALUE");


来源:https://stackoverflow.com/questions/34762845/set-default-values-for-the-sharedpreferences-for-the-whole-aplication

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!