preventing twice run inside android's textwatcher - java

im working with android's TextWatcher for doing this: when user type, save what typed and after saving, change characters inside Edittext. for example, i have a constant text like"hi im happy" , and every thing i type in edittext user sees that this text is writing(this string shows Tandemly while user typing)! but main text that user types, stored in a variable . i use this code inside afterTextChanged:
if(s.toString().charAt(s.length()-1) != 'a'){
//save inside freaktext variable(append)
freaktext=freaktext+s.toString().charAt(s.length()-1);
//change edittext value(what user see's)
txtfreak.setText(s.toString().substring(0, s.length()-1) + "a");
txtfreak.setSelection(txtfreak.getText().length());
}else{
freaktext=freaktext+"a";
}
i this code i say, if typed character is not "a", save it on a variable named "freaktext" and then change edittext value and put "a" character to the end of string inside edittext. but if user types "a" just save it in freaktext.
bu my problem is: when user types a none "a" character, everything works fine and my code save typed character and then modify edittext value, but when edittext value changes whole code runs again and because last time i change it and put an "a" to it, my code's second part (else) runs and again save an "a" to the end of saved string. in fact when i type "q" i see "qa" in my saved string!! i want that just user directly type "a" in the keyboard, "a" saved and in other situations not. i fact my else section only runs when user directly pressed on "a" key on the keyboard.how i can do this? please help me, this code waste my time for 1 day

Outside your function, somewhere:
boolean weChangedIt = false;
Inside afterTextChanged:
if (weChangedIt) {
weChangedIt = false;
} else {
if(s.toString().charAt(s.length()-1) != 'a'){
weChangedIt = true;
freaktext=freaktext+s.toString().charAt(s.length()-1);
txtfreak.setText(s.toString().substring(0, s.length()-1) + "a");
txtfreak.setSelection(txtfreak.getText().length());
}else{
freaktext=freaktext+"a";
}
}

txtfreak.removeTextChangedListener(whateveryourlistenername);
if(s.toString().charAt(s.length()-1) != 'a'){
freaktext=freaktext+s.toString().charAt(s.length()-1);
txtfreak.setText(s.toString().substring(0, s.length()-1) + "a");
txtfreak.setSelection(txtfreak.getText().length());
}else{
freaktext=freaktext+"a";
}
txtfreak.addTextChangedListener(whateveryourlistenername);

Related

How to get the current Letter at cursor position toString in java?

I want to get the current letter in EdiText to String, I tried using some ways but without success, because I'm beginner and still learning.
what I want exactly is to insert special char after every written special char (in onTextChanged event), after get it into String to use (if ...equals ...)
String selected = edittext1.getText().toString().substring(startSelection);
Editable editAble = edittext1.getEditableText();
int start = edittext1.getSelectionStart();
if (selected.equals("(")) {
editAble.insert(start, ")");
}
this code not working.
any suggestions ?

Is there a way to automatically select text in TextView?

Is there a way to automatically select or highlight a predetermined area of text on TextView? For instance, I want a specific line on the TextView to be already pre-selected when I start the activity, instead of having the user select that area of text themselves.
What you're looking for is most likely the setSelection, function.
it works like this:
EditText edText = findViewById(id);
edText.setSelection(start, stop);
The setSelection() function takes 2 arguments start and stop, both are ints, its the index of the character where you want the selection to start and the index of the character where you want the selection to end.
for example setSelection(0,1) will select the first character of the EditText.
If you want to select a specific String in an EditText you could do something like:
EditText edText = findViewById(id);
String lookingFor = "whatever youre looking for";
//You get the index of the first character of the string you're looking for
int start = edText.getText().toString().indexOf(lookingFor);
//You add the string's length to the index so the selection actually selects the
//whole string.
int stop = start+lookingFor.length();
//You -start- selecting from the 1st character and -stop- at the last character
//Of the string you're looking for.
edText.setSelection(start,stop);

How to check for all empty edit text dynamically and show corresponding message in android?

Some times we have a lot of edit text input field and we have to check all input fields and need to show specific message according to input type which is too much irritating to check all one by one and show message.So is there any way to check all the input field dynamically and show messages just by one method ?
Yes this is too much irriating while there is a lot of input fields.Once i have to check 25 input fields for empty and needed to show specific message and this time i have created a way to check all input fields and show messages dynamically by using just one method.I'm sharing my way.
in editText there is an option to set tag to each edittext.So i just set tag to each edittext after type casting of them.like-
etEmail.setTag("email");
if(emptyChecker(new EditText[]{etEmail})){
// do your task
}
and after that on submit button i just called my created method with an array of edittext. The method is below-
/**
* input field empty checker
*
* #param editTexts
* #return
*/
public static boolean emptyChecker(EditText[] editTexts, Activity activity) {
/**
* checking input field for empty or not
*/
int totalLength = 0;
for (int i = 0; i < editTexts.length; i++) {
EditText editText = editTexts[i];
if (editText.getText().toString().trim().equals("")) {
Toast.makeText(activity, editTexts[i].getTag().toString().toLowerCase() + " " + activity.getString(R.string.is_empty), Toast.LENGTH_SHORT).show();
break;
} else {
if (editText.getTag().toString().toLowerCase().equals(activity.getString(R.string.email).toLowerCase())) {
String email = editText.getText().toString().trim();
String emailPattern = "[a-zA-Z0-9._-]+#[a-z]+\\.+[a-z]+";
if (!email.matches(emailPattern)) {
Toast.makeText(activity, activity.getString(R.string.invalid), Toast.LENGTH_SHORT).show();
break;
} else {
totalLength++;
}
} else {
totalLength++;
}
}
}
//true means all okay
//false means at least one is empty
return totalLength == editTexts.length;
}
here i took one array of edittext and after i looped through the array.On each edittext i checked if this is empty or not.if empty then i took the tag of that edittext and append with ** is empty** and showed on a toast.And then if the edittext is not empty then i checked the tag with email.So if it email then i used regex to validate the email and if it is valid then i increment the counter and if not then i break the the loop and showed an toast.And if it is not email type then i just increment the counter.And finally i have returned the boolean value by comparing the counter length with the edittext array length as there's counter is incremented only when the edittext is not empty.So the idea is if all edit texts are not empty then the counter size will be same as edittext array's length.And if any edit text is empty or email is not matches with the regex then i have shown message by getting the tag of edittext and concat with is empty. This will show the message dynamically.
You just need to settag to the edittext and pass it as array to this method and do your task if the return value is true and the all other task will be done in this simple method.

Setting the color of multiple characters of TextView in java

I will do my best to explain my problem, sorry if I am not clear. Basically I want to set the color of individual characters of a text, and then display them in Android App Development Kit. The problem I am having is that I am taking an array of the characters, and don't know how to set the color of them to a certain hexadecimal value.
For instance if the String is "hello". I would want each character to be a different color.
So I would take 'h' and assign it the hexadecimal value of "#000000". And then display it using xml. Is this possible? Here is what I am attempting to do now with my code.
String end = "";
for (int p = 0; p < charzart.size(); p++) {
if (charzart.get(p).equals(" ")) {
}
else{
Spannable colorSpan = new SpannableString(charzart.get(p));
int fake = Integer.parseInt(color.get(p));
colorSpan.setSpan(new ForegroundColorSpan(fake), 0, 1, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
end += colorSpan;
}
}
output.setText(end);
Right now my code doesn't work and I am not sure why. So i am running through charzart which holds my characters. And then attempting to assign the hexadecimal value ( which I have in another array list called color). I check to see if there is a space, if there is I ignore it and move on until i reach a character. From there, I get the character, set it to a spannable. I then get the color, apply it to the spannable, add it to a string and at the end set the TextView to that string.
Basically I want to know how to assign a hexadecimal value to a character, which will then be outputted by XML.

How to ignore null values when reading from a form?

I have the following block of code in my Java program:
Filter.sitesToBeFiltered.add(eid.getSite());
System.out.println("Entity Site added to ArrayList. ");
Filter.applicationsToBeFiltered.add(eid.getApplication());
System.out.println("Entity Application added to ArrayList. ");
Filter.IDsToBeFiltered.add(eid.getEntity());
System.out.println("Entity ID added to ArrayList");
Filter.positionsToBeFilteredX.add(position.getX());
System.out.println("Entity X position added to ArrayList. ");
Filter.positionsToBeFilteredY.add(position.getY());
System.out.println("Entity Y position added to ArrayList. ");
Filter.positionsToBeFilteredZ.add(position.getZ());
System.out.println("Entity Z position added to ArrayList. ");
Currently, it will read the values of a set of JTextFields, and add each value to an associated ArrayList. (The ArrayLists are either ArrayLists of Integers or Doubles). However, it will read their values no matter whether the value is a String, int/ double or null...
I want to add some error checking code, so that it will only add the value to the associated ArrayList if it is of the correct data type. I've tried doing this by surrounding each of the two-line blocks in the code displayed above with an 'if' statement, such as:
if(eid.getSite() != null){
Filter.sitesToBeFiltered.add(eid.getSite());
System.out.println("Entity Site added to ArrayList. ");
}
But if I do this, I get a compile error on the if statement that says "The operator != is undefined for the argument type(s) int, null"... Why is this? What should I use to check that the value of the JTextFields are not equal to null instead?
try with:
if(eid != null && eid.getSite()) {
doSomething();
}
If it is int (primitive type) you will always get 0 if no value is set.
If for 0 nothing is assigned at UI side, then try to ignore zero if (!eid.getSite() == 0) but please make sure that 0 dont have any meaning.
With string you can cast return object to string if it's Object class, and check for not blank
I managed to solve this by adding the error checking code to where I was reading the values in from the JTextFields. So instead of:
filter1Type = String.valueOf(Gui.filter1.getSelectedItem());
filter1Value = Integer.parseInt(Gui.filter1Text.getText());
I now have:
filter1Type = String.valueOf(Gui.filter1.getSelectedItem());
if(isNumeric(Gui.filter1Text.getText()){
filter1Value = Integer.parseInt(Gui.filter1Text.getText());
} else {
filter1Value = 0;
//Display some error message to the user here.
}
So now, any value entered into the filter1Text JTextField that is not numeric will automatically be converted to 0, and a message will be displayed to the user telling them to enter a valid value.
First of all,you can control the empty TextFields using the trim method. This control must be used before you assign textField value to the arraylist.
Before control textField value is empty or not,then assign to the arraylist.
String controlledText = eid.getText().trim();//read contents of text area into 'TextField'
if(!controlledText.equals("")){
//doSometing();
}

Categories