setText 使我的应用程序崩溃 - inStream.read



我对setText( TextView)有问题。

view        = EgridView.getChildAt( iterator );
parameter   = (TextView) view.findViewById( R.id.gridItemParameter );

if( modbus.readAvailable() > 0 ){
    if( !((data = modbus.readData()).equals("")) ){


Log.i("-------------TEST-----------", data); // <-------- wrok
//Toast.makeText(getApplicationContext(), data , Toast.LENGTH_LONG).show(); <----- work
// parameter.setText( "test" ); <----------- work
parameter.setText( data ); // <--------- crash


    }
}

为什么 **parameter.setText( data ); 为什么我的应用程序崩溃?


更多代码:

public int readAvailable(){
    try{
        return inStream.available();
    }  catch( Exception e ){
        return 0;
    }
}
public String readData(){
    try{
        if( isConnected == true && socket.isConnected() && inStream != null ){
            int     i;
            int     oneByte;
            byte    byteArray[] = new byte[ 100 ];
            int     available   = inStream.available();
            String  data        = "";                                               
            if( available > 0 ){
                inStream.read( byteArray );
                for( i = 0; i < available; i++ ){
                    oneByte  = byteArray[ i ] & 0xff;
                    data = data.concat( Integer.toString( oneByte ) + " " );
                }                                                                               
                return data; // <-----
            } else {
                    return "";
            }
        } else {
            errorText = "no communication";
            return "";
        }
    } catch( Exception e ){
        errorText = e.getMessage();
        return "";
    }
}

如果在readData()中我写返回"test";然后工作

如果在 readData() 中,我写返回 byteArray.toString(); 然后工作

如果在 readData() 中我写 for( i = 0; i <10; i++ ){ 则工作

如果在 readData() 中我写 for( i = 0; i <11; i++ ){崩溃

在这种情况下,int 可用 = 13。

我的问题对我来说是不合逻辑的。请指教。

谢谢所有答案

只能在 UI

线程上修改 UI 元素,例如文本视图。

从 android 文档中查看此链接:http://developer.android.com/reference/android/app/Activity.html#runOnUiThread(java.lang.Runnable)

我猜你的最终字符串数据

使数据无法填充

所以你的变量数据仍然为空

并且您尝试设置文本(空),这就是为什么..

尝试将最终字符串数据更改为字符串数据 = "

如果您的读取数据函数有问题

试试这个解决方案

            InputStream is = conn.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            StringBuilder sb = new StringBuilder();
            String line = null;
            try {
                while ((line = reader.readLine()) != null) {
                    sb.append((line + "n"));
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    is.close(); 
                } catch (IOException e) {
                    e.printStackTrace(); 
                }
            }
            Toast.makeText(con, "Return Nya = " +sb.toString(), 0).show();
            Log.v("TEST" , "Return Nya = " + sb.toString());
            is.close();

最新更新