gpt4 book ai didi

java - Android:DataOutputStream 上的 NullPointerException

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

我正在编写一种手机和电脑之间的聊天应用程序。为了从手机接收数据,我设置了一个套接字并将其 outputStream 放入 DataOutputStream 中,从 LinkedBlokingQueue 轮询字符串并使用writeUTF()。但由于某种原因,我在执行 dataOutputStream.writeUTF(input) 时遇到空指针异常。

代码如下:

public class txThread extends Thread{
private LinkedBlockingQueue activityQueue;
private Socket socket;
private String input;

public txThread(LinkedBlockingQueue activityQueue){
this.activityQueue = activityQueue;
socket = null;
input = null;
}

public void run(){
DataOutputStream dataOutputStream = null;
try {
socket = new Socket("192.168.1.8",1755);
Log.d("DEBUG","THREAD_TX_CONNECTED");
dataOutputStream = new DataOutputStream(socket.getOutputStream());
while(true){
input = (String) activityQueue.poll();
dataOutputStream.writeUTF(input);
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally{
if (socket != null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataOutputStream != null){
try {
dataOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return;
}
}

最佳答案

我认为您不需要 activityQueue.poll() ,如果队列中没有第一个项目,它会返回 null

Retrieves and removes the head of the queue represented by this deque (in other words, the first element of this deque), or returns null if this deque is empty.

我认为您应该在 while(true) 循环中使用 activityQueue.take() 来等待队列中出现一个项目:

Retrieves and removes the head of the queue represented by this deque (in other words, the first element of this deque), waiting if necessary until an element becomes available.

关于java - Android:DataOutputStream 上的 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10376685/

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