1

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???

4 Answers4

2

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.

Community
  • 1
  • 1
Nir Duan
  • 6,164
  • 4
  • 24
  • 38
0

"findViewById" returns null when the provided id (in your example, it's called "bluetooth_switch") doesn't exist in the "resource tree" of the current container

hello404
  • 22
  • 2
0

I solved it moving these lines of code to my fragment java file. Thanks.

0

In my case, had called setId() on the view for tracking, and so findViewById returns null. Maybe might help someone

N. Kyalo
  • 47
  • 3