Search code examples
javaandroidsharedpreferencesandroid-sharedpreferences

Android Sharedpreferences passing value of variable


How can I pass the value of the variable to other class? I'm using SharedPreference and I don't know if im passing the right value to other class. Here's my statement.

if (arr != null) {
    int sum = 0;
    for(int i = 0;i<arr.length();i++) {
        listdata.add(arr.get(i).toString());
        String money = arr.getJSONObject(i).getString("amount");
        sum += Integer.parseInt(money);
    }

    SharedPreferences sharedPref1 = getActivity().getSharedPreferences(String.valueOf(sum), Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPref1.edit();
    editor.putInt(String.valueOf(sum), sum);
    editor.commit();
}

Here is how I get the SharedPreference in other class. Is this right?

 SharedPreferences sharedpref1 = getContext().getSharedPreferences(String.valueOf(""), MODE_PRIVATE);
 int budgeted = sharedpref1.getInt(String.valueOf(""), Integer.parseInt(""));

Solution

  • SharedPreference is basically a key-value pair stored locally in the application package storage. So you might pick a tag for your SharedPreference in your application. Lets say, your SharedPreference tag is MySharedPreference.

    So in case of storing a value in your SharedPreference you need to do this.

    SharedPreferences sharedPref1 = getActivity().getSharedPreferences("MySharedPreference", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPref1.edit();
    editor.putInt("TotalSum", sum);  // Pick a key here. 
    editor.commit();
    

    And when you're retrieving the preference value from some other class, just do this.

    SharedPreferences sharedpref1 = getContext().getSharedPreferences("MySharedPreference", MODE_PRIVATE);
    int budgeted = sharedpref1.getInt("TotalSum", 0); // Use the same key you used before to retrieve the data.