从另一个线程更改UI

时间:2013-03-05 09:31:44

标签: android multithreading user-interface

更新:我更新了一些日志输入,而不是你的帮助。

我正在应用以下代码:

@Override
public void run() {

     byte[] bytes = null;

     int TIMEOUT = 5000;

     int status = connection.bulkTransfer(ep, bytes, ep.getMaxPacketSize(), TIMEOUT);

     Log.d(TAG, "status: " + status);

     write_to_screen( bytes );

}

public void write_to_screen( byte[] bytes  ) {

    Log.d(TAG, "bytes: " + bytes);

    String str_non_final = null;

    try {

        str_non_final = new String( bytes, "UTF-8");
        Log.d(TAG, "str_non_final : " + str_non_final );

    } catch (UnsupportedEncodingException e) {

        e.printStackTrace();

    }   

    final String str = str_non_final;

    Log.d(TAG, "str: " + str);

    runOnUiThread(new Runnable() {@Override public void run()
    {
       textView7.setText( str );
       Log.d(TAG, "UI updated");
    }
    });

}   

logcat的结果如下:

D / EthernetActivity(15721):打开SUCCESS

D / EthernetActivity(15721):状态:-1

D / EthernetActivity(15721):bytes:null

所以我觉得问题在于“str_non_final = new String(bytes,”UTF-8“);”。这有什么问题?

1 个答案:

答案 0 :(得分:1)

在此声明中

str_non_final = new String( bytes, "UTF-8");

您正在使用byte,并且在logcat中打印为null。所以它会抛出NullPointerException而你的捕获只能处理UnsupportedEncodingException

确保bytes在调用

之前不应为null
write_to_screen( bytes );