Search code examples
javaandroidnumberformatexception

Android NumberFormatException when parsing EditText


I'm writing an app that takes in an input from the AddBook class, allows it to be displayed in a List, and then allows the user to Search for their book. To this end, I'm creating a temporary EditText, binding it to the box where the user actually enters their search value, then (after ensuring that it is not empty) I compare what they've entered for the ISBN number with the ISBN numbers of each entry in the arrayList of <Book> custom objects, the list being named books.

Problem is, when I try to parse the EditText into an Int, it doesn't seem to work. I first tried using toString() on the EditText, then using Integer.parseInt() on the result of that method, but it hasn't worked out, as the conversion is seemingly unsuccessful;

All of the resources are in place and the code compiles properly, so those aren't the problems here.

  EditText myEdTx = (EditText) findViewById(R.id.bookName);

    if(myEdTx.getText().equals("")){Toast toast = Toast.makeText(this, "Please enter something for us to work with!", Toast.LENGTH_SHORT);
    toast.show();}
    else{
    //resume here
    for(int i=0; i<books.size(); i++)
    {
    Book tBook =  new Book(i, null, null);  tBook = books.get(i); String s=myEdTx.toString(); 
    int tInt = Integer.parseInt(s);`

Solution

  • To get the string representation of an EditText's content, use:

    String s = myEdTx.getText().toString();
    

    Using toString() directly on the EditText gives you something like:

    android.widget.EditText{40d31450 VFED..CL ......I. 0,0-0,0}
    

    ...which is clearly not what you want here.