Checking an editText that is on the Shared prefs settings screen - android

I want to know if there is a way to check what someone is entering on the shared prefs/settings screen for validation. The user touches the Ip enter options, an edittext dialog pops up and I am trying to restrict what they can enter to something like a standard IP address(ie. 0-255.0-255.0-255.0-255) I have looked in numerous online forums and saw examples of different things with REGEX and patterns and this is what I have so far, but absolutely nothing is happening....Can anyone help me out? I would greatly appreciate it!
public class PrefsActivity extends PreferenceActivity implements
OnSharedPreferenceChangeListener
{
private EditTextPreference ipTextBox;
private String whatWasTyped;
private String previousText = "";
private Editor myEditor;
final Pattern IP_ADDRESS = Pattern
.compile("^((1\\d{2}|2[0-4]\\d|25[0-5]|\\d?\\d)\\.){3}(?:1\\d{2}|2[0-4]\\d|25[0-5]|\\d?\\d)$");
private String IP_FROM_PREFS = "ipAddressPref";
SharedPreferences prefs;
#Override
/**
* The onCreate method handles thing when starting this activity,
* mainly display the activity_settings.xml.
*/
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// pattern for IP address validation
addPreferencesFromResource(R.layout.activity_settings);
// prefs.registerOnSharedPreferenceChangeListener(this);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
// Get a reference to the preferences
ipTextBox = (EditTextPreference) getPreferenceScreen().findPreference(
IP_FROM_PREFS);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key)
{
// check prefs value for IP.
if (key.equals(IP_FROM_PREFS))
{
whatWasTyped = prefs.getString(IP_FROM_PREFS, "");
CharSequence s = whatWasTyped;
if (IP_ADDRESS.matcher(s).matches())
{
previousText = s.toString();
myEditor = prefs.edit();
myEditor.putString(IP_FROM_PREFS, previousText);
myEditor.commit();
} else
{
//if the format does not match, put up an error message
// or something.
}
}
}
#Override
protected void onResume()
{
super.onResume();
// Setup the initial values
// mCheckBoxPreference.setSummary(sharedPreferences.getBoolean(key,
// false) ? "Disable this setting" : "Enable this setting");
// mListPreference.setSummary("Current value is " +
// sharedPreferences.getValue(key, ""));
// Set up a listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
previousText = prefs.getString(IP_FROM_PREFS, "");
}
#Override
protected void onPause()
{
super.onPause();
// Unregister the listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);
}
}
Since this is something created on the shared prefs screen, there are no button id, etc...

Just writing
whatWasTyped.replace(s, previousText);
will not assign the the previousText to the SharedPreference you need to assign it back to the shared preference and commit.

Related

SharedPreferences not working with TextView

I have a page in my application where the user can enter a product name and it's calorie count, which it then removes from a daily calorie count which comes from another class. This works perfectly I wanted to make it so that it doesn't reset to the original value each time the page is opened (unless its a fresh install / manual reset via a button).
I came across SharedPreferences and tried to implement this, but it always comes up with the default value in my onResume method and I am not too sure why and need some assistance to figure out what I am doing wrong and how to fix it, as I will need to use this in several other classes also.
My Class:
public class CalorieTracker extends AppCompatActivity {
protected String age, calorieCount;
protected EditText itemName, kCal;
protected TextView remainingCalories;
protected Button submitBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calorie_tracker);
getSupportActionBar().setDisplayShowHomeEnabled(true);
Bundle extras = getIntent().getExtras();
age = extras.getString("age");
calorieCount = extras.getString("calories");
System.out.println(age + ":" + calorieCount);
itemName = findViewById(R.id.productNameCalorieTracker);
kCal = findViewById(R.id.calorie_kcal);
submitBtn = findViewById(R.id.submit_calorie);
remainingCalories = findViewById(R.id.remainingCalorieCount);
remainingCalories.setText(calorieCount);
submitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int currentCount = Integer.parseInt(remainingCalories.getText().toString());
int enteredAmount = Integer.parseInt(kCal.getText().toString());
calorieCount = String.valueOf(currentCount - enteredAmount);
remainingCalories.setText(calorieCount);
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("sessionCalories",remainingCalories.getText().toString());
editor.commit();
}
});
}
#Override
protected void onResume() {
super.onResume();
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
remainingCalories.setText(mPrefs.getString("sessionCalories",""));
}
}
http://prntscr.com/me99dp
Image of what it looks like when I boot the application, even though the initial calorieCount value should be 2100 which I get from the previous page using the Bundle extras.
If I change the
line remainingCalories.setText(mPrefs.getString("sessionCalories","")); in my onResume method, to :
remainingCalories.setText(mPrefs.getString("sessionCalories","3")); then it shows 3 initially.
Make sure that your data is updated in shared preference correctly. In Activity life cycle after onviewCreated only onResume called .
so if your current activity will go to foreground or rotate then only onResume will call again.
so solution ,in button click after set the value and get value from sharedpreference and display like this
submitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// first time save data
setvalueFromSharedpreference()
}
});
public setvalueFromSharedpreference()
{
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
remainingCalories.setText(mPrefs.getString("sessionCalories",""));
}
when I boot the application, even though the initial calorieCount
value should be 2100 which I get from the previous page using the
Bundle extras.
If I change the line
remainingCalories.setText(mPrefs.getString("sessionCalories","")); in
my onResume method, to :
remainingCalories.setText(mPrefs.getString("sessionCalories","3"));
then it shows 3 initially.
Reason editText remainingCalories always have default (sharedpreference value) is because onResume method is called after onCreate in activity's lifecycle. Thats why, Bundle extras value is being overwritten by sharedpreference value.
You can achieve this in onCreate method by checking if Intent extras has value. If yes, then set that value otherwise set the sharedPrefrence's value as follows
#Override
protected void onCreate(Bundle savedInstanceState) {
...
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
calorieCount = mPrefs.getString("sessionCalories","");
Bundle extras = getIntent().getExtras();
age = extras.getString("age");
if(!calorieCount.isEmpty)
remainingCalories.setText(calorieCount);
else
{
calorieCount = extras.getString("calories");
}
System.out.println(age + ":" + calorieCount);
itemName = findViewById(R.id.productNameCalorieTracker);
kCal = findViewById(R.id.calorie_kcal);
submitBtn = findViewById(R.id.submit_calorie);
remainingCalories = findViewById(R.id.remainingCalorieCount);
remainingCalories.setText(calorieCount);
}
And remove the sharedPreference setting from onResume.
Hope it helps cheers:)

Using SharedPreference to save user details

I understand that the best way to save values is to use SharedPreferences e.g.
SharedPreferences Savesettings = getSharedPreferences("settingFile", MODE_PRIVATE);
SharedPreferences.Editor example = Savesettings.edit();
example.putString("Name", name)
.putInt("Age", age)
.putInt("Score", score)
example.apply();
But what if I want my program to remember a button being disabled or enabled after the user closes and opens the program? i have tried a RegisterOnChangePreferanceListener however i have no luck e.g.
SharedPreferences Preferences= PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.OnSharedPreferenceChangeListener Example =
new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences preferance, String key) {
Name = name;//only an example not the main focus
Age = age;
Score = score;
enableBTN = false; //disables button
Name.setEnabled(false); //disables the edit text from further editing
}
};
Preferences.registerOnSharedPreferenceChangeListener(Example);
Is there a way to do this, both methods do not seem to be working for me.
You need to save it from within the button's OnClickListener. That way, everytime the button is clicked, you are guaranteed that the button's state is saved. button is a reference to a Button view object
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle bundle) {
Button button = (Button)findViewById("this_button_view_id");
EditText editText = (EditText)findViewById("this_edit_text_id");
SharedPreferences Savesettings = getSharedPreferences("settingFile", MODE_PRIVATE);
// If the Savesettings shared preferences above contains the "isButtonDisabled" key
// It means the user clicked and disabled the button before
// So we use that state instead
// If it does does not contain that key
// We set it to true so that the button is not disabled
// Same for the edit text
button.setEnabled(Savesettings.contains("isButtonDisabled") ? Savesettings.getBoolean("isButtonDisabled") : true);
editText.setEnabled(Savesettings.contains("isEditTextDisabled") ? Savesettings.getBoolean("isEditTextDisabled") : true);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// disable the edit text
editText.setEnabled(false);
// disable the button
button.setEnabled(false);
SharedPreferences.Editor example = Savesettings.edit();
// Save the button state to the shared preferences retrieved above
example.putBoolean("isButtonDisabled", true);
// Save the edit text state to the shared preferences retrieved above
example.putBoolean("isEditTextDisabled", true);
example.apply();
}
});
}
}

Android PreferenceFragment, best practice for persistent UI update?

I am implementing the Settings for my android app through the PreferenceFragment.
My android:summary for the different Preferences should display the current value at all times therefore I have read through severals posts and the official documentation.
Although I got it working technically my solution seems kind of hacky and I am now searching for best practice since I found no good source on how it is meant to be properly implemented.
For example I implemented onSharedPreferenceChanged to listen for changes and to update the UI, but after every restart of the PreferenceFragment, the initial android:summary is shown again. To solve this I added this to the onCreate
// display current value in the UI
EditTextPreference editText = (EditTextPreference) findPreference("serverAddress");
editText.setSummary(editText.getText());
Is this is how it is supposed to be done or am I misunderstanding something ?
Full Code:
public class SettingsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {
public static final String KEY_PREF_SERVER_ADDRESS = "serverAddress";
public static final String KEY_PREF_GENDER = "gender";
public SettingsFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle saveInstanceState) {
super.onCreate(saveInstanceState);
//Load the preferences from the XML file
addPreferencesFromResource(R.xml.preferences);
// display current value in the UI
EditTextPreference editText = (EditTextPreference) findPreference("serverAddress");
editText.setSummary(editText.getText());
}
// Listen for settings changes and update the UI
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals(KEY_PREF_SERVER_ADDRESS)) {
Preference serverAddressPref = findPreference(key);
//Set UI to display updated summary
serverAddressPref.setSummary(sharedPreferences.getString(key, ""));
}
if (key.equals(KEY_PREF_GENDER)) {
Preference serverAddressPref = findPreference(key);
//Set UI to display updated summary
serverAddressPref.setSummary(sharedPreferences.getString(key, ""));
}
}
#Override
public void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);
}
}

How to change the Summary of a PreferenceScreen with an Intent on Java

I am programming an application that uses SharedPreferences, one of them was a date, so I end up creating an Preference with and Intent so this acts like a button to another Activity on wich the user can select a date and time from pickers and stored the value as a String on my SharedPreferences, so far so good.
However, I want my "Preference button" to load that String into it's Summary property implementing the OnSharedPreferenceChangeListener, I have been able to do it for my EditTextPreference objects, here's my code so far:
public class SettingsActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener {
// DECLARATION OF USED OBJECTS
EditTextPreference userId;
EditTextPreference userName;
EditTextPreference hospital;
Preference dateTime;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.activity_preferences);
//LOAD SHARED PREFERENCES
SharedPreferences getData = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
//ASSING EACH DECLARED CONTROL A PREFERENCE
userId = (EditTextPreference) getPreferenceScreen().findPreference("pref_userId");
userName = (EditTextPreference) getPreferenceScreen().findPreference("pref_username");
hospital = (EditTextPreference) getPreferenceScreen().findPreference("pref_hospital");
dateTime = (Preference) getPreferenceScreen().findPreference("pref_dateTime");
}
#Override
protected void onPause() {
// STOPS MY LISTENER WHEN A KEY CHANGES
super.onPause();
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
#Override
// SETS UP MY LISTENER WHEN A KEY CHANGES
protected void onResume() {
super.onResume();
// LOADS SHARED PREFERENCES INTO THE PREFERENCES SUMMARIES
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
userId.setSummary(sharedPreferences.getString("pref_userId", ""));
userName.setSummary(sharedPreferences.getString("pref_username", ""));
hospital.setSummary(sharedPreferences.getString("pref_hospital", ""));
dateTime.setSummary(sharedPreferences.getString("pref_dateTime", ""));
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
//REFRESHES THE SUMMARIES WHEN A PREFERNECE IS CHANGED
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals("pref_userId")) {
userId.setSummary(sharedPreferences.getString(key, ""));
}else
if (key.equals("pref_username")) {
userName.setSummary(sharedPreferences.getString(key, ""));
}else
if (key.equals("pref_hospital")) {
hospital.setSummary(sharedPreferences.getString(key, ""));
}else
if (key.equals("pref_dateTime")) {
dateTime.setSummary(sharedPreferences.getString(key, ""));
}
}
This code does not generate any errors on Eclipse so it will allow me to test it but I get the app will just stop unexpectedly when I try to go into my PreferenceActivity
Error is on the OnResume and/or onSharedPreferenceChanged methods, any ideas on a workaround so I can display my saved SharedPreference on this Preference Summary by using this implement of PreferenceActivity or should be using another approch (Keeping in mind I have a min of API8). Thanks guys any help will be really appreaciated.

OnSharedPreferenceChangeListener not registering change in preference

I'm working on listpreferences and I have implemented the OnSharedPreferenceChangeListener to change the text on a textview based on which item is selected on the listpreference. However it doesn't register any changes and I have run out of ideas so any help would be appreciated. Thanks
public class pref extends PreferenceActivity implements OnSharedPreferenceChangeListener {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefs);
setContentView(R.layout.main);
TextView text = (TextView) findViewById(R.id.textView1);
String keys = null;
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
pref.registerOnSharedPreferenceChangeListener(this);
keys = pref.getString("listPref1", "");
if (keys == "ON")
{
text.setText("ON");
}
else if (keys == "OFF")
{
text.setText("OFF");
}
else{
text.setText("Choose One");
}
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
//What code to I put in here to have the listener register the change
}
}
Your code looks good for registering to hear preference changes, you need to put some code in your onSharedPreferenceChanged method to process the preferences as they are changed. Remember that you will get called back when any preference changes, so you need to do some filtering in the method to make sure it's what you're interested in.
Could be something as simple as:
if(key.equals("listPref1"))
text.setText("ON"); // Need to make text a class variable
Thank you all for your help, I've sorted most of it out now here is the code
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(this);
TextView text = (TextView) findViewById(R.id.textView1);
if (prefs.getString("listPref1", "").equals("OFF")) {
text.setText("goodbye");
} else if (prefs.getString("listPref1", "").equals("ON")) {
text.setText("hello");
}
prefs.registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
TextView text = (TextView) findViewById(R.id.textView1);
if (prefs.getString("listPref1", "").equals("OFF")) {
text.setText("goodbye");
} else if (prefs.getString("listPref1", "").equals("ON")) {
text.setText("hello");
}
}
}
As you can see I have to repeat the if/else statement, if I put it only in the listener nothing gets until a change is made and for if it's only outside the listener it only gets read when the app is first run and changes are not registered.
Isn't there a code to get the listener to notify a change has been made and the code gets re-run?
Your code looks like it should work: you can try logging out to ensure its doing what it should. Move all the conditional code into the listener.
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
android.util.Log.v("PREFERENCE CHANGE", "[" + key + "]");
if ("listPref1".equals(key)) {
String keys = pref.getString("listPref1", "");
if (keys == "ON") {
text.setText("ON");
} else if (keys == "OFF") {
text.setText("OFF");
} else {
text.setText("Choose One");
}
}
}
You don't have any code to actually update your SharedPreferences. The listener will only be triggered when your pref object is edited. Example...
pref.edit().putString("listPref1", "ONE").commit();

Categories

Resources