简体   繁体   中英

How to set a default value to SharedPreferences programmatically?

I am using SharedPreferences to keep the information about user's weight, which I need in my application. The problem is, how to set a default value (eg. 75 kg) automatically after installation? I know how to do it via .xml, but how to do this programmatically?

My code:

public class SettingsDialogFragment extends DialogFragment{

public static final String PREFS_NAME = "settings";
public Dialog onCreateDialog(Bundle savedInstanceState) {


builder.setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {

                Data.weight = weight;
                SharedPreferences prefs = getActivity().getSharedPreferences(PREFS_NAME, 0);
                Editor editor = prefs.edit();
                editor.putInt("key_weight", weight);
                editor.commit();
                Data.ifMale = ifMale;
                checkedRadio = rg.getCheckedRadioButtonId();
                System.out.println("numer radio" +checkedRadio);
            }
            });
return builder.create();
    }
}

Try this way, please.

        SharedPreferences prefs = getActivity().getSharedPreferences(
                PREFS_NAME, 0);
        if (prefs.getInt("key_weight", null) == null) {
            Editor editor = prefs.edit();
            editor.putInt("key_weight", 75);
            editor.commit();
        }

For first time use this, or else use your code only(means without if condition).

getInt takes a default value.

prefs.getInt("key_weight", 75)

Or in a more mainstream style....

public class AppPreferences {

    private SharedPreferences mPreferences;

    Public AppPreferences(SharedPreferences preferences)
    {
         this.mPreferences = preferences;
    }

    private static final String KEY_WEIGHT_KEY = "key_weight";
    private static final int DEFAULT_KEY_WEIGHT = 75;

    public static  int getKeyWeight()
    {
      return mPreferences.getInt(KEY_WEIGHT_KEY,DEFAULT_KEY_WEIGHT);

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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