java - Android NullPointerException 蓝牙

标签 java android android-fragments nullpointerexception android-bluetooth

当点击 button2 时,我的应用崩溃并出现错误,如下面的 GamesFragment Activity 所示。我希望能够单击按钮并通过调用其他 TopRated Activity 中的 writeData 函数将数据发送到蓝牙设备。

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,然后再使用它来写入数据。顺便说一句,永远不要使用这样的 fragment - 最好的解决方案是将 writeData 方法移动到另一个类,并在构造函数或此方法中 init outStream。

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

相关文章:

java - 反射 - 多个子类的方法缓存

android - 在 android studio 上单击推送通知后重定向到特定 Activity

Android ActionBar 选项卡 - 滑动

android - 使用 CursorLoader 在 ListFragment 中查询 SQLite 数据库的最佳实践?

android - 工具栏和抽屉导航

java - 让 Logback 不*遵循类继承*

java - 在 java 主方法之外初始化一个对象

java - 如何检查字符串是否加密?

java - Cursor isAfterLast() 在到达最后一行时返回 true

android - ViewTreeObserver 不调用 onGlobalLayout