Click here to Skip to main content
15,893,663 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
i have this very silly question. i have a code that when i enter a value in edittext it will split the string checking some condition. if the condition is false i need to clear the edittext. when i enter a wrong information into the edittext i get force close error.

Java
public void afterTextChanged(Editable s) {
               String iGTIN = pscan.getText().toString();
               if (iGTIN.length() == 40 || iGTIN.contains("(01)") && iGTIN.contains("(21)")) {
                   String pGtin = iGTIN.substring(4, 18);
                   String sSerialNo = iGTIN.substring(22, 32);
                   gtin.setText(pGtin);
                   serial.setText(sSerialNo);
                   pscan.setText(" ");



               }
               else
               {
                   error.setText("Not a Valid Primary Scan Code..Please check and scan again");
                   pscan.setText("");
               }
Posted
Comments
Sergey Alexandrovich Kryukov 3-Jul-15 0:43am    
Please use the debugger. I can see a number of absurdities in your code. I bet getText() already returns String, so why calling toString()? Why such a strange condition in "if"? What exactly are you trying to achieve?
Why hard-coding 40, 4, 18? This is not programming, is something opposite...
—SA
Rahul Ramakrishnan 3-Jul-15 0:48am    
i need to check if the length is 40 , and it should contain (01) and (21)
is there any other way to acheive it?

1 solution

This is exactly the same issue as how to split numbers using substring[^], which I already answered. If you want to verify parts of the content as it is entered then you should not make assumptions about the length of substrings, or where they occur. In the above case if the user enters:
foo(01)abc(21)bar

your code will crash, because you are trying to extract a substring beyond the limit of the entered data.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900