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));
}
}*
Related
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.
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.
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
Ok so I only have a EditText field and a button, which when pressed triggers an AsyncTask.
EditText playerName = (EditText)findViewById(R.id.playerEditText);
if(playerName.getText().toString().length() == 0 )
playerName.setError("Player name is required!");
else {
// do async task
}
The problem is that the error message seems to stay up even after when I input valid text to search. Is there a way to remove the error as soon as the EditText is not empty?
In your else bracket, put playerName.setError(null), which will clear the error.
API documentation: "The icon and error message will be reset to null when any key events cause changes to the TextView's text."
Though it is not so - and therefore we can regard this as bug.
If you use inputType such as textNoSuggestions, textEmailAddress, textPassword, the error is unset after a character is typed. Nearly as documented but again not exactly - when you delete a character, error stays.
It seems, a simple workaround with addTextChangedListener and setError(null) can attain promised behavior.
Besides there are posts about icon losing on Android 4.2. So use with care.
Try this listener:
playerName.addTextChangedListener(new TextWatcher()
{
public void afterTextChanged(Editable edt){
if( playerName.getText().length()>0)
{
playerName.setError(null);
}
}
If you want to hide the error message one way is you apply onclicklistener on the edit box and then
editTextName.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
editTextName.setError(Null)
}
});
Below code worked for me
#OnTextChanged(
value = R.id.editTextName,
callback = OnTextChanged.Callback.TEXT_CHANGED)
public void afterInput(CharSequence sequence) {
editTextName.setError(null);
editTextName.setErrorEnabled(false);
}
'
editTextName.setError(null) Will clear the error message.
editTextName.setErrorEnabled(false) Will remove additional padding.
Add a TextWatcher to your EditText and onError, show your error message using et.setError(errorMessage) else you can remove the error message and error icon like below.
// to remove the error message in your EditText
et.setError(null);
// to remove the error icon from EditText.
et.setCompoundDrawables(null, null, null, null);
This code worked for me.
textInputSetting(binding.emailEdt)
fun textInputSetting(view: TextInputLayout) {
view.apply {
this.editText!!.addTextChangedListener {
if (this.editText!!.text.isNotEmpty()) {
this.error = null
this.isErrorEnabled = false
}
}
}
}
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