Converting EditText to int? (Android)

前端 未结 11 1156
深忆病人
深忆病人 2020-12-09 03:08

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         


        
相关标签:
11条回答
  • 2020-12-09 03:31

    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
    }
    
    0 讨论(0)
  • 2020-12-09 03:36

    Use Integer.parseInt, and make sure you catch the NumberFormatException that it throws if the input is not an integer.

    0 讨论(0)
  • 2020-12-09 03:41

    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.

    0 讨论(0)
  • 2020-12-09 03:41

    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();
    
    0 讨论(0)
  • 2020-12-09 03:44

    In Kotlin, you can do this.

    val editText1 = findViewById(R.id.editText)
    val intNum = editText1.text.toString().toInt()
    
    0 讨论(0)
  • 2020-12-09 03:48

    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" />
    
    0 讨论(0)
提交回复
热议问题