Question

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);`
Was it helpful?

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.

OTHER TIPS

You assume the user inputs a number into the text field, but that is unsafe, as you only get a string text (which theoretically can contain non-numbers as well). When I remember correctly, you can adjust a text field in android where a user only can input numbers, which should suit you more.

NumberFormatException occurs when Integer.parse() is unable to parse a String as integer, so, its better to Handle this exception.

   String s = myEdTx.getText().toString();
    try {
         int tInt = Integer.parseInt(s);
     } catch( NumberFormatException ex ) {
       //do something if s is not a number, maybe defining a default value.
       int tInt = 0;
     }

So the current String here you are trying to parse is with white space in the line and integer class unable to parse that white space. So use following code.

String s=myEdTx.getText().toString();     
int tInt = Integer.parseInt(s.trim());
String s = myEdtx.getText().toString().trim();

int iInt = Integer.parseInt(s);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top