Search code examples
androidcasting

Throws exception while Type casting from String to Int.


I have no idea what is going wrong here. Code Snippet

       b1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                String s1=SpinnerObj.getSelectedItem().toString();
                String n1=s1.substring(s1.indexOf("Rs")+2,s1.length()-1);
                int ns1=Integer.parseInt(String.valueOf(n1));//Couldnt cast and throws Exception
                Toast.makeText(getBaseContext(),""+ns1,Toast.LENGTH_LONG).show();
                Intent i = new Intent(getBaseContext(),OrderPlaced.class);
                startActivity(i);
            }
                catch (NumberFormatException nfe) {
                Toast.makeText(getBaseContext(), "gg", Toast.LENGTH_LONG).show();
            }
        }});

here i m trying to Type cast the String getting from Spinner to integer for computaions.


Solution

  • IMO you are taking incorrect first index of substring try below code

      String test = "Havells fan(Rs 900)";
            String n1=test.substring(test.indexOf("Rs")+3,test.length()-1);\\ use +3 instead of +2
            int ns1 = Integer.parseInt(String.valueOf(n1));
            Toast.makeText(getBaseContext(),""+ns1,Toast.LENGTH_LONG).show();