How do I set the text of an EditText to an Int? - android

In an attempt to set an EditText to an Int value, I've tried various ways of converting the Int to a value that the EditText will accept, but all fail:
processButton.setOnClickListener {
var intNo = inputText.text as Int
intNo *= 2
outputText.text = intNo as String // error = "required editable"
outputText.text = intNo.toString() // err: type mismatch
outputText.text = Int.toString(intNo) // type mismatch reqd editable
outputText.text = "What is going on?" // type mismatch reqd editable
}
How can I set the EditText to an Int value?

var a: Int = 12
var s: String = a.toString()
This should work for this.

Try given code it will work. What I am doing here I am converting inputText first to String then Int. After I am multiplying with 2 then I am assigning a value for outputText by converting to string.
processButton.setOnClickListener {
var intNo = inputText.text.toString().toInt()
intNo *= 2
//println(intNo.toString())
val myString = intNo.toString()
// If you using outputText as Editable then use this
outputText.text = SpannableStringBuilder(myString)
}

There are a couple things going on here, and to understand them, let's take a look at the various getText and setText methods that EditText has:
Editable getText()
void setText(CharSequence text)
void setText(#StringRes int resid)
// many other setText methods with buffer options
So what Kotlin does here to let you use property syntax is that it creates a text property. The getter used for the property is obvious, since there's only one. The setter for the property is supposed to be the one that takes a CharSequence parameter (it would make sense, Editable extends CharSequence), but actually trying to assign anything other than an Editable to it won't work. See this issue.
To get to the problem at hand, you can read the value in your EditText and convert it to a String like this:
val input = inputText.text.toString()
Then, you can use the toInt() function from the standard library to convert it to an Int (be aware that this will throw an exception if the String can't be parsed):
val doubled = input.toInt() * 2
And finally, you can set the value of the EditText by calling the setText setter in the traditional Java style, passing in a String:
inputText.text.setText(doubled.toString())
A bit of a mess because of the two-way conversion between String and Int, plus the oddities of how the text property is generated here, but that's the way to do it. If you're bothered by how this looks, you could always hide some of this mechanism behind extension properties.

var num: Int = 5
to convert to string would be
num.toString()

Related

Adding two numbers from EditText fields

fun add(num1: EditText, num2: EditText){
try {
num1.toString().toInt()
num2.toString().toInt()
answer.setText((num1 + num2).toString())
} catch (e: NumberFormatException) {
answer.text = "Input Error"
}
}
I'm trying to make an integer calculator and have a problem.
answer.setText((num1 + num2).toString())
Here the addition symbol is highlighted in red. The text of the error is huge. What could be the problem?
Use getText() method of EditText to get the value from a EditText.
Change your code like the below
val value1 = num1.getText().toString().toInt()
val value2 = num1.getText().toString().toInt()
answer.setText((value1 + value2).toString())
Rafiul and Tenfour04 answer above is correct.. You need to take value from edittext before converting it to string. what you do at you code is convert the whole edittext to string not the value. And I think you need a variable to contain value from edittext. So it will look like this:
var a = num1.getText().toString().toInt()
var b = num2.getText().toString().toInt()
answer.setText((a + b).toString())
num1 and num 2 are EditTexts and you are adding the EditTexts.. this is the main mistake.
From your end you are type casting the values of EditTexts but not getting the values of editText and not saving in the separate variables.
Just get & save the values in separate variables: as #Bobby suggested:
var a = num1.getText().toString().toInt()
var b = num2.getText().toString().toInt()
And then perform addition.
answer.setText((a + b).toString())

Comparing TextView's getText() w/ R.string.stringValue in android?

Here's my code that's giving me grief.
TextView questionView = (TextView) findViewById(R.id.questionView);
if(questionView.getText().equals(R.string.begginigStatement){
currentQuestionIndex = -2;
Log.d(TAG, "the TextView's text is equal to R.string.beggingStatement);
}
I'm trying to compare a string w/ an int
but I can't figure out the solution other than perhaps hardcoding the string, though I know that's not a proper convention. What's the solution?
R.string.begginigStatement is just an ID of the string as generated in R.class. To retrieve the value call:
getResources().getString(R.string.begginigStatement)
try to use:
context.getResources().getString(R.string.begginigStatement);
and context can be 'getActivity()' if it's in Fragment or just :
getResources().getString(R.string.begginigStatement)
if it has context
You have to compare this string values:
questionView.getText().toString().equal(getResources().getString(R.string.begginigStatement))

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

android Cannot invoke substring(int, int) on the primitive type long

I have textview which will show large numbers and if the number of digits is larger than 5 I want to make the textview show only 4 digits with dots like this(3544...) I tried but I got this error:
android Cannot invoke substring(int, int) on the primitive type long
here is my code:
EditText EditNumber;
long theNumber;
String str = EditNumber.getText().toString();
theNumber = Long.parseLong(str );
if( theNumber >5)
{
theNumber = theNumber.substring(0,4)+"..."; // the error in this line.
textView1.setText(Long.toString(theSide));
}
else
{
textView1.setText(Long.toString(theNumber));
}
As pointed by Martin Cazares the long does not have substring. Use your string instead of your double value.
EditText EditNumber;
long theNumber;
String str = EditNumber.getText().toString();
if( str.length() > 4) // > 4 digits
{
textView1.setText(str.substring(0,4)+"...");
}
else
{
textView1.setText(str);
}
Hope it helps!
Long.toString(theNumber).substring(x,y);
That should give you the digits you want.
You're trying to do a substring method call on a Long which doesn't have that method. You probably intended to do str.substring(0, 0) instead.
The error is that "long" do not have a substring method, be carefull with primitives, they do not have any methods at all...
If you want to substring do it like this:
String theNumber = str.substring(0,4)+"...";
textView1.setText(theNumber);
But beyond that, you might not even need to do it your self, look at the
android:ellipsis="end" property of the TextView
it will do the ellipsis for you if the size of the TextView is smaller than the actual text.
Regards!

Add a number and a Text Input value with adobe flex

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.

Categories

Resources