Scenario: when the focus is lost from an EditText, I'm checking if it contains null (in the first if block).
If so, then I'll show a Toast.
In the else-if block I'm checking if the EditText doesn't contain letters.
Then I'll show a toast, but when I run the application, the Toast is shown even on a correct input.
I.e.: If I enter any letter the Toast should not be shown, it should be shown only when a null or digit/special symbol is entered.
Here is the code
et1.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
if(!hasFocus)
{
a = et1.getText().toString();
if (a.equals(""))
{
Toast.makeText(getApplicationContext(), "Your entry is incorrect!!", Toast.LENGTH_LONG).show();
}
else if (!a.contains("[a-z]")||!a.contains("[A-Z]")) {
Toast.makeText(getApplicationContext(), "Your entry is incorrect!!", Toast.LENGTH_LONG).show();
}
else
{
}
Please help
The '==' operator only compares references. To compare string values you must use the equals() method.
Instead of
if (a == "")
use
if (a.equals(""))
See: What is the difference between == vs equals() in Java?
It's not working because:
if (a == "")
won't work in Java
Use
if (a.equals(""))
instead
Also, String.contains doesn't use regular expressions, but CharacterSequences.
So, unless your string doesn't contain the exact character sequences "[a-z]" or "[A-Z]" (and only one of these 2 strings), you'll never get a match.
See: http://developer.android.com/reference/java/lang/String.html#contains(java.lang.CharSequence)
The problem is:
if (a == "")
Strings can't be compared like this. Instead, check for size equal to 0, or against a specific string with the equals() method.
Related
I am going to save the value in one textview after the length of input string is fulfilled. but saved value is empty if the value of textview is used. If Editable s value in afterTextChanged is used, it causes crash.
Some codes as following:
number = (EditText) findViewById(R.id.number);
final String numberStr = number.getText().toString();
if following afterTextChanged is used, empty value is saved even I already input sth.
#Override
public void afterTextChanged(Editable s) {
if (s.length() == 11) {
Toast.makeText(MainActivity.this, numberStr , Toast.LENGTH_SHORT).show();
saveSettingNote(MainActivity.this, "number_save", "number", numberStr);
number.setText(getSettingNote(MainActivity.this,"number_save", "number"));
}
}
if following code is used, it will cause crash:
#Override
public void afterTextChanged(Editable s) {
if (s.length() == 11) {
Toast.makeText(MainActivity.this, s.toString(), Toast.LENGTH_SHORT).show();
saveSettingNote(MainActivity.this, "number_save", "number", s.toString());
number.setText(getSettingNote(MainActivity.this,"number_save", "number"));
}
}
Saving and getting are based on SharedPreferences, which works well in other situation.
Actually, what I want to implement is saving String after the criteria is fulfilled for input string.
Please help to identify what is wrong in above code or suggest a new to get that function. Thanks a lot in advance.
Your app is crashing because your listener is looping indefinitely with the same value passed in over and over.
The ugly truth is that you've to unbind your listener, set the value and then bind it again:
#Override
public void afterTextChanged(Editable s) {
if (s.length() == 11) {
// unbind your listener
editText.addTextChangedListener(null);
// do your stuff
Toast.makeText(MainActivity.this, s.toString(), Toast.LENGTH_SHORT).show();
saveSettingNote(MainActivity.this, "number_save", "number", s.toString());
number.setText(getSettingNote(MainActivity.this,"number_save", "number"));
// bind your listener again
editText.addTextChangedListener(MainActivity.this);
}
}
Using RxBinding you can achieve this in a more elegant way:
RxTextView.textChanges(editText)
.map { it.toString() }
.filter({ it.length == 11 })
.distinctUntilChanged() // <-- the important part
.subscribe(
{ s -> /* do your stuff here */}
)
you set text in editext afterTextChanged(Editable s) which calls text change listener again and again and cause the application to crash. call number.setText(getSettingNote(MainActivity.this,"number_save", "number")); outside the text change listener.
My guess it that by declaring numberStr as you did, you expect to change its value each time the edit text change its content. However, this is not the case; it will be initialised with an empty string "" (unless you don't have any other string in the edit text at that moment) and then it will NEVER change its value, thus resulting in the empty value that you save. As solution I would suggest to make numberStr non final and update its value (like you already did) each time before showing the Toast.
I'm trying to check the editText condition. In the code below, I declared a setOnClickListener method to check the condition of editText. If condition is true, I want to print toast message, change the activity and to output a sound. If condition fails, it should toast a single message. In both cases if it's true or not, it prints me only "Incorect" no matter if editText is correct.
What I am doing wrong?
public void next(View v){
final MediaPlayer correctSound = MediaPlayer.create(this, R.raw.correctsound);
Button playCorrectSound = (Button) this.findViewById(R.id.angry_btn1);
final EditText editTextt = (EditText) findViewById(R.id.editText);
playCorrectSound.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
editTextt.setVisibility(View.INVISIBLE);
if(editTextt.getText().toString() == "string")
{
Toast.makeText(getApplicationContext(), "Correct", Toast.LENGTH_SHORT).show();
correctSound.start();
Intent i = new Intent(Hereuu.this, MainActivity.class);
startActivity(i);
} else {
Context context = getApplicationContext();
CharSequence text = "Incorect";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
editTextt.setVisibility(View.VISIBLE);
}
});
}
Like everyone had said, you
Basically, when you use == operator, your are checking if the reference for object are the same/equals. When you use .equals(String), the method checks the content.
tip:
When your are working with Strings, remember to avoid NullPointerException situations. So,you should write "constant".equals(editTextValue) instead of editTextValue.equals("constant")
The link bellow will help you to understand how String objects and String content work:
Java String.equals versus ==
regards
in java you need to compare strings using equals method instead of ==
check this topic for more details
I would suggest you to take some basic JAVA lessons. That will immensely help you.
For now, the problem is in the way you are checking equality of the strings. You do not use == with strings, you use String#equals() method. So,
Change
editTextt.getText().toString() == "string"
to
editTextt.getText().toString().equals("string")
Make sure to compare strings in java with .equals and not ==. Use this if statement:
if(editTextt.getText().toString().equals("string"){
Here the Text Area is constantly changing in terms of number and I want to trigger an event when the Text Area gets a particular number example I have tried this -
public void myfunction45(Canvas Panel)
{
if (Indicator = 45) {
Panel.enabled = false;.
}
} //(indicator- www.progress).
But it does not work(it does not read it nothing happens). how do I match the condition as the number is to be specific. please give an example for explanation. Thanks in advance.
That if statement would cause you problems.
You would want:
if(Indicator == 5)
instead. At the moment you're assigning the value without checking it, this would cause a compiler error. If it's just a typo, then update your answer, slightly confusing otherwise.
With regards to checking the text value. You'd have to grab the text value, for that you need a reference to the Text area. This approach assumes that the text area has it's value set by a user. Currently you're not grabbing any text values to compare, as a result, the if statement won't know what to compare.
Here's one approach:
public void myfunction5(Canvas Panel)
{
float result;
string textValue = yourTextArea.text;
if(Single.TryParse(textValue, out result))
{
if(result == Indicator)
{
Panel.enabled = false;
}
}
}
You use TryParse to avoid any potential exceptions that would be thrown if the user entered something that wasn't a number. This method will take the value from your text area, how you get your text area is up to you, and try to parse the text value into a float. The method will return true if the parse was a success, false otherwise.
Here's the reference for the TryParse stuff:
https://msdn.microsoft.com/en-us/library/26sxas5t(v=vs.110).aspx
If you wanted to parse it to an int, then you'd be using the Int32's version of TryParse, https://msdn.microsoft.com/en-us/library/system.int32_methods(v=vs.110).aspx
I'd also recommend having a peak at the Input Field documentation: https://docs.unity3d.com/Manual/script-InputField.html
You can subscribe your method to the Input-fields On Value Changed event, your function will need to tweaked slightly though:
public void myfunction5(string text)
{
float result;
if(Single.TryParse(text, out result))
{
if(result == Indicator)
{
CachedPanel.enabled = false;
}
}
}
Don't forget to store a reference to the panel you want to disable.
Hopefully this is what you're after.
Panel is already a Canvas type, it doesn't make any sense to GetComponent<Canvas> on the same type.
Try using Panel.enabled = false;.
For the rest, we don't know how you get the Indicator reference, or how you built the UI hierarchy, so we can't assess if the problem is there.
Edit: I could I miss the single = baffles me lol. I should avoid answering questions when I'm tired.
I am creating an app for counting points in games. This app has a edittext component. I want to check if the string retrieved from the edit text contains characters other than 0-9. This is because my app contains a integer.parse function wich crashes if characters other than 0-9 is inputed. All help will be greatly appreciated. Thanks in advance.
If you just want to notify the user of an invalid character then you can wrap it in a try/catch and act accordingly
try
{
int someInt = Integer.parseInt(et.getText().toString());
// other code
}
catch (NumberFormatException e)
{
// notify user with Toast, alert, etc...
}
You also can use a regular expression to look for the characters you want/don't want depending on your needs.
Just to be clear in case my code comment wasn't, I am suggesting that you do something with the exception and notify the user. Don't catch it and let it sit
public static boolean isNumeric(String str)
{
for (char c : str.toCharArray())
{
if (!Character.isDigit(c)) return false;
}
return true;
}
OR
public boolean isNumeric(String s) {
return s.matches("[-+]?\\d*\\.?\\d+");
}
Firstly you can setup edittext as integer numbers only, so in your layout put
android:inputType="number"
It will set to integer numbers only in edit text.
All possible types here:
http://developer.android.com/reference/android/widget/TextView.html#attr_android:inputType
Then you can test with regular expression or/and catch exception when parsing.
Regular expression would be:
"string".matches("\\d+") // true when numbers only, false otherwise
Reference here:
http://developer.android.com/reference/java/lang/String.html#matches(java.lang.String)
http://developer.android.com/reference/java/util/regex/Pattern.html
I have 4 edit text fields in my app which take in one long and 3 double values respectively. I have used them with onFocusChangedListener(). My issue is whenever a certain edit text gains focus a default (0.0 in case of double) is displayed into the edit field before the user enters the values. I want them to to be blank before the user enters his values. I have tried using editText.setText("") and editText.setHint(""). But these work when the activity starts, but once the edit field gains focus the default values are shown.
Please help me with the glitches.
Thank you.
Heres the code
public void onFocusChange(View EditTextFocus , boolean hasFocus)
{
// TODO Auto-generated method stub
try
{
km= Long.parseLong(ETKm.getText().toString());
fuelQty= Double.parseDouble(ETFuelQty.getText().toString());
fuelPrice= Double.parseDouble(ETFuelPrice.getText().toString());
totalCost= Double.parseDouble(ETTotalCost.getText().toString());
}
catch(NumberFormatException ne)
{
ne.printStackTrace();
}
if(ETTotalCost.hasFocus())
{
if((fuelQty!=0)&&(fuelPrice!=0))
totalCost=fuelQty*fuelPrice;
ETTotalCost.setText(new DecimalFormat("##.##").format(totalCost));
}
else if(ETFuelQty.hasFocus())
{
ETFuelQty.setText("");
if((fuelPrice!=0)&&(totalCost!=0))
fuelQty= (int) (totalCost/fuelPrice);
ETFuelQty.setText(String.valueOf(fuelQty));
}
else if(ETFuelPrice.hasFocus())
{
ETFuelPrice.setText("");
if((fuelQty!=0)&&(totalCost!=0))
fuelPrice=totalCost/fuelQty;
ETFuelPrice.setText(String.valueOf(fuelPrice));
}
}
Try setting setHint() to something.
A hint is a placeholder until the person enters some input, so you can put something like "Fuel price".
I solved my problem. It might prove useful for others searching this as well.
My issue was that I was initializing and parsing my variables before they came in focus. This made me get the initial values ie. null (0) values in the edit fields when in focus.
I initialized and parsed my variables after the edit fields gained focus
So, I changed my code to:
*case R.id.ETTotalCost:
if(ETTotalCost.hasFocus())
{
if(ETFuelQty.length()>0 && ETFuelPrice.length()>0)
{
fuelQty=Double.parseDouble(ETFuelQty.getText().toString());
fuelPrice= Double.parseDouble(ETFuelPrice.getText().toString());
if((fuelQty!=0)&&(fuelPrice!=0))
totalCost=fuelQty*fuelPrice;
ETTotalCost.setText(new DecimalFormat("##.##").format(totalCost));
}
}*