gpt4 book ai didi

java - 尝试显示字节值时 setText 使应用程序崩溃

转载 作者:行者123 更新时间:2023-12-01 23:28:50 24 4
gpt4 key购买 nike

我正在开发一个发送和接收数据的 Android 应用程序。在应用程序中,我有一个按钮和一些 TextView 。当我按下按钮时,将发送数据(两个字符)。并且已发送的数据将显示在两个 tekst View 中。

我对两个整数做了同样的事情,现在有效,我想对字节和字符做同样的事情,但失败了。

logcat 给出以下错误:10-28 09:27:19.338: E/AndroidRuntime(13138): android.content.res.Resources$NotFoundException: 字符串资源 ID #0x0

下面是 onClick 监听器代码:

  @Override
public void onClick(View v) {

// Control value
ArrayOutput[0] = 'B';
ArrayOutput[1] = 'B';


//Creating TextView Variable
TextView text = (TextView) findViewById(R.id.tv);

//Creating TextView Variable
TextView statustext = (TextView) findViewById(R.id.status);


//Sets the new text to TextView (runtime click event)
text.setText("You Have click the button");


// Convert string to bytes
ArrayOutput[0] = ArrayRecieved[0];
ArrayOutput[1] = ArrayRecieved[1];

final char Byte1 = (char) ArrayOutput[0];
final char Byte2 = (char) ArrayOutput[1];

final TextView Xtext = (TextView) findViewById(R.id.xtext);
final TextView Ytext = (TextView) findViewById(R.id.ytext);
Ytext.setText(Byte1);
Xtext.setText(Byte2);


try
{
statustext.setText("Sending....");
server.send(ArrayOutput);
statustext.setText("Sending succes");
}
catch (IOException e)
{
statustext.setText("Sending failed");
Log.e("microbridge", "problem sending TCP message", e);
}
}
});

有人对问题可能是什么有建议吗?欢迎任何建议!如果我需要提供更多信息,请说出来。

更新

谢谢大家的建议!对于 onclick 函数它有效!我尝试对接收功能做同样的事情。当有可用数据时,将调用此事件处理函数。

当我使用 setText 函数时,几个周期后它会使我的应用程序崩溃,在这个函数中我有三个 settext 操作。仅调用第一个(然后应用程序崩溃)。当我更改这些操作的顺序时,仍然只调用第一个操作。难道应用程序显示了第一个 settext 操作但崩溃了?我使用虚拟数据,因此当调用事件处理函数时,不会使用实际收到的数据,但应用程序在第一次操作后仍然崩溃。有人有建议吗?

另一边每秒发送一次数据。

下面是 onRecieve(事件处理程序)函数:

@Override
public void onReceive(com.example.communicationmodulebase.Client client, byte[] data)
{

Log.e(TAG, "In handler!");

//Control value
ArrayRecieved[0] = 'C';
ArrayRecieved[1] = 'B';

if (data.length < 2){
return;
}

// Set data that has been recieved in array
//ArrayRecieved[0] = data[0];
//ArrayRecieved[1] = data[1];

char Byte1 = (char) ArrayRecieved[0] ;
char Byte2 = (char) ArrayRecieved[1] ;

TextView Xtext = (TextView) findViewById(R.id.xtext);
TextView Ytext = (TextView) findViewById(R.id.ytext);
Xtext.setText(""+Byte2);
Ytext.setText(""+Byte1);

TextView textRecvStatus = (TextView) findViewById(R.id.RecvStatusText);
textRecvStatus.setText("In handler!");

}

});

最佳答案

TextView 有两种方法,例如

TextView.setText(CharSequence) and TextView.setText(int).

1) 第一个方法直接将文本分配给 TextView,该文本作为 CharSequence 传递(可以是 String、StringBuffer、Spannable...)
2) 第二个方法搜索您在资源中定义的字符串资源,并将 ID 作为参数传递。

并且您将 char 作为参数传递。此 char 类型转换为 int 并将其作为 TextView.setText(int) 调用,并使用该 int 搜索资源字符串 其值未在资源中定义的 ID。

char 类型转换为 String,如 String.valueOf(char) 并尝试一次...

关于java - 尝试显示字节值时 setText 使应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19630491/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com