如何将接收到的数字两两分开

时间:2019-10-27 18:38:57

标签: java android arduino

您好,亲爱的stackoverflow社区, 我正在研究一个从arduino模块接收信息并将其显示为图表的项目。 问题是我有5个元素(温度,湿度等),并且我拥有的代码一次只能接收一个数字(例如:2838752458),如示例中所示,该数字有10位数字来自arduino,我想将它们一分为二,因此每两个元素都需要一个元素。 您可能会问为什么我不设置处理程序,以便我可以在一个分开的时间接收每个两个数字,但是我已经尝试过了,这给了我封闭的应用程序错误,因为我一次只能收到一个数字的代码。 / p>

  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) {


                }
            }
        }
    }

问题:如何将10位数字二一二分开并将它们加到分开的整数中,以便可以将其传递给图表活动?请给我举一个“ 1234567890”这个数字的例子。

here是我到目前为止创建的图表的输出。

谢谢!

2 个答案:

答案 0 :(得分:0)

首先,请确保您的数字位数(例如:1234567890)始终可被2整除。嗯,那么我为您准备了一点技巧。

首先,将digits转换为String并在步骤2中运行for-loop,然后仅在 i-th 使用循环到数组中产生每个字符串的第(i + 1)个位置。最后,您只需将数组中的String解析为图表中的int值,就可以从数组列表中读取项目并将其发送到图表中。这是我使用 Kotlin 编写的示例代码(但如果需要,我可以将其转换为 Java 代码)。如果您遇到任何问题,请随时发表评论。

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)
}

快乐编码!

答案 1 :(得分:0)

这似乎可以满足您的要求:

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));
       } 

    }
}

并输出:

12
34
56
78
90