gpt4 book ai didi

java - 在Android中转换为缓冲区

转载 作者:行者123 更新时间:2023-12-01 10:59:15 24 4
gpt4 key购买 nike

我正在尝试使用套接字将文本从客户端传递到服务器,我将从 Android Studio 中的 EditText 获取该文本,但我不知道如何将此文本传递到缓冲区,以便我可以将其传递到服务器并当我尝试将来自 View 的文本转换为字符串然后进行缓冲时,它给我一个错误,说我无法从可编辑文本转换为字符串

       send = (Button) findViewById(R.id.send);
message =(EditText) findViewById(R.id.message);

发送是获取消息并发送的按钮,消息是我要发送的文本。

最佳答案

Java 7/Android API 19

message.getText().toString().getBytes(StandardCharsets.UTF_8);

如果不可用,您需要执行此操作

message.getText().toString().getBytes(Charset.forName("UTF-8"));

如果 UTF-8 不存在,第二个将抛出 RuntimeException。

<小时/>

public Editable getText ()来自android.widget.EditText

Return the text the TextView is displaying. If setText() was called with an argument of BufferType.SPANNABLE or BufferType.EDITABLE, you can cast the return value from this method to Spannable or Editable, respectively. Note: The content of the return value should not be modified. If you want a modifiable one, you should make your own copy first.

此方法返回android.text.Editable它实现了 java.lang.CharSequence它覆盖 java.lang.Object.toString()返回对象的字符串表示形式。一旦你有了字符串表示,你就可以调用 java.lang.String.getBytes()或其任何重载,将其转换为所需字符集中的字节。上面的这一行代码只是在一行中完成所有操作并返回结果字节数组。

关于java - 在Android中转换为缓冲区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33451703/

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