我有一个例子,我尝试创建一个使用套接字通过wifi发送消息的Android应用程序。下面的代码编译,但在执行发送按钮onclicklistener中的代码时引发NullPointerException。我希望ClientThread类中的代码实际上会使MainActivity的字段“socket”指向新打开的Socket,但是当我尝试打开DataOutPutStream时,'socket'似乎仍然指向null。为什么我的内部类的实例不能改变字段套接字指向的内容?
public class MainActivity extends AppCompatActivity {
Socket socket;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText ipText = findViewById(R.id.ipText);
final EditText msgText = findViewById(R.id.msgText);
Button sendbtn = findViewById(R.id.button);
Button ipbtn = findViewById(R.id.ipbtn);
sendbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
dos.writeUTF(msgText.getText().toString());
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
});
ipbtn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view){
new Thread(new ClientThread(ipText.getText().toString())).start();
}
});
}
class ClientThread implements Runnable{
String ip;
private ClientThread(String address){
ip = address;
}
@Override
public void run(){
try {
socket = new Socket(ip, 80);
} catch (UnknownHostException e1){
e1.printStackTrace();
} catch (IOException e1){
e1.printStackTrace();
}
}
}
}
运行时我一定要先按ipbtn,所以ClientThread.run()中的代码应该已经运行了。