Reputation: 295
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.
Upvotes: 1
Views: 690
Reputation: 2643
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
).
Upvotes: 0
Reputation: 3100
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();
Upvotes: 3