简体   繁体   中英

how to convert from string to integer

I have a problem that made me confused, i want to use the value of EditText and convert it to int, when launching the activity it displays on logcat "invalid int" and i make the input value for the editText is 9 digits! could you help me in finding the problem

this is my code:

     String texti =  numberi.getText().toString();
     int x = Integer.parseInt(texti);

你必须保存很long

long x = Long.parseLong(texti);

If your only objective is to allow user to input numbers into EditText.Then use

android:inputType="number"

And then Integer.parseInt(editText.getText().toString());

u said that u have wrote that in onCreate() . so u have to check first, is the text is null or not:

String texti =  numberi.getText().toString();
long x;
if(texti.trim().length() > 0)
  x = Long.parseLong(texti);

texti的整数可能大于Integer.MAX_VALUE值,因此请使用Long

long x = Long.parseLong(texti.trim());

What you have code is correct but for better way use this,

  String texti =  numberi.getText().toString();
  int x = Integer.parseInt(texti.trim());  // Trim the extra spaces, if any.

Always have habbit to trim() when converting to Numeric format, This will prevent from NumberFormatException

将字符串解析为整数:

    Integer.parseInt(<Your EditText>.getText().toString());

Ideally, if your EditText will only accept integers then you should set inputType property to either:

  • numberSigned
  • number

eg. something like this:

<EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/editTextCustomerPin"
        android:layout_marginTop="20dp"
        android:inputType="numberSigned"
        android:textSize="16dp" android:hint="@string/enterCustomerPin"
        android:layout_gravity="center_horizontal"/>

Now in your activity, you can always do:

EditText myEditText = (EditText) findViewById(R.id.editTextCustomerPin);
String editTextContent = myEditText.getText().toString();
if (editTextContent.length() > 0) {
     int num = Integer.parseInt(num);
     //Do your processing
} else {  
     //Show error message, eg. a toast or an alert dialog
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM