【发布时间】:2016-11-25 18:22:44
【问题描述】:
所以我基本上有这个问题。我试图通过蓝牙与 arduino 通信,一切正常,将数据从主要活动发送到 arduino,直到我尝试将数据从我的片段传输到 arduino,我在 logcat 中抛出一个错误:
**java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.administradora.prueba.MainActivity$ConnectedThread.write(java.lang.String)' on a null object reference**
这里是用于通信的 ConnectedThread 类......
public class ConnectedThread extends Thread {
private final InputStream mmInStream;
private final OutputStream mmOutStream;
//creation of the connect thread
public ConnectedThread(BluetoothSocket socket) {
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
//Create I/O streams for connection
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[256];
int bytes;
// Keep looping to listen for received messages
while (true) {
try {
bytes = mmInStream.read(buffer); //read bytes from input buffer
String readMessage = new String(buffer, 0, bytes);
// Send the obtained bytes to the UI Activity via handler
bluetoothIn.obtainMessage(handlerState, bytes, -1, readMessage).sendToTarget();
} catch (IOException e) {
break;
}
}
}
//write method
public void write(String input) {
byte[] msgBuffer = input.getBytes(); //converts entered String into bytes
try {
mmOutStream.write(msgBuffer); //write bytes over BT connection via outstream
} catch (IOException e) {
//if you cannot write, close the application
Toast.makeText(getBaseContext(), "La Conexión fallo", Toast.LENGTH_LONG).show();
finish();
}
}
}`
这是我尝试发送数据的片段 java 类:
public class exterior extends Fragment {
public MainActivity.ConnectedThread mConnectedThread;
public exterior() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v=inflater.inflate(R.layout.fragment_exterior,container,false);
ToggleButton garage,lucext;
garage=(ToggleButton)v.findViewById(R.id.garage);
garage.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if(isChecked){
mConnectedThread.write("7");
Toast.makeText(getActivity(),"On",Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getActivity(),"Off",Toast.LENGTH_SHORT).show();
}
}
});
return v;
}
}
(下面是我添加的试图修复错误的行,但似乎没有多大作用)***
public MainActivity.ConnectedThread mConnectedThread;
希望有人知道如何解决,谢谢大家。
【问题讨论】:
-
你永远不会为 mConnectedThread 分配任何东西
-
我应该分配什么?请帮帮我
-
您应该将
mConnectedThread分配给片段内的new ConnectedThread。 Activity 的值不共享>,除非您明确设置它。 -
如何设置?让我的片段使用 mConnectedthread?我想从片段中包含的按钮发送数据,但它一直给我一个错误
-
这是唯一的问题,我不能在我的片段人中使用 mConnectedThread,write()
标签: android android-fragments nullpointerexception android-bluetooth