将String转换为word并将其发送到textView

时间:2015-04-13 20:44:56

标签: android textview

public void beginListenForData() {

     Thread workerThread = new Thread(new Runnable() {
          int readBufferPosition = 0;
          byte[] readBuffer = new byte[1024];
          boolean stopWorker = false;
          Handler handler = new Handler(); 

          public void run() {

               while(!Thread.currentThread().isInterrupted() && !stopWorker) {

                   try {      
                        int bytesAvailable = mmInStream.available();            
                        if(bytesAvailable > 0) {
                        byte[] packetBytes = new byte[bytesAvailable];
                        mmInStream.read(packetBytes);
                        for(int i=0;i<bytesAvailable;i++) {
                            Thread.sleep(500);
                            byte b = packetBytes[i];                                        

                              readBuffer[readBufferPosition++] = b;
                              byte[] encodedBytes = new byte[readBufferPosition];
                              System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
                              data = new String(encodedBytes, "US-ASCII");
                              readBufferPosition = 0;

                              handler.post(new Runnable() {
                                   public void run() {

                                       System.out.println(data);
                                       getData.setTextView(data);//not working

                                       Toast.makeText(MainActivity.this, data, Toast.LENGTH_LONG).show();
                                   }

                              });                                    
                        }
                   }
              }catch (IOException ex) {
                   stopWorker = true;
                   break;
              }

                   catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

         }
    }

});

所以我收到了一封LogCat给我看的好信:

  • 04-13 23:36:57.202:I / System.out(25711):J
  • 04-13 23:36:57.212:I / System.out(25711):O
  • 04-13 23:36:57.702:I / System.out(25711):N
  • 04-13 23:36:58.202:I / System.out(25711):A
  • 04-13 23:36:58.712:I / System.out(25711):S

    如何将这些字母写成一个单词:JONAS并在textView上显示它?

1 个答案:

答案 0 :(得分:0)

一些事情:

首先,创建一个类变量,所以

private String text;

然后,在内部运行中,每次都将数据添加到文本上,所以

public void run() {
    text += data;

这将添加到整个字符串。然后,最后,要使TextView显示此信息,首先需要获取textView。

TextView tv = (TextView) findViewById(R.id./*id of your textview*/);
tv.setText(text);

这应该都在你的run方法中。

如果您对此工作原理有任何疑问,请发表评论。