android check if string contains characters other than 0-9 - android

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

Related

Get an event triggered when text change unity?

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.

Button pressing causes app crash

In eclipse i tried making a calculator. I had 2 separate text fields for two numbers and addition subtraction buttons. When i press add or sub button without entering values app crashes. Is there any possible way out?
public void onClick(View v) {
// TODO Auto-generated method stub
String l1= et1.getText().toString();
String l2= et2.getText().toString();
int a=0, b=0;
double result=0.0;
a=Integer.parseInt(l1);
b=Integer.parseInt(l2);
switch(v.getId())
{
case R.id.b1:
result=a+b;
break;
case R.id.b2:
result=a-b;
break;
case R.id.b3:
result = a*b;
break;
case R.id.b4:
if(b==0)
{
open("Cannot Divide By zero");
}
else result = a/b;
break;
}
et3.setText(Double.toString(result));
}
Clayton Oliveira's answer is good. It handles the empty input situation. This code handles all the cases where l1, l2 can not be parsed to integer.
try{
a=Integer.parseInt(l1);
b=Integer.parseInt(l2);
} catch(NumberFormatException e) {
Log.e("Wrong input", e.getMessage());
}
If no value was entered in the EditText, the Integer.parseInt() method will crash because the String passed is not a valid number.
a=Integer.parseInt(l1);
b=Integer.parseInt(l2);
Replace with:
if(!l1.isEmpty() && !l2.isEmpty()){
a=Integer.parseInt(l1);
b=Integer.parseInt(l2);
}else{
Toast.makeText(this,"Something is wrong!",Toast.LENGTH_SHORT).show();
}
Note: the code above only check if was entered something in the EditTexts, you should check if it's a number also. i will leave that part for you to learn ;)
You should post more detail about your code to get many support at here, but i guess you have get this problem:
Add or Sub function net two integer number to calculate but you not enter any value (number value) into Edittext (text field) and value is null or empty string so wrong.
Solution:
- You set edittext to require input number value not string
- you need check input value is empty (if true then do not something) to before calculate.

if-else block not working properly in android

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.

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();
}
}
});

Setting initial Edittext value to blank on focus

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));
}
}*

Categories

Resources