An EditTextPreference with Minimum character requirement - android

I have an EditTextPreference that I user to allow use to set a passcode to an app. I want to require a 4-digit passcode. I set the maxLength = "4" in the xml file. Now I have the problem to not allow submit unless the entered passcode is 4 digits long.
Here is what I have:
<EditTextPreference
android:defaultValue=""
android:dependency="EnablePasscode"
android:dialogMessage="Add a numeric passcode to provide access to enter the app. The passcode must be 4 digits."
android:dialogTitle="Set Passcode"
android:inputType="number"
android:key="passcode"
android:maxLength="4"
android:password="true"
android:title="Set Passcode" />
Now in Java:
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
if (key.equals("passcode")) {
EditTextPreference setPasscode = (EditTextPreference) findPreference("passcode");
if (setPasscode.getText().toString().length() == 4) {
// return true
}
}
}
Where it says return true comment out, I am not sure how to handle this; I know I don't do a return; what I want it it to submit the Dialog Box if length is 4, otherwise if it is 0, 1, 2, or 3, throw a toast. Where and how can I do that?
UPDATE: TO validate this preference, I need control of the OK button which I do not have; this may be a workaround.

private EditTextPreference preference;
this.preference = ((EditTextPreference) getPreferenceScreen() //put this in the onCreate
.findPreference("passcode"));
if (key.equals("passcode")) {
EditTextPreference setPasscode = (EditTextPreference) findPreference("passcode");
if (sharedPreferences.getString("passcode","0").length() != 4) {
Toast.makeText(this, "Should be 4 digits", Toast.LENGTH_LONG).show();
this.preference.setText(null);
return;
}else{
Toast.makeText(this, "Success!", Toast.LENGTH_LONG).show();
}
}
something like this should help you. Do keep in mind that getPreferenceScreen is deprecated, it is recommended to use PreferenceFragment. I am assuming that PreferenceActivity is being extended here.

Related

Validation for save button

I've difficulty in creating a validation before saving it to sqlite, below is the code:
public void save(View v){
String weight = weightinputid.getText().toString();
String bmi = BMIfinal.getText().toString();
String status = BMIStatus.getText().toString();
long id = data.insertData(weight, bmi, status);
if(id<0){
message.mess(this, "Error");
}
else{
message.mess(this, "BMI has been saved");
}
}
How do I create a validation if all the textfields are empty? my problem right now, even if i pressed the save button, the empty textfields was saved inside the database
You can just try this, to check if value is not entered in the EditText.
if (weight .equals(""))
{
Toast.makeText(getApplicationContext(),"Please enter Value1", Toast.LENGTH_LONG).show();
}
if (bmi.equals(""))
{
Toast.makeText(getApplicationContext(),"Please enter Value2", Toast.LENGTH_LONG).show();
}
if (status.equals(""))
{
Toast.makeText(getApplicationContext(),"Please enter Value3", Toast.LENGTH_LONG).show();
}
Alternatively, you can use .matches("") instead of .equals("")
UPDATE
As #Rajesh mentioned in his comments, you can also use
TextUtils.isEmpty(weightinputid.getText())
to achieve the same functionality.
You can definitely do #Lal suggestion but in case the N fields are empty it's going to show the N toasts, and that's not very useful:
I'll suggest to do the following one of the following options:
a) Implement MaterialEditText:
Check the details here:
https://github.com/rengwuxian/MaterialEditText
<com.rengwuxian.materialedittext.MaterialEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Min Characters"
app:met_minCharacters="1" />
b) Use a TextWatcher and enable the SaveButton only after you have your required fields with values:
http://developer.android.com/reference/android/text/TextWatcher.html
You can see how to it with the following question:
Disable Button when Edit Text Fields empty

Android Edittext: when contains misspelling word (with red underline over it), do not allow to submit

I am recently making my first Android App and it has a Edittext area which plans to only allow users to input correctly spelled words. Basically I have already learned how to use layout properties such as Android:inputType to detect any misspelled words. Any misspelled words should be marked with a red underline. But I cannot find a way to prevent users from inputting misspelled words.
The ideal situation is: if a user has input any misspelled words and clicks the submit button, a prompt message (for example a Toast message) would appear to inform the user to modify misspelled words before they can really submit.
Follow steps from this link to create a spelling checker.
http://www.tutorialspoint.com/android/android_spelling_checker.htm
Then modify the sample code above to meet your requirement:
E.g. When (arg0.length == 0), that means there is no suggestion (no spelling mistake), you can create validation from here.
However, it could be a word that is not written in English. So you would need a language detection:
https://code.google.com/p/language-detection/
(From: How to detect language of user entered text?)
What you have to do to achieve this is implement spellchecksession listener.
May be you can use spell check listener along with a text watcher.
SpellCheckListener
You can use this method to validate word(Spell check).
public boolean CheckForWord(String Word){
try {
BufferedReader in = new BufferedReader(new FileReader("/usr/share/dict/american-english"));
String str;
while ((str = in.readLine()) != null) {
if ( str.indexOf( Word) != -1 ) {
return true;
}
}
in.close();
}
catch (IOException e) {
}
return false;
}
And on SUBMIT Button Click
btnSUBMIT.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String EdittextValue = edittext.getText().toString();
if(CheckForWord(EdittextValue)){
Toast.makeText(getActivity(),
"Correct Word " + EdittextValue ,
Toast.LENGTH_LONG).show();
// Do something here.
}
else{
Toast.makeText(getActivity(),
"Wrong Word " + EdittextValue ,
Toast.LENGTH_LONG).show();
}
}
});

where to put checking edittext syntax?

i need a favor.. i'm confused to put these codes to check whether the edittext is empty or not:
String input = editText.getText().toString();
if(input == null || input.trim().equals("")){
Toast.makeText(context, "Sorry you did't type anything"), Toast.LENGTH_SHORT).show();
}
where must i write these codes? is it between these codes?
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menuawal);
...
...
...
JmlAhliWarisAnakLK = (EditText) findViewById(R.id.JmlAhliWarisAnakLK);
JmlAhliWarisAnakPR = (EditText)findViewById(R.id.JmlAhliWarisAnakPR);
or in this function after double sisa=0;??
public void cc() {
int JmlWarisAnakPR = Integer.parseInt(JmlAhliWarisAnakPR.getText().toString());
int JmlWarisAnakLK = Integer.parseInt(JmlAhliWarisAnakLK.getText().toString());
int JmlHarta = Integer.parseInt(JmlHartaPeninggalan.getText().toString());
double HasilSuami = 0;
double HasilIstri = 0;
double HasilAnakLK = 0;
double HasilAnakPR = 0;
double sisa = 0;
}
please correct me if i'm wrong.. :D
you are on the right track
After you set the layout using setContentView you need to add your EditText's which you are doing fine as follows.
JmlAhliWarisAnakLK = (EditText)findViewById(R.id.JmlAhliWarisAnakLK);
JmlAhliWarisAnakPR = (EditText)findViewById(R.id.JmlAhliWarisAnakPR);
You then need to store the value you get from the EditText's in some variable,
int JmlWarisAnakPR = Integer.parseInt(JmlAhliWarisAnakPR.getText().toString());
....
....
After you have stored your values you can then call some method that validates your input on click of a button(if you have):
public void validateinput()
{
if(input == null || input.trim().equals(""))
{
Toast.makeText(context, "Sorry you did't type anything"), Toast.LENGTH_SHORT).show();
}
}
According to me, you should put the check on some event, like if its login screen, then on click of submit button. or other wise on focus change it main instantly provide user with the toast that he left the field empty. or if other case, please provide more information for your query. thanks.
That depends on when you want to validate the editText..You propably have some button which "submits" the EditText so call this code in after onClick event gets fired on the button..
Put the input validation code when you have to navigate away from the current activity, either to go to another activity or to save the input details. That's the least annoying place to shove an error message onto the user.
Another approach is to validate when the focus leaves the EditText. But in this case the error notification should be more subtle (and therefore less annoying) like changing the EditText's background to lightred.
Ur questions does not seem to be clear. Are u asking where do u need to put the validation for empty edittext? If this is ur question then the general case would be to validate during any events such as BUTTON CLICK. Set the onClickListener for ur button and inside ur onclick perform the validation.
String input = editText.getText().toString();
if(input == null || input.trim().equals("")){
Toast.makeText(context, "Sorry you did't type anything"), Toast.LENGTH_SHORT).show();
}
Your above code is pretty much correct. You Must need to add above code whenever you want to take input from these edittext, Or whenever you want to save these value. make a function which will return true if edit text is empty so u can ask user to enter values
public boolean isETEmpty(){
String input = editText.getText().toString();
if(input == null || input.trim().equals("")){
Toast.makeText(context, "Sorry you did't type anything"), Toast.LENGTH_SHORT).show();
return true;
}
return false; // if not empty
}
call this function Whenever u want to use values from ET, if this function return true, you must let user enter values. Such as on Button Click to save etc

How to setOnClickListener() to OK button of an EditTextPreference Dialog? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
how to call the ok button in the EditTextPreference
I want to validate the Inputs (enter 6 digits) of an EditTextPreference dialog box.
This is how my (relevant) preferences.xml snippet looks like :
<!--EditTextPreference-->
<com.app.preferences.UpdatePincodePreference
android:key="PIN_CODE_PREFERENCE"
android:title="#string/pincode_preference_title"
android:summary="#string/pincode_preference_summary"
android:dialogTitle="#string/pincode_preference_dialog_title"
android:dialogMessage="#string/pincode_preference_dialog_message"
android:inputType="number"
/>
How do I test that the user has not entered less or more than 6 digits in the EditText of the preference dialog?
Basically I need to set an onClickListener() on the OK button, but how to I get a hold of the OK button which I did not define. Its the default view of an EditTextPreference, and so is the Cancel button.
The question is exactly the same as "how to call the ok button in the EditTextPreference" but the links provided in the accepted solution are broken now.
The author of the solution has moved his project from Google Code to GitHub. You can find the new project at https://github.com/Knickedi/android-toolbox and the links to the two files he was referring to validating DialogPreference and validating EditTextPreference
This could be achieved using setOnPreferenceChangeListener()
public UpdatePasswordPreference(Context context, AttributeSet attrs) {
this.setOnPreferenceChangeListener(new OnPreferenceChangeListener()
{
#Override
public boolean onPreferenceChange(Preference preference, Object newValue)
{
MobicopLogger.d("Preference input changed");
try
{
if(newValue.toString().length() != 6)
return false;
else
return true;
}
catch(Exception e)
{
return false;
}
}
});
}
create a custom layout and apply it to the preference by the following override method :
#Override
protected void onPrepareDialogBuilder(AlertDialog.Builder builder) {
super.onPrepareDialogBuilder(builder); //To change body of overridden methods use File | Settings | File Templates.
builder.setView(LayoutInflater.from(ctx).inflate(R.layout.custome_preference_layout,null));
}

Comparison involving preferences failing after first time

Quite new to coding for android but this issue has me tearing my hair out because it seems to make no sense at all...
I have an activity with four form elements in the layout: a CheckBox, two EditTexts and a Button.
When the user presses the button, it saves the content of the EditTexts as two preference values.
When the user presses the checkbox, it does the following:
If the checkbox is checked, load the preferences and store them into two variables.
Check if either of those variables contain empty strings after trimming them.
If so, show an error message, otherwise show a success message.
Essentially, the two text fields are used to set a pair of preferences which must not be empty when the checkbox is clicked.
It seems to work fine if I click the checkbox before pressing the button - error message or success message shown as appropriate.
If I press the save button and then click the checkbox, it always shows the success message regardless of the preferences.
Code follows (trimmed from the program as a whole)...
layout.xml
<CheckBox android:id="#+id/cboxActive" android:text="Click me!" android:onClick="toggleActive" android:layout_width="wrap_content" android:layout_height="wrap_content" />
<EditText android:id="#+id/editFrom" android:layout_width="fill_parent" android:layout_height="wrap_content" android:inputType="phone"><requestFocus /></EditText>
<EditText android:id="#+id/editTo" android:layout_width="fill_parent" android:layout_height="wrap_content" android:inputType="phone"></EditText>
<Button android:id="#+id/btnSave" android:onClick="savePrefs" android:text="Save" android:layout_width="120dp" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" />
</LinearLayout>
main class:
public class AutoMessengerActivity extends Activity
{
SharedPreferences settings;
CheckBox cboxActive;
EditText editFrom, editTo;
boolean active;
String from, to;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editFrom = (EditText) findViewById(R.id.editFrom);
editTo = (EditText) findViewById(R.id.editTo);
showPrefsInUI();
}
private void loadPrefs()
{
//Load preferences
settings = getPreferences(MODE_PRIVATE);
from = settings.getString("from", "");
to = settings.getString("to", "");
}
private void showPrefsInUI()
{
loadPrefs();
//Set UI elements to preference values
editFrom.setText(from);
editTo.setText(to);
}
public void savePrefs(View view)
{
SharedPreferences.Editor editor = settings.edit();
editor.putString("from", editFrom.getText().toString());
editor.putString("to", editTo.getText().toString());
editor.commit();
Toast.makeText(this, "Prefs saved!", Toast.LENGTH_SHORT).show();
}
public void toggleActive(View view)
{
if (cboxActive.isChecked())
{
loadPrefs();
//This toast is for debugging
//It shows the correct data in all circumstances...
Toast.makeText(this, "F: " + from + " T: " + to, Toast.LENGTH_SHORT).show();
//This is the part that seems to fail if you save then click checkbox
if (from.trim() == "" || to.trim() == "")
{
Toast.makeText(this, "Error - Prefs not saved", Toast.LENGTH_LONG).show();
cboxActive.setChecked(false);
}
else
{
Toast.makeText(this, "Success!", Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(this, "Unchecked!", Toast.LENGTH_SHORT).show();
}
}
}
Hopefully that code gives an idea of the problem and allows it to be replicated...
Oh god, how silly of me - Urban and jcxavier hit the nail on the head... I forgot about that damn annoying quirk of Java! Changed the line to
from.trim().equals("") || to.trim().equals("")
And it works fine!
For what it's worth, that HAD actually crossed my mind briefly, but it was 2am when I tried equals and I got confused about requiring an Object as the parameter and ended up specifying null rather than "" - which didn't work...

Categories

Resources