0
final ArrayAdapter adapter = new ArrayAdapter(...);
listView.setOnItemClickListener(new AdapterView.OnitemClickListener(){
    @Override
    public void onItemClick(AdapterView<?> parent,View view,int position,long id){
        Word word = adapter.getItem(position);
    }
});

I can't understand why the anonymous inner class calls the "adapter" object which should be declared "final" ? Is this a rule? Should i be remember that? I know the variable declared final will save its reference without changing. But in the example above, there is no change of reference, I just call a method on final object.

diginoise
  • 7,352
  • 2
  • 31
  • 39
GeniusL
  • 1
  • 1
  • It's is effective final – Viet Aug 15 '17 at 03:28
  • Anonymous inner classes solve some annoying problems in a simple yet effective way. They also allow you to create more efficient code when event handled by Adapter Classes while we cannot extend a final class. – Tehmina Aug 15 '17 at 03:31

2 Answers2

1

That's because you're trying to access to your adapter in a listener (and you don't know when it will happen). So, you need to declare it final because that means that the reference will be the same whenever you get the callback from your listener. When a function is destroyed, all the non-final references declared inside your function will be also destroyed. Then, the reference that you will try to access later in your listener will not exist anymore.

So you have two solutions: declare it final (and keep the reference even after the function is "destroyed") or declare it global.

  • This function says the setonItemClickListener method? and how do i know that this function will not be used after the destruction of the reference? – GeniusL Aug 15 '17 at 05:06
  • I mean, when you use setOnItemClickListener you are like "assigning" a behaviour to the component. Every time you call to the function, new references are created and when you get out of the function those references get destroyed. A solution if you dont want it final is to declare your adapter outside any function (even outside an onCreate) because ithat makes the variable global and you keep the reference. You can also declare your variable inside the listener if you dont need to use that variable outside the listener – Shalon Isaac Aug 15 '17 at 05:16
  • Can i understand that in order to call the onItemClickListener method when my adapter is still there? So I declare it as final. You say every time you call the function, will create a new reference, who cites who? – GeniusL Aug 15 '17 at 08:54
0

Declaring variables used by inner class final is to make you aware that dereference will happen possibly on another thread or much later in time. Not making these final would require shifting these from stack onto the heap and would provide closures. Apparently users objected to it.

See here: http://people.csail.mit.edu/gregs/ll1-discuss-archive-html/msg04030.html

diginoise
  • 7,352
  • 2
  • 31
  • 39