I'm trying to use preference activity in android, I set everything up, but I have problems getting user preferences. To be specific, these are two options for edittext, the length and the length of the year, which I want to get as int values, so I can use them when calculating in another activity.
Every example I find is different and I cannot find a clear explanation. I will publish the class and method that I use below, I know the code that is not correct, but I feel that I have come across it all the time, and I canβt figure it out. In this line, in particular, I do not believe that this is correct: SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); and I really don't understand the effect of preferences in general, they don't seem to work the way I expected. Any advice would really be great! I manipulated the same lines of code several times.
Thank you
The action of my preferences is as follows:
package com.geistware.studentbudgetapp; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.EditTextPreference; import android.preference.PreferenceActivity; import android.preference.PreferenceManager; import android.text.method.DigitsKeyListener; import android.util.Log; public class UserPrefs extends PreferenceActivity { public int termLength = 1; public int yearLength = 1; @Override
and I want to be able to get users termLength and yearLength (as ints) in this method:
public float alterForFrequency(float enteredAmount, String spinnerPosition){ //get user preferences (not working) SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); String termKey = getString(R.string.term_length_set, ""); String yearKey = getString(R.string.year_length_set, ""); int termLength = prefs.getInt(termKey, 1); int yearLength = prefs.getInt(yearKey, 1); Log.v("alterForFrequency", "userprefs: " + termLength + yearLength); //perform calculations for monthly/temly/yearly if(spinnerPosition.equals("Monthly")){ usersAmount = ((enteredAmount / 31)* 7); Log.v("FiscFreq", "revisingAmount=" + usersAmount); } else if(spinnerPosition.equals("Termly")){ usersAmount = (enteredAmount / termLength); Log.v("FiscFreq", "revisingAmount=" + usersAmount); } else if(spinnerPosition.equals("Yearly")){ usersAmount = (enteredAmount / yearLength); } else{ usersAmount = enteredAmount; } currencyRevisedAmount = toCurrency(usersAmount); //drops the unwanted digits return currencyRevisedAmount; }
I actually create an instance of FiscalFrequency to use alterForFrequency in an activity called Keypad, for example:
public class Keypad extends Activity { ..... public float reviseOnSpinnerPos(){ enteredAmount = Float.valueOf(userAmount.getText().toString()); FiscalFrequency ff = new FiscalFrequency(); revisedAmount = ff.alterForFrequency(enteredAmount, spinnerPosition); return revisedAmount; } }