Home » Android » Variable ' ' is accessed from within inner class, needs to be declared final

Variable ' ' is accessed from within inner class, needs to be declared final

Posted by: admin November 1, 2017 Leave a comment

Questions:

In ‘Main’ im trying to use function declared in class Bluetooth, and having error as in title.

Here is the code

    ImageButton3.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            bluetooth.wlaczBT();
        }
    });

I have class bluetooth and within it i have a method wlaczBT (in english its Turn on BT).

But have bluetooth underlined in red unfortunetly.
How can I used that method in Main class?

This is how i declared variable bluetooth (in Main ofc)

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Bluetooth bluetooth = new Bluetooth(this);

i tried to add “final” before “Bluetooth”, but the app crashed while instaling on phone.

Answers:

You need to make bluetooth a global variable. That means declare it before the onCreate() but initialize it in onCreate ().