Search code examples
androidvariablesmemorydoublestore

How to store double using SharedPreferences?


I am having trouble storing a double in the phone's memory. What are my other options if this isn't possible. Basically what the code is aiming to do using sharedpreferences is take the stored value of "Alcohol" spending and then add whatever the input is in the editText to it and then store that new value for the next time. Running total of spending on alcohol

**Can someone please help with this issue and be detailed where x y & z should go in the project.

The user selects from a spinner, which works.

public void addInput(){

    double dblCostInput = Double.valueOf(inputBox.getText().toString());
    String strCategories= spinnerCategories.getSelectedItem().toString();

    if(strCategories.equals("Alcohol"))
    {

        alcoholSpend = alcoholSpend + dblCostInput;
        inputBox.setText("");
        nextInput();
        inputBox.setText("Your Spending on"+strCategories+" is: " +d.format(alcoholSpend));

    }

Solution

  • getSharedPreferences("MY_PREFERENCE", MODE_PRIVATE).edit().putString("double", "0.28").commit();
    

    and then to retrieve the double, simply use Double.parseDouble:

    Double.parseDouble(getSharedPreferences("MY_PREFERENCE", MODE_PRIVATE).getString("double", "0.28"));