I am trying to create a boolean from an Edit Text field.
I've already converted it into a string but need to make a boolean from the answer. I want to assign the correct answer as 1 and 2 as the wrong answer. If you can give me a tip how to make sure they enter only 1 or 2 that would be great!
This is what i have so far:
public void EnterAnswer(Editable insertAnswer) {
EditText enterAnswer = (EditText) findViewById(R.id.editText_question_six);
String answer = enterAnswer.getText().toString().trim();
}
First and foremost, using an EditText, there is really no way of specifying the values a user can input. Best you can do is to use the input type attribute by setting the input type to "number" as shown below. This way, a user would only be able to input numbers.
android:inputType="number"
You can also use the setError() method of the EditText to display an error if the user inputs a value that is neither 0 nor 1. This is illustrated below:
if(!(editText.getText().toString().equals("0") || editText.getText().toString().equals("1"))){
editText.setError("Wrong input, you can only input 0 or 1");
}
Follow this procedure:
Get the text from your textview
Check whether the text is one or two
assign a value to your boolean variable based on the result above.
Illustration:
public boolean EnterAnswer(Editable answerView){
boolean result = false;
String answer = answerView.getText().toString().trim();
if(answer.equals("1")){
result = true;
}
return result;
}
Following the logic above, the method will only return true if the answer (from the EditText) is one.
I hope this helps... Merry coding!
Related
I want to pass the float variable 'f' through sendKeys in the below program.Can someone please let me know the same? As of now, it is throwing
"The method sendKeys(CharSequence...) in the type WebElement is not applicable for the arguments ".
Code:
public static String isEditable(String s1) {
f=Float.parseFloat(s1);
System.out.println(f);
boolean bool=webDriver.findElement(By.xpath("expression")).isEnabled();
if(bool) {
if((f<0) || (f>6)) {
error="Value must be between 0.00% and 6.00%";
System.out.println(error);
} else {
webDriver.findElement(By.xpath(""expression")).sendKeys(f);
}
} else {
error="Please enter a valid Number";
}
return error;
}
Convert the float to a string:
webDriver.findElement(By.xpath("...")).sendKeys(Float.toString(f));
I know you already accepted an answer but I wanted to clean up your code a little and give you some feedback.
I changed the name of the function because a function named isEditable() should return a boolean indicating whether some field is editable. That's not what your function is doing so it should be given a more appropriate name. I made a guess at what the actual name should be... I could be way off but you should name it something more along the lines of what it's actually doing... putting text in a field.
I removed the isEnabled() check because that should be done in the function that sets the fund number. Each function should do one thing and only one thing. This function validates that the rate passed is in a valid range and then puts it in the field.
I removed the duplicate code that was scraping the INPUT twice. Just do it once, save it in a variable, and reuse that variable. In this case, there's no need to scrape it twice.
and as d0x said, you shouldn't convert the s1 string to a float and then back to string when you sendKeys() ... just send the s1 string. Translating it back doesn't help readability, it just means you wrote more code that someone after you will need to understand. Favor clean code... it's always more readable.
public static String enterRate(String s1)
{
f = Float.parseFloat(s1);
WebElement input = webDriver.findElement(By.xpath(".//*[#id='p_InvestmentSelection_4113']/div/div/div[5]/div/ul/li/div[3]/div[2]/label/div[1]/input"));
if ((f < 0) || (f > 6))
{
error = "Value must be between 0.00% and 6.00%";
}
else
{
input.sendKeys(s1);
}
return error;
}
Can you try passing s1 instead of f. Because the method takes a string, not a float.
Your method should look like this:
String selector = "expression";
webDriver.findElement(By.xpath(selector)).sendKeys(f);
And please use better variable names like userInput instead of s1 or userInputAsFloat instead of f or investmentInputVisible instead of bool etc.
I'm new to Java GUI . I'm doing a project using Netbeans.There are several text fields and I need to do validations for them.
Validations should be
Want to check whether fields are empty or not.
If it's a number field it should be validated only to input numbers.
In web (Ex:contact form) validations we can validate the fields step by step when user is entering data up to down. I need to know whether it is possible or not in Java GUI programmes.
Found several methods as Documentfilter,InputVerifier and PlainDocument. Can someone please explain the differences of them and what is the best method to use for validations input data of users in Java?
depending how familiar you are with java programming in general, this helps you more or less
Retrieve the text from the JTextField (getText()) and check for emptiness
Cast the text to a number and catch a NumberFormatException in case its not a number.
for 2) its a validation after the user has entered something and not an validation during typing
You should write java method for validation .
1.Read Text from JTextField using (getText() ) and pass this string to NumberValidation Method . Sample code is shown below
String data=textFieldObject.getText().trim();
boolean validate =isValidMobile(data);//return false if the data is not a valid phone number
public boolean isValidMobile(String PhoneNumber)
{
try{
if(PhoneNumber.length()==10) //checking length.
{
for(int i=0;i<10;i++){
char c=PhoneNumber.charAt(i);
if(!Character.isDigit(c)) //return false if the character is digit
{
return false;
}
}
}else
{
return false;
}
return true;
}catch(Exception r)
{
return false;
}
}
Basically I need to check that the user input from inputET (an EditText) is equal to the integer, correctAnswer. The problem I'm getting is that "" (which is the text in the EditText field) cannot be converted to an int. Is there any other ways of achieving this or catching the error, I've tried the following code which to my understanding asks if the string in the EditText is not equal to "". Am i going the right way about this or is there an easier way?
// check the input
if (inputET.getText().toString() != "") {
if (correctAnswer == Integer.parseInt(inputET.getText()
.toString())) {
inputET.setText("");
newSum();
}
}
if the user inputs the same int as the correctAnswer integer then the EditText text is reset to "".
Thanks for any help.
try this:
if (!inputET.getText().toString().equals("")) {
if (correctAnswer == Integer.parseInt(inputET.getText()
.toString())) {
inputET.setText("");
newSum();
}
}
Used .equals() method for String comparison.
Based on your requirement I think using TextUtil class will be right way to go for checking the edittext is empty or not.
if(!TextUtils.isEmpty( inputET.getText().toString())){
if (correctAnswer == Integer.parseInt(inputET.getText()
.toString())) {
inputET.setText("");
newSum();
}
}
rather tha doing if (inputET.getText().toString() != "") have a try with
if (!inputET.getText().toString().equals(""))
print the "inputET.getText().toString()" to console and see what it returns. I would hope you need to check the following
String str = inputET.getText().toString()
if (null!=str && str.trim().equals("")) {
if(inputET.getText().toString()!=null&&!(inputET.getText().toString().isEmpty())){
//code for mot null
}else{
//code for null
}
I'm writing an app that takes in an input from the AddBook class, allows it to be displayed in a List, and then allows the user to Search for their book. To this end, I'm creating a temporary EditText, binding it to the box where the user actually enters their search value, then (after ensuring that it is not empty) I compare what they've entered for the ISBN number with the ISBN numbers of each entry in the arrayList of <Book> custom objects, the list being named books.
Problem is, when I try to parse the EditText into an Int, it doesn't seem to work. I first tried using toString() on the EditText, then using Integer.parseInt() on the result of that method, but it hasn't worked out, as the conversion is seemingly unsuccessful;
All of the resources are in place and the code compiles properly, so those aren't the problems here.
EditText myEdTx = (EditText) findViewById(R.id.bookName);
if(myEdTx.getText().equals("")){Toast toast = Toast.makeText(this, "Please enter something for us to work with!", Toast.LENGTH_SHORT);
toast.show();}
else{
//resume here
for(int i=0; i<books.size(); i++)
{
Book tBook = new Book(i, null, null); tBook = books.get(i); String s=myEdTx.toString();
int tInt = Integer.parseInt(s);`
To get the string representation of an EditText's content, use:
String s = myEdTx.getText().toString();
Using toString() directly on the EditText gives you something like:
android.widget.EditText{40d31450 VFED..CL ......I. 0,0-0,0}
...which is clearly not what you want here.
You assume the user inputs a number into the text field, but that is unsafe, as you only get a string text (which theoretically can contain non-numbers as well). When I remember correctly, you can adjust a text field in android where a user only can input numbers, which should suit you more.
NumberFormatException occurs when Integer.parse() is unable to parse a String as integer, so, its better to Handle this exception.
String s = myEdTx.getText().toString();
try {
int tInt = Integer.parseInt(s);
} catch( NumberFormatException ex ) {
//do something if s is not a number, maybe defining a default value.
int tInt = 0;
}
So the current String here you are trying to parse is with white space in the line
and integer class unable to parse that white space. So use following code.
String s=myEdTx.getText().toString();
int tInt = Integer.parseInt(s.trim());
String s = myEdtx.getText().toString().trim();
int iInt = Integer.parseInt(s);
I am working on android. In my app users will register by entering their phone number in edittext. This phone number is then saved in database. Now when the user login with the app, I am getting the list of contacts from his mobile and comparing that with the people who register with this app. If the number in the contacts list matches with the number in the database, then I need to display those numbers in listview. Here the problem is if the user save his number with +91 or with 0 before his contact then the number in the database is not matching with the contact. At that time the numbers are not displaying.
For this issue, Do we need to keep any alert before entering the number in edit text? For example in edit text I gave, Ph no: 8923458128 and the saved it in database. Now I logged in with this number and my contacts list for suppose
9823484586
+919988334856
Lets say the above 2 numbers are stored in database. But the 2nd contact , the user entered as 9988334856 without +91. Then finally in the listview instead of 2 numbers only 1 number is displaying as the second number is not matching with database number.
How can I solve this issue? Please help me in this regard.
If you are fetching all phones from DB, then you can use below code to match entered phone with phone from DB using PhoneNumberUtils.compare()
It compares phone numbers a and b, return true if they're identical
enough for caller ID purposes.
private String getMatchedPhones(ArrayList<String> contactsFromDB, String phoneToMatch) {
// Iterate all numbers and match
for (String numberFromDb : contactsFromDB) {
if (PhoneNumberUtils.compare(numberFromDb, phoneToMatch)) {
return phoneToMatch; // Or numberFromDb
}
}
return null; // Or can custom msg. If not matched.
}
I think best way to do it create your table with 4 column-
1)id
2)name(if needed)
3)country-code
4)phone number
And now on your UI prefix country code in a spiner and give phone-number type of field in a textview. And in your database use integer value to store number.
And from matching your phone number just pass this query-
1)phoneNumber = phoneNumberEditText.getText().toString();
2)
// Reading all contacts from database
List<Contacts> number = db.getAllNumber();
for (final Contacts cn : number) {
if ((phoneNumber.equals(cn.getNumber()){
//do what you want
}
}
Thanks!Hope it will help you.
Put these two lines in your XML file at that phone number edit text field
android:inputType="numberDecimal"
android:maxLength="10"
then he could not enter more than 10 numbers and only he should enter numbers.
you can take country code in one more text field and validate with it.
For an Mobile number validation android provide InBuilt Patterns.But it only works in API level 8 and above.Try below one line code.
/* method for phone number validation */
private Boolean Number_Validate(String number)
{
return !TextUtils.isEmpty(number) && (number.length()==10) && android.util.Patterns.PHONE.matcher(number).matches();
}
you can call this mehtod by passing number in parameter,it return either true or false.
Number_Validate(number);
Hope you get your answer.
Thanks.
Use TEXT not Int in your database. When you use Int, if the first number is 0 it will disregard so just use TEXT.
private boolean phvalidator(String ph2) {
// TODO Auto-generated method stub
String expression = "^[0-9-1+]{10,15}$";
CharSequence inputStr = ph;
Pattern pattern = Pattern.compile(expression,Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);
return (matcher.matches())? true : false;
try this
final String mobile = emobile.getText().toString();
if (!isValidMobile(mobile)){
emobile.setError("Invalid Mobile");
}
private boolean isValidMobile(String mobile) {
if (!TextUtils.isEmpty(mobile)) {
return Patterns.PHONE.matcher(mobile).matches();
}
return false;
}