I’m trying to write my first Android app. It will take a number input by a user in an EditText field, convert it to an integer, then find the factors. I want to port this from a Java program that I wrote before. I have stubs working to the point that I have a UI, but I haven’t yet ported the code that will find the factors. I’m stuck trying to convert the EditText to an integer. If I insert either of the following lines, the program crashes in the emulator. Log.Cat says, “Caused by NumberFormatExcepion: Unable to parse ” as an integer.”
Any suggestions are appreciated.
userNumber is the name of the value taken from the EditText field, and the EditText field is also named userNumber. I don’t know if that’s bad form or not. I want to assign the value of userNumber to the integer value userInt. userInt will then be factored.
Either of these approaces will cause the problem:
userNumber = (EditText) findViewById(R.id.userNumber);
userInt = Integer.parseInt(userNumber.getText().toString());
Integer userInt = new Integer(userNumber.getText().toString());
The EditText block of XML looks like this:
<EditText
android:id="@+id/userNumber"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number" >
<requestFocus />
</EditText>
Here is the relevant code from the class:
public class AndroidFactoringActivity extends Activity {
// Instance Variables
EditText userNumber;
Button factorButton;
TextView resultsField;
int factorResults = 1;
int userInt = 0; // This comes out if using Integer userInt
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
resultsField = (TextView) findViewById(R.id.resultsField);
factorButton = (Button) findViewById(R.id.factorButton);
userNumber = (EditText) findViewById(R.id.userNumber);
// userNumber is also the name of the EditText field.
// userInt = Integer.parseInt(userNumber.getText().toString());
// Integer userInt = new Integer(userNumber.getText().toString());
resultsField.append("\n" + String.valueOf(userInt));
//Later, this will be factorResults, not userInt.
// Right now, I just want it to put something on the screen.
}
}
You’re trying to parse the int in your
onCreatemethod, which occurs before the user has a chance to enter anything into theEditText. Hence the exception from trying to parse an empty string.You’ll have to either make a button to press, which will then parse the int out of the
EditText, or attach a listener to theEditTextthat will parse it when something is typed into it.