简体   繁体   中英

How to separate received digits two by two

Hello dear stackoverflow community, I'm working on a project which receives information from an arduino module and shows it as a chart. The problem is i have 5 elements ( temperature,humidity, etc... ) and the code i have can only receive one number at a time ( for example: 2838752458 ), as you see in the example the number has 10 digits which comes from arduino and i want to separate them two by two so each two of them goes for one element. you might ask why i don't set a handler so i can receive each two number at a separated time but i've tried that and it gives me closed application error because the code i have only can receive one number at a time.

  public class Analysies extends AppCompatActivity {                
        Handler h;        
        String tekrar = "";
        String dama = "";
        String qaza = "";
        String faaliat = "";
        String rotobat = "";
        private OutputStream outStream = null;
        private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

        private static String address = "00:21:13:00:02:5B";

        final int RECIEVE_MESSAGE = 1;        // Status  for Handler
        private BluetoothAdapter btAdapter = null;
        private BluetoothSocket btSocket = null;
        private StringBuilder sb = new StringBuilder();

        private Analysies.ConnectedThread mConnectedThread;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_analysies);

            gifImageView = (GifImageView) findViewById(R.id.gifBro);
            txt1 = (GifImageView) findViewById(R.id.afterAutotxt);


            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {        
                    txt1.animate().alpha(1f).setDuration(2000);
                }
            }, 1000);        
            h = new Handler() {
                public void handleMessage(android.os.Message msg) {
                    switch (msg.what) {
                        case RECIEVE_MESSAGE:                                                   
                            // if receive massage
                            byte[] readBuf = (byte[]) msg.obj;
                            String strIncom = new 
                            String(readBuf, 0, msg.arg1);                 
                            // create string from bytes array
                            sb.append(strIncom);                                                
                            // append string
                            int endOfLineIndex = sb.indexOf("\r\n");                            
                            // determine the end-of-line
                            if (endOfLineIndex > 0) {                                            
                            // if end-of-line,
                                String sbprint = sb.substring(0, endOfLineIndex);                // extract string
                                sb.delete(0, sb.length());
                                sbprint.getBytes().toString();


////////////////////////////// HERE IS WHERE I CAN RECEIVE INFORMATION FROM ARDUINO ///////////////////////////////

                            }
                            //Log.d(TAG, "...String:"+ sb.toString() +  "Byte:" + msg.arg1 + "...");
    //                        Toast.makeText(CommunicationAuto.this, "String:" + sb.toString() , Toast.LENGTH_LONG).show();
                            break;
                    }
                }

                ;
            };

            btAdapter = BluetoothAdapter.getDefaultAdapter();       // get Bluetooth adapter
            checkBTState();
       }

        private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
            if(Build.VERSION.SDK_INT >= 10){
                try {
                    final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[] { UUID.class });
                    return (BluetoothSocket) m.invoke(device, MY_UUID);
                } catch (Exception e) {
    //                Toast.makeText(getApplicationContext(), "Could not Insecure", Toast.LENGTH_SHORT).show();
                }
            }
            return  device.createRfcommSocketToServiceRecord(MY_UUID);
        }

        @Override
        public void onResume() {
            super.onResume();

            // Set up a pointer to the remote node using it's address.
            BluetoothDevice device = btAdapter.getRemoteDevice(address);

            // Two things are needed to make a connection:
            //   A MAC address, which we got above.
            //   A Service ID or UUID.  In this case we are using the
            //     UUID for SPP.

            try {
                btSocket = createBluetoothSocket(device);
            } catch (IOException e) {
    //            Toast.makeText(getApplicationContext(), "Socket failed", Toast.LENGTH_SHORT).show();
            }

            // Discovery is resource intensive.  Make sure it isn't going on
            // when you attempt to connect and pass your message.
            btAdapter.cancelDiscovery();

            // Establish the connection.  This will block until it connects.
    //        Toast.makeText(getApplicationContext(), "Connecting", Toast.LENGTH_SHORT).show();
            try {
                btSocket.connect();
    //            Toast.makeText(getApplicationContext(), "Connecting ok!", Toast.LENGTH_SHORT).show();
            } catch (IOException e) {
                try {
                    btSocket.close();
                } catch (IOException e2) {
    //                errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
                }
            }

            // Create a data stream so we can talk to server.


            mConnectedThread = new Analysies.ConnectedThread(btSocket);
            mConnectedThread.start();
        }

        @Override
        public void onPause() {
            super.onPause();        
            try     {
                btSocket.close();
            } catch (IOException e2) {
    //            errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
            }
        }

        private void checkBTState() {
            // Check for Bluetooth support and then check to make sure it is turned on
            // Emulator doesn't support Bluetooth and will return null
            if(btAdapter==null) {


                Toast.makeText(getApplicationContext(), " Bluetooth is not supported. ", Toast.LENGTH_SHORT).show();

            } else {
                if (btAdapter.isEnabled()) {

                } else {

                   Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(enableBtIntent, 1);


                }
            }
        }

        private void errorExit(String title, String message){
            Toast.makeText(getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show();
            finish();
        }

        private class ConnectedThread extends Thread {
            private final InputStream mmInStream;
            private final OutputStream mmOutStream;

            public ConnectedThread(BluetoothSocket socket) {
                InputStream tmpIn = null;
                OutputStream tmpOut = null;

                // Get the input and output streams, using temp objects because
                // member streams are final
                try {
                    tmpIn = socket.getInputStream();
                    tmpOut = socket.getOutputStream();
                } catch (IOException e) { }

                mmInStream = tmpIn;
                mmOutStream = tmpOut;
            }

            public void run() {
                byte[] buffer = new byte[256];  // buffer store for the stream
                int bytes; // bytes returned from read()

                // Keep listening to the InputStream until an exception occurs
                while (true) {
                    try {
                        // Read from the InputStream
                        bytes = mmInStream.read(buffer);        // Get number of bytes and message in "buffer"
                        h.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget();     // Send to message queue Handler
                    } catch (IOException e) {
                        break;
                    }
                }
            }

            /* Call this from the main activity to send data to the remote device */
            public void write(String message) {


                byte[] msgBuffer = message.getBytes();
                try {
                    mmOutStream.write(msgBuffer);
                } catch (IOException e) {


                }
            }
        }
    }

The question: How can i separate the 10 digit number two by two and add them to separated integers so i can pass them to the chart activity? Please give me an example for "1234567890" this number.

here is the output of the chart I created so far.

Thank you!

At first make sure the number of your digits (eg: 1234567890) always divisible by 2. Well, then I have a little hack for you.

First, convert the digits to String and run a for-loop with step 2, then just append the characters at i-th and (i+1)th position into each string producing using the loop into an array. And finally, you can just read item from the array list and send value to your chart just parsing the String into int value to your chart. Here is a sample code I did with Kotlin (but I can convert it into Java code if you need). If you face any issues, feel free to comment.

fun main() {
    val digits = 1234567890
    val arr = arrayListOf<String>()

    for (i in 0 until digits.toString().length step 2) {
        val sub = "${digits.toString()[i]}${digits.toString()[i+1]}"
        arr.add(sub)
    }
    println(arr)
}

Happy Coding!

This seems to do what you want:

import java.util.regex.*;

public class HelloWorld{


    public static void main(String []args){

       String s = "1234567890";

       String pattern = "(\\d\\d)";
       Pattern p = Pattern.compile(pattern);
       Matcher m = p.matcher(s);
       while (m.find()) {
           System.out.println(m.group(0));
       } 

    }
}

And output:

12
34
56
78
90

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM