Add a number and a Text Input value with adobe flex - android

I am trying to add a number and a text input value to display in a label. here is my code thus far.
'lblAnswer.text = bloodglucose + 100;'
Please tell me what I am doing wrong.

Please try following answer -
bloodglucose += 100;
lblAnswer.text = String(bloodglucose);
Hope this will work :)

Sunil is correct - when doing mixed type addition, the UI input first needs to be coerced to either int or Number. IE: Number(bloodglucose) + 100; This assumes bloodglucose is actually a getter to the input text reference. If it's not, then you need to coerce the property and not the id of the component.
Getter: public function get bloodglucose():Number { return Number(myInput.text); }
In method: lblAnswer.text = bloodglucose + 100;
or (bloodglucose is a UIComponent):
In method: lblAnswer.text = Number(bloodglucose.text) + 100;

You should use String(int i)
lblAnswer.text = String(bloodglucose + 100);
Update: What about something like this:
var i:int = bloodglucose + 100;
var s:String = String(i);
lblAnswer.text = s;

** Update ,
I am changing the code from the update that was previously posted. I initially found that because I was including the string value inside of the equation this is what was prompting an error. You have to wrap the converted components to Number inside of the string all together. Basically convert the components to a number, then convert the answer received into a string.
Below is an example of the wrong code.
txtAnswer = (String(Number(bloodglucose)+100)) / 36)).toFixed(2)
Below this line is the fixed code.
txtAnswer.text = String( (Number(bloodglucose.text) + (Number(100))/ (Number(36))).toFixed(2) ;
The .toFixed Property signifies how many decimal places I want the returned value to display.

Related

How to check if a string has a specified character?

I am new to android studio and kotlin. I need to find a way to check if a string contains a char, which is, in this case, "/"
I want to form a piece of code in the following manner:
if (string input contains a character "/") = true {
<code>
}
else{
<code>
}
Please tell me how to do this, and if possible, give me the code I'll need to specify as the condition.
You can use contains, like this:
val a = "hello/"
val b = a.contains("/")
When the string has the character will return true.

Spliting a Text on multiple conditions

I am writing an app with Android Studio and I want to split a text into different values.
I have following text in result
*"Name: Peter;Age: 25; City: Chicago"*
I want to get:
*Name = Peter;
Age = 25;
City = Chicago;*
I used the search function and found these solutions: Android Split string but for my problem it seems to be too complicated.
The easiest way is to use split() method.
String s1="Name: Peter;Age: 25; City: Chicago";
String[] words=s1.split(";");
//using java foreach loop to print elements of string array
for(String w:words)
{
Log.i("Words: ", w);
}

Format textField value with comma - Titanium

I have a textField value as 12345678955. I want to format this value as 1,234,567.8955
Want to seperate the value with comma.
I have tired with some codes. But it doesn't work.
Well, you would want to get your 4 decimal places you would need to divide your number by 10000:
var newNumber = parseInt($.yourTextField.value);
newNumber = Math.round(Number(newNumber)) / 10000;
console.log(newNumber); // 1234567.8955
Next you want to add your commmas:
var parts = newNumber.toString().split(".");
var num = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",") + (parts[1] ? "." + parts[1] : "");
console.log(num); // 1,234,567.8955
Thats the functionality, how you tie that to your textField and by which event listener, is yours to work out.
(answer adapted from https://stackoverflow.com/a/25127753/829989 which you could have easily found on your own)

Android TextView : "Do not concatenate text displayed with setText"

I am setting text using setText() by following way.
prodNameView.setText("" + name);
prodOriginalPriceView.setText("" + String.format(getString(R.string.string_product_rate_with_ruppe_sign), "" + new BigDecimal(price).setScale(2, RoundingMode.UP)));
In that First one is simple use and Second one is setting text with formatting text.
Android Studio is so much interesting, I used Menu Analyze -> Code Cleanup and i got suggestion on above two lines like.
Do not concatenate text displayed with setText. Use resource string
with placeholders. less... (Ctrl+F1)
When calling TextView#setText:
Never call Number#toString() to format numbers; it will not handle fraction separators and locale-specific digits properly. Consider
using String#format with proper format specifications (%d or %f)
instead.
Do not pass a string literal (e.g. "Hello") to display text. Hardcoded text can not be properly translated to other languages.
Consider using Android resource strings instead.
Do not build messages by concatenating text chunks. Such messages can not be properly translated.
What I can do for this? Anyone can help explain what the thing is and what should I do?
Resource has the get overloaded version of getString which takes a varargs of type Object: getString(int, java.lang.Object...). If you setup correctly your string in strings.xml, with the correct place holders, you can use this version to retrieve the formatted version of your final String. E.g.
<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>
using getString(R.string.welcome_message, "Test", 0);
android will return a String with
"Hello Test! you have 0 new messages"
About setText("" + name);
Your first Example, prodNameView.setText("" + name); doesn't make any sense to me. The TextView is able to handle null values. If name is null, no text will be drawn.
Don't get confused with %1$s and %2$d in the accepted answer.Here is a few extra information.
The format specifiers can be of the following syntax:
%[argument_index$]format_specifier
The optional argument_index is specified as a number ending with a “$” after the “%” and selects the specified argument in the argument list. The first argument is referenced by "1$", the second by "2$", etc.
The required format specifier is a character indicating how the argument should be formatted. The set of valid conversions for a given argument depends on the argument's data type.
Example
We will create the following formatted string where the gray parts are inserted programmatically.
Hello Test! you have 0 new messages
Your string resource:
< string name="welcome_messages">Hello, %1$s! You have %2$d new
messages< /string >
Do the string substitution as given below:
getString(R.string.welcome_message, "Test", 0);
Note:
%1$s will be substituted by the string "Test"
%2$d will be substituted by the string "0"
I ran into the same lint error message and solved it this way.
Initially my code was:
private void displayQuantity(int quantity) {
TextView quantityTextView = (TextView) findViewById(R.id.quantity_text_view);
quantityTextView.setText("" + quantity);
}
I got the following error
Do not concatenate text displayed with setText. Use resource string with placeholders.
So, I added this to strings.xml
<string name="blank">%d</string>
Which is my initial "" + a placeholder for my number(quantity).
Note: My quantity variable was previously defined and is what I wanted to append to the string. My code as a result was
private void displayQuantity(int quantity) {
TextView quantityTextView = (TextView) findViewById(R.id.quantity_text_view);
quantityTextView.setText(getString(R.string.blank, quantity));
}
After this, my error went away. The behavior in the app did not change and my quantity continued to display as I wanted it to now without a lint error.
Do not concatenate text inside your setText() method, Concatenate what ever you want in a String and put that String value inside your setText() method.
ex: correct way
int min = 120;
int sec = 200;
int hrs = 2;
String minutes = String.format("%02d", mins);
String seconds = String.format("%02d", secs);
String newTime = hrs+":"+minutes+":"+seconds;
text.setText(minutes);
Do not concatenate inside setText() like
text.setText(hrs+":"+String.format("%02d", mins)+":"+String.format("%02d", secs));
You should check this thread and use a placeholder like his one (not tested)
<string name="string_product_rate_with_ruppe_sign">Price : %1$d</string>
String text = String.format(getString(R.string.string_product_rate_with_ruppe_sign),new BigDecimal(price).setScale(2, RoundingMode.UP));
prodOriginalPriceView.setText(text);
Don't Mad, It's too Simple.
String firstname = firstname.getText().toString();
String result = "hi "+ firstname +" Welcome Here";
mytextview.setText(result);
the problem is because you are appending "" at the beginning of every string.
lint will scan arguments being passed to setText and will generate warnings, in your case following warning is relevant:
Do not build messages by
concatenating text chunks. Such messages can not be properly
translated.
as you are concatenating every string with "".
remove this concatenation as the arguments you are passing are already text. Also, you can use .toString() if at all required anywhere else instead of concatenating your string with ""
I fixed it by using String.format
befor :
textViewAddress.setText("Address"+address+"\n"+"nCountry"+"\n"+"City"+"city"+"\n"+"State"+"state")
after :
textViewAddress.setText(
String.format("Address:%s\nCountry:%s\nCity:%s\nState:%s", address, country, city, state));
You can use this , it works for me
title.setText(MessageFormat.format("{0} {1}", itemList.get(position).getOppName(), itemList.get(position).getBatchNum()));
If you don't need to support i18n, you can disable this lint check in Android Studio
File -> Settings -> Editor -> Inspections -> Android -> Lint -> TextView Internationalization(uncheck this)
prodNameView.setText("" + name); //this produce lint error
val nameStr="" + name;//workaround for quick warning fix require rebuild
prodNameView.setText(nameStr);
I know I am super late for answering this but I think you can store the data in a varible first then you can provide the variable name. eg:-
// Java syntax
String a = ("" + name);
String b = "" + String.format(getString(R.string.string_product_rate_with_ruppe_sign);
String c = "" + new BigDecimal(price).setScale(2, RoundingMode.UP));
prodNameView.setText(a);
prodOriginalPriceView.setText(b, c);
if it is textView you can use like that : myTextView.text = ("Hello World")
in editText you can use myTextView.setText("Hello World")

Getting Int from EditText causes error?

So first of all sorry if this has already been asked and answered before, I couldn't find anything relating to my issue.
So I'm working on a project for college and I need to get int values from EditText widgets. I was told to use parseInt to do this however when running my program, that line of code causes the application to crash. I don't know what I'm doing wrong, I'm still very new to android development, thanks for the help :)
public void Calculate (View view)
{
int MilesTravelled;
int FuelUsed;
int MPG;
/* the two lines below are what cause the application to crash */
MilesTravelled = Integer.parseInt(txtMilesTravelled.getText().toString());
FuelUsed = Integer.parseInt(txtFuelUsed.getText().toString());
FuelUsed = (int) (FuelUsed / 4.55);
MPG = MilesTravelled / FuelUsed;
lblMPG.setText(FuelUsed);
}
Do you have this in the onCreate() function?
EditText txtMilesTravelled = (EditText) findViewById(R.id.YourEditText);
But I think you mixed Integer and int. They are not the same:
See this link!
First of all, don't capitalize the first letter of an variables or method names. Following the Java coding conventions, only do that for classes.
What is probably causing your app to crash is you trying to set the text of a label to an integer. The setText method for a TextView needs to take in a string.
So change:
lblMPG.setText(FuelUsed);
to:
lblMPG.setText(String.valueOf(FuelUsed));
Otherwise it might be that it's trying to parse a non-numerical string to an integer.
For exmaple, if the EditText is blank, it will cause your app to crash. To prevent that, try this:
int MilesTravelled = 0, FuelUsed = 0;
try {
MilesTravelled = Integer.parseInt(txtMilesTravelled.getText().toString());
FuelUsed = Integer.parseInt(txtFuelUsed.getText().toString());
} catch (NumberFormatException nfe) {
Toast.makeText(getApplicationContext(), "Error NFE!", 0).show();
nfe.printStackTrace();
}
This way, it will catch a NumberFormatException error (parsing a string to an integer that can't be represented as an integer, such as "hello"). If it catches the error, it will toast that an error has occurred and your integer variables will remain 0.
Or you could just test if the strings contain only digits using the following regex:
int MilesTravelled = 0, FuelUsed = 0;
if (txtMilesTravelled.getText().toString().matches("[0-9]+")) {
MilesTravelled = Integer.parseInt(txtMilesTravelled.getText().toString());
} else {
// contains characters that are not digits
}
if (txtFuelUsed.getText().toString().matches("[0-9]+")) {
FuelUsed = Integer.parseInt(txtFuelUsed.getText().toString());
} else {
// contains characters that are not digits
}
If that's not the problem, then make sure you define your variables properly.
txtMilesTravelled and txtFuelUsed should be EditText:
EditText txtMilesTravelled = (EditText)findViewById(R.id.txtMilesTravelled);
EditText txtFuelUsed = (EditText)findViewById(R.id.txtFuelUsed);
And make sure that your R.id.editText actually exists on your layout and that the IDs are the correct ones.
Last thing, make sure FuelUsed is not 0 before calculating MPG because then you are dividing by 0:
int MPG = 0;
if (FuelUsed != 0) {
MPG = MilesTravelled / FuelUsed;
}
I am assuming that you're entering perfect integers in the EditTexts. It might be a good idea to use the trim function txtMilesTravelled.getText().toString().trim() before using parseInt.
However, I think the major problem is here : lblMPG.setText(FuelUsed);
FuelUsed is an integral value, when you pass an integer to setText(), it looks for a string resource with that integral value. So you should be passing a String to the setText() method.
Use : lblMPG.setText(Integer.toString(FuelUsed));

Categories

Resources