Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any simple way to require an EditTextPreference value to not be blank in Android?

I have a number of EditTextPreference which must be a number 0-9. I can prevent other characters but not backspace. Backspace + Okay = an empty value. An empty value means when the it is retrieved and parsed into a number it will crash.

At the moment I check when a preference changes, if it has certain keys and no length, and if so, I re-save with a "0". Is there a simpler built in way to do this? A "require value" property, or at least something more automatic like being able to get the digits of the changed preference? (if digits is "0123456789" then it must not be empty).

So far in the settings activity I have:

public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
    //Prevent EditText from being non number
    String type = this.findPreference(key).getClass().getSimpleName();
    if( type.equals("EditTextPreference")
        //Put key of any allowed to be blank here...
                && prefs.getString(key, "0").length()==0 ){ 
            this.findPreference(key).setSummary("0");

        SharedPreferences.Editor prefedit = prefs.edit();
        prefedit.putString(key, "0");
        prefedit.commit();
    }
    updateSummaries();
}

(Set summary isn't working --^. Being able to check the android:digits="0123456789" property would make it so I wouldn't need to put keys of any that should be blank.)

Or in the main activity I can put all of the numerical prefs into Strings, check the string, set it to 0 if no good, then parse each string. As I use more of them this feels less appealing, not automatic.

String sTT = prefs.getString("mykey", "0");
>> x10
if(sTT.length()==0){ sTT="0"; }
>> x10
tt = Long.parseLong( sTT );
>> x10, different types

(This may still be the best way...?)

like image 353
Ael Avatar asked Nov 13 '22 17:11

Ael


1 Answers

You can apply a TextWatcher to the EditTextPreference's underlying EditText. This allows you to intercept any changes to the text, and modify it in any way you want, by forcing it to contain a default digit (0) for example.

Although, I think it would make more sense overall for you to just cope with an empty input when you parse the data.

like image 144
Graham Borland Avatar answered Dec 01 '22 15:12

Graham Borland