Search code examples
androidbluetoothfindviewbyid

Switch findViewById returns null


I am trying 2 days to solve this problem. I made a fragment in which I made a switch to enable and disable bluetooth. Well in my main activity i wrote:

bluetoothSwitch = (Switch) findViewById(R.id.bluetooth_switch);
bluetoothSwitch.setOnClickListener(clicked);

where clicked:

clicked = new ButtonClicked();

and:

class ButtonClicked implements AdapterView.OnClickListener
{
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bluetooth_switch:
                if (bluetoothAdapter.isEnabled()){
                    bluetoothAdapter.disable();
                    Log.d("Log", "Bluetooth is disabled");
                }
                else{
                    bluetoothAdapter.enable();
                    Log.d("Log", "Bluetooth is enabled");
                }
                break;
            case R.id.buttonSearch:
                arrayListBluetoothDevices.clear();
                startSearching();
                break;
            case R.id.discoverable_switch:
                makeDiscoverable();
                break;
            default:
                break;
        }
    }
}

when I run it the findViewById return null...Do you have any idea???


Solution

  • What you're trying to do won't work - your findViewByID looks for the view inside your activity xml but the view (R.id.bluetooth_switch) is inside the fragment's xml.
    Look on this SO answer for code implementation.