简体   繁体   中英

Printing alternate items in an arrayadapter

The code snippet is from BluetoothChat code. I have modified it to display only alternate values received, in the ListView. I am not quite sure with the working of an ArrayAdapter. Can somebody explain me what is the error in the code?

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  .....

                }
     }                      

Your logic for skipping messages is in the wrong place. The handleMessage is called once for every message. You need to have a flag which will show if previous message was printed.

 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  .....

                    }
         } 

Note, that this is not thread safe.

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