Search code examples
androidsavecurrencysharedpreference

Android save selected Currency in SharedPreference


in my Activity, the user chooses whether to display the currency Canadian or Chinese. I would like to save this choice, I think the best way is to save it in a SharedPreferences. How can I do?

 NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.CANADA);
 nf.setCurrency(Currency.getInstance(Locale.getDefault()));

 NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.CHINA);
 nf.setCurrency(Currency.getInstance(Locale.getDefault()));

Solution

  • To save:

    SharedPreferences sharedPrefs = getSharedPreferences("currency", MODE_PRIVATE);
    sharedPrefs.edit().putString("code", nf.getCurrency().getCurrencyCode()).commit();      
    

    Then, to restore it:

    SharedPreferences sharedPrefs = context.getSharedPreferences("currency", MODE_PRIVATE);
    nf.setCurrency(sharedPrefs.getString("code", defaultCurrency)); 
    

    defaultCurrency should be the default value. For example:

    String defaultCurrency = Currency.getInstance(Locale.getDefault()).getCurrencyCode();