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.
Related
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.
Previously i am using if else condition for checking the edit text field its working but i need to change into switch case.I am not getting to implement switch case inside my code.please tell me how to implement that in switch case.
btnSave.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
/**
* Validation
*/
if(tvStartLocation.getText().toString().equalsIgnoreCase(""))
{
Toast.makeText(getActivity(),"Please enter start location", Toast.LENGTH_SHORT).show();
}
else if(tvEndLocation.getText().toString().equalsIgnoreCase(""))
{
Toast.makeText(getActivity(),"Please enter end location", Toast.LENGTH_SHORT).show();
}
else if(etStartOdometer.getText().toString().equalsIgnoreCase(""))
{
Toast.makeText(getActivity(),"Please enter Trip Start Odometer reading", Toast.LENGTH_SHORT).show();
}
else
{
gotonextfraggment();
}
You cannot use a switch-case construct in your case. In a switch-case, only one argument is matched with the case labels and if there is a match, that label is executed.
switch(arg) {
case "label1":
case "label2":
.
.
.
default:
}
arg is tested with label1, label2 and so on.
In your case, in every else-if, you are trying to test the equality of the text in different EditTexts with "". So your arg changes in every else-if. Even if you try to implement switch-case, the arg of your switch-case will change continuously and you'll not be able to go any further. You cannot even do this:
switch("") {
case edittext1.getText():
case edittext2.getText();
.
.
.
default:
}
Because the case labels must be literals not variable values.
So it is impossible to implement switch-case for the problem that you are facing
In fact what you've done right now is the perfect way to do it.
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();
}
}
});
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 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