在arrayadapter中打印备用项目

时间:2014-09-04 17:44:20

标签: java android bluetooth

代码段来自BluetoothChat代码。我已将其修改为仅在ListView中显示收到的备用值。我不太确定ArrayAdapter的工作原理。有人可以解释一下代码中的错误是什么吗?

private ArrayAdapter<String> mConversationArrayAdapter; 



private final Handler mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {

                case MESSAGE_READ:

                    byte[] readBuf = (byte[]) msg.obj;

                    String readMessage = new String(readBuf, 0, msg.arg1);

                    for(int i = 0; i<readBuf.length; i+=2) {                                  

                          mConversationArrayAdapter.add(readMessage);

                    }           

                    break;

                case MESSAGE_WRITE  .....

                }
     }                      

1 个答案:

答案 0 :(得分:1)

您跳过邮件的逻辑错误。每条消息都会调用handleMessage一次。您需要有一个标志,显示以前的信息是否已打印。

 private final Handler mHandler = new Handler() {
                boolean flag=true;
                @Override
                public void handleMessage(Message msg) {
                    switch (msg.what) {

                    case MESSAGE_READ:
                       if (flag) {

                           byte[] readBuf = (byte[]) msg.obj;

                           String readMessage = new String(readBuf, 0, msg.arg1);

                           //you don't need loop
                           //for(int i = 0; i<readBuf.length; i+=2) //{                                  

                              mConversationArrayAdapter.add(readMessage);

                          //}           

                        } 
                        flag = !flag;

                        break;

                    case MESSAGE_WRITE  .....

                    }
         } 

请注意,这不是线程安全的。