有谁能告诉我如何解决这个错误?我正在尝试创建和应用程序,当我点击切换按钮时,它将向计算机(UDP测试工具)发送一个字母或数字。 sendData(mBytes [0])发生错误; connectSocket(" 192.168.0.100&#34);
package com.example.ledgo;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;
import android.widget.ToggleButton;
public class MainActivity extends Activity {
ToggleButton tgbutton;
private byte[] mBytes = new byte[1];
private DatagramSocket mSocket;
private Toast mToast;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tgbutton = (ToggleButton) findViewById(R.id.toggleButton1);
tgbutton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (tgbutton.isChecked()){
mBytes[0] = (byte) (0);
sendData(mBytes[0]);
connectSocket("192.168.0.100");
}
else {
mBytes[1] = (byte) (1);
sendData(mBytes[1]);
connectSocket("192.168.0.100");
}
}
});
}
private void sendData(byte[] byteData){
if(mSocket == null) return;
int dataLen = byteData.length;
DatagramPacket dPacket = new DatagramPacket(byteData, dataLen);
try{
mSocket.send(dPacket);
try {
Thread.sleep(25);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}catch(IOException e){
mToast.setText("send: " + e.toString());
mToast.show();
}
}
private void connectSocket(String ip){
InetSocketAddress mAddr = new InetSocketAddress(ip ,2390);
try {mSocket = new DatagramSocket();}
catch(SocketException E){
mToast.setText("new socket: " + E.toString());
mToast.show();
};
try {mSocket.connect(mAddr);}
catch(SocketException connectE){
mToast.setText("connect: " + connectE.toString());
mToast.show();
}
}
}
答案 0 :(得分:0)
您将一个字节作为参数传递给sendData(byte[] byteData)
。
尝试将代码更改为:
if (tgbutton.isChecked()){
mBytes[0] = (byte) (0);
sendData(mBytes);
connectSocket("192.168.0.100");
}
else {
mBytes[0] = (byte) (1); //Your code actually was mBytes[1] = (byte)(1); which is invalid since you declared mBytes as an array with size 1 only.
sendData(mBytes);
connectSocket("192.168.0.100");
}
或简单地说,将sendData
和connectSocket
电话移到外面,
if (tgbutton.isChecked()){
mBytes[0] = (byte) (0);
}
else {
mBytes[0] = (byte) (1);
}
sendData(mBytes);
connectSocket("192.168.0.100");
我仍然认为你应该首先致电connectSocket
,但这完全取决于你的实施。