1

I am receiving some data from an USB component, component will send me continuous data, if I have received the data I have to stop reading the data myself and the component will not stop sending data, I am trying to break the loop if I received some key I tried using boolean, but it is not terminating the loop.

 boolean shouldBreak = false;

    switch(msg.what)
    {               

    case USBAccessoryWhat:
    switch(((USBAccessoryManagerMessage)msg.obj).type) {
    case READ:
        if(accessoryManager.isConnected() == false) {
            return;
        }
        while(true) {
            if(accessoryManager.available() < 2) {
                break;
            }

            switch(commandPacket[0]){
                case 0:
                    test = Integer.toString(commandPacket[0]) + ", " + Integer.toString(commandPacket[1]);
                    Test_one(test);
                break;
                case 1:
                    test = Integer.toString(commandPacket[0]) + ", " + Integer.toString(commandPacket[1]);
                    Test_one(test);
                break;
                case 2:
                    test = Integer.toString(commandPacket[0]) + ", " + Integer.toString(commandPacket[1]);
                    Test_one(test);
                    shouldBreak = true; // have to break here
                break;
                default:
                break;
            } 
             if (shouldBreak) break; //To break this while
        }
        break;

    }
    break;
    }
Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111

3 Answers3

2

Try replacing while(true) with while(!shouldBreak) as a break statement only breaks out of the inner-most loop / switch / while etc.

For more details see e.g. Difference between break and continue statement

Erich Schreiner
  • 2,038
  • 1
  • 14
  • 24
1

Just use your flag in the while check:

switch ()
  case  
    bool shouldLoop = true
    while (shouldLoop)
      switch
        case 
          if 
            shouldLoop = false
Vincent Mimoun-Prat
  • 28,208
  • 16
  • 81
  • 124
1

Try using label with the while loop as below :

label:
    While()
    {
      for()
      {
         break label;
      }
    }
Onur Akan
  • 41
  • 10