单击下面的button2
活动中的GamesFragment
时,我的应用程序崩溃并给我一个错误。我希望能够通过在其他writeData
活动中调用TopRated
函数来单击按钮并将数据发送到蓝牙设备。
public class GamesFragment extends Fragment {
public Button chaser;
private String dataToSend;
View rootView;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
chaser = (Button) rootView.findViewById(R.id.button2);
chaser.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.button2:{
dataToSend = "on";
TopRatedFragment top = new TopRatedFragment();
top.writeData(dataToSend);
}
}
}
});
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_games, container, false);
return rootView;
}
}
/******* This is where the writedata function is***/
public class TopRatedFragment extends Fragment {
private ArrayAdapter<String> mNewDevicesArrayAdapter;
private OutputStream outStream = null;
private String dataToSend;
private BluetoothAdapter bluetoothAdapter;
public static String EXTRA_DEVICE_ADDRESS = "device_address";
private BluetoothSocket btSocket = null;
public static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
public Button connect;
public Button disconnect;
View rootView;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
final Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
// Initialize array adapters. One for already paired devices and
// one for newly discovered devices
final ArrayAdapter<String> pairedDevicesArrayAdapter =
new ArrayAdapter<String>(getActivity(), R.layout.device_name);
mNewDevicesArrayAdapter = new ArrayAdapter<String>(getActivity(), R.layout.device_name);
// Register for broadcasts when a device is discovered
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
((MainActivity)getActivity()).registerReceiver(this.mReceiver,filter);
// Find and set up the ListView for paired devices
ListView pairedListView = (ListView) getActivity().findViewById(R.id.listView);
pairedListView.setAdapter(pairedDevicesArrayAdapter);
pairedListView.setOnItemClickListener(mDeviceClickListener);
// Register for broadcasts when discovery has finished
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
((MainActivity)getActivity()).registerReceiver(this.mReceiver, filter);
connect = (Button) rootView.findViewById(R.id.button);
connect.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.button:{
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, 1);
doDiscovery();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
pairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
}
}
}
}
});
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_top_rated, container, false);
return rootView;
}
private void doDiscovery() {
//Log.d(TAG, "doDiscovery()");
// Indicate scanning in the title
//setProgressBarIndeterminateVisibility(true);
// If we're already discovering, stop it
if (bluetoothAdapter.isDiscovering()) {
bluetoothAdapter.cancelDiscovery();
}
// Request discover from BluetoothAdapter
bluetoothAdapter.startDiscovery();
}
@Override
public void onDestroy() {
super.onDestroy();
// Make sure we're not doing discovery anymore
if (bluetoothAdapter!= null) {
bluetoothAdapter.cancelDiscovery();
}
// Unregister broadcast listeners
//this.unregisterReceiver(mReceiver);
try {
btSocket.close();
} catch (IOException e) {
}
}
private AdapterView.OnItemClickListener mDeviceClickListener
= new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
// Cancel discovery because it's costly and we're about to connect
bluetoothAdapter.cancelDiscovery();
// Get the device MAC address, which is the last 17 chars in the View
String info = ((TextView) v).getText().toString();
String address = info.substring(info.length() - 17);
// Create the result Intent and include the MAC address
Intent intent = new Intent();
intent.putExtra(EXTRA_DEVICE_ADDRESS, address);
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address);
try {
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
btSocket.connect();
Toast.makeText(getActivity(),"Connected " + device.getName() ,Toast.LENGTH_SHORT).show();
//Log.d(TAG, "Connexion r�ussie !!");
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
//Log.d(TAG, "Impossible de fermer la connexion.");
}
//Log.d(TAG, "Cr�ation de socket �chou�e.");
}
// Set result and finish this Activity
//setResult(Activity.RESULT_OK, intent);
//finish();
}
};
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// If it's already paired, skip it, because it's been listed already
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
// When discovery is finished, change the Activity title
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
//setProgressBarIndeterminateVisibility(false);
if (mNewDevicesArrayAdapter.getCount() == 0) {
//do nothing
}
}
}
};
protected void writeData(String data) {
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
//Log.d(TAG, "Bug AVANT l'envoie.", e);
}
String message = data;
byte[] msgBuffer = message.getBytes();
try {
outStream.write(msgBuffer);
} catch (IOException e) {
//Log.d(TAG, "Bug DURANT l'envoie.", e);
}
}
}
这是我得到的错误:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.OutputStream android.bluetooth.BluetoothSocket.getOutputStream()' on a null object reference
at info.androidhive.tabsswipe.TopRatedFragment.writeData(TopRatedFragment.java:207)
at info.androidhive.tabsswipe.GamesFragment$1.onClick(GamesFragment.java:44)
at android.view.View.performClick(View.java:5197)
at android.view.View$PerformClick.run(View.java:20926)
最佳答案
您在TopRatedFragment中的outStream
为null,并且永远不会初始化。您必须先初始化outStream,然后才能在写入数据中使用它。顺便说一句,永远不要使用这样的片段-最好的解决方案是将writeData方法移动到另一个类,并在构造函数或此方法中初始化outStream。