I am wondering how to convert an edittext input to an int, I have the user input a number, it than divides it by 8.
MainActivity.java
@SuppressWarnin
I'm very sleepy and tired right now but wouldn't this work?:
EditText et = (EditText)findViewById(R.id.editText1);
String sTextFromET = et.getText().toString();
int nIntFromET = new Integer(sTextFromET).intValue();
OR
try
{
int nIntFromET = Integer.parseInt(sTextFromET);
}
catch (NumberFormatException e)
{
// handle the exception
}
Use Integer.parseInt, and make sure you catch the NumberFormatException that it throws if the input is not an integer.
you have to used.
String value= et.getText().toString();
int finalValue=Integer.parseInt(value);
if you have only allow enter number then set EditText property.
android:inputType="number"
if this is helpful then accept otherwise put your comment.
You can use parseInt with try and catch block
try
{
int myVal= Integer.parseInt(mTextView.getText().toString());
}
catch (NumberFormatException e)
{
// handle the exception
int myVal=0;
}
Or you can create your own tryParse method :
public Integer tryParse(Object obj) {
Integer retVal;
try {
retVal = Integer.parseInt((String) obj);
} catch (NumberFormatException nfe) {
retVal = 0; // or null if that is your preference
}
return retVal;
}
and use it in your code like:
int myVal= tryParse(mTextView.getText().toString());
Note: The following code without try/catch will throw an exception
int myVal= new Integer(mTextView.getText().toString()).intValue();
Or
int myVal= Integer.decode(mTextView.getText().toString()).intValue();
In Kotlin, you can do this.
val editText1 = findViewById(R.id.editText)
val intNum = editText1.text.toString().toInt()
I had the same problem myself. I'm not sure if you got it to work though, but what I had to was:
EditText cypherInput;
cypherInput = (EditText)findViewById(R.id.input_cipherValue);
int cypher = Integer.parseInt(cypherInput.getText().toString());
The third line of code caused the app to crash without using the .getText() before the .toString().
Just for reference, here is my XML:
<EditText
android:id="@+id/input_cipherValue"
android:inputType="number"
android:layout_width="match_parent"
android:layout_height="wrap_content" />