Hello I am trying to do pretty much the exact same thing as the person who asked this question: Variable is accessed from within inner class needs to be declared final
So I'm going to continue to use their code as a reference in this question:
File directory = new File(prefs.getString("path",null));
File[] files = directory.listFiles();
for (File file :files){
if(file.isDirectory()) {
buttons.add(new Button(this));
Button button = buttons.get(buttons.size() - 1);
String fileName = file.getName();
button.setText(fileName);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(currentActivity, EOChoiceActivity.class);
intent.putExtra("fileExtension",fileName);
startActivity(intent);
}
});
layout.addView(button);
}
}
I'm asking the same question as the original author also: why is it that only the last fileName selected is sent for any button? I understand that this has to do with the rules of how an inner class accesses local variables, as cited in JLS 8.1.3, but I still just can't understand the reasoning.
The only thing I can think of that makes sense of this is that the inner class is using a reference of fileName, and so when the fileName value changes on each iteration, and eventually is solidified in it's value on the last iteration, the "final" reference would be to the value of the last element in the files array and this reference would be present for each button.
Yeah I'm just really confused here... I can't understand why the different values for fileName wouldn't apply to each button, but instead only the last fileName value is applied to each button.