Android Studio gives me the following problem:
Error: (83, 25) error: local variable btArrayAdapter is accessed from within inner class; needs to be final final
However, if I put it out of the event of the onclick button, the error is removed.
package net.stackblue_v1_0.stackblue_v1_0;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Set;
public class BluetoothActivity extends AppCompatActivity {
public BluetoothAdapter mBluetoothAdapter;
public final static int REQUEST_ENABLE_BT = 1;
public Switch switch1;
public Button buttonBD;
public ListView listViewDE;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bluetooth);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
switch1 = (Switch) findViewById(R.id.switch1);
buttonBD = (Button) findViewById(R.id.buttonBD);
ArrayAdapter<String> btArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
listViewDE = (ListView) findViewById(R.id.listViewDE);
if (mBluetoothAdapter == null) {
Toast.makeText(getApplicationContext(), "Su dispositivo no soporta bluetooth", Toast.LENGTH_LONG).show();
switch1.setChecked(false);
}
if (mBluetoothAdapter.isEnabled()) {
Toast.makeText(getApplicationContext(), "El servicio Bluetooth ya estaba activado", Toast.LENGTH_LONG).show();
switch1.setChecked(true);
} else {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
switch1.setChecked(true);
}
switch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
mBluetoothAdapter.enable();
} else {
mBluetoothAdapter.disable();
}
}
});
buttonBD.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
// Loop through paired devices
Toast.makeText(getApplicationContext(), "Mas de un device", Toast.LENGTH_LONG).show();
for (BluetoothDevice device : pairedDevices) {
// Add the name and address to an array adapter to show in a ListView
btArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
}
listViewDE.setAdapter(btArrayAdapter);
}
});
}
}