1

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.

5
  • what value is getting in a n1? Commented Sep 8, 2017 at 7:52
  • 1
    add error logcat ... Commented Sep 8, 2017 at 7:53
  • Converting String to int is sometimes not possible when it has more than integers.It will throw exception.Try to use use String value and check once Commented Sep 8, 2017 at 8:04
  • Be sure there is no space or anyother string value in your n1 string, It must contains only numeric value. OR may be n1 value is null. Post logcat and your strings too to get more clear idea. Commented Sep 8, 2017 at 8:04
  • i have spinner value as "Havells fan(Rs 900)". and m getting 900 in n1. Commented Sep 8, 2017 at 8:05

3 Answers 3

3

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();
Sign up to request clarification or add additional context in comments.

Comments

0

Based on the string you gave in comments: Havells fan(Rs 900) you include a whitespace in your string while computing the starting index for the number because s1.indexOf("Rs")+2(this computation will give 14) will point to the whitespace (index 14), not to 9(index 15). For a proposed a solution, you can use any of the existing answers either trimming the string (n1.trim()) or counting the space char when you compute the starting index(s1.indexOf("Rs")+3).

Comments

-1

maybe the string has a space. you should use n1.trim()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.