I would like to use a non-final variable in an On-click listener and converting the variable to final is not an option because the variable is an ArrayList<String> which i will be altering and editing throughout the coarse of the program.
This is an overview of the code
I have an EditText which i will be getting the value of to add to the ArrayList.
I am then setting a ListView based on this ArrayList using a custom adapter which all works fine.
ArrayList<String> nameList = new ArrayList<String>();
Button newName = (Button) findViewById(R.id.AddItemButton);
newName.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
if(name.getText().toString().equals("")){
Toast error2 = Toast.makeText(getBaseContext(), "The Product Name cannot be empty", Toast.LENGTH_LONG);
error2.setGravity(Gravity.CENTER, error2.getXOffset() / 2, error2.getYOffset() / 2);
error2.show();
}
else{
// The variable i need to access which cannot be non-final vvv
nameList.add(name.getText().toString());
setListAdapter(adapter);
};
}
I realise i could make a junk variable to make a copy of the arraylist and make that final but i dont believe this variable will update itself when my ArrayList chances.
I have found this solution which interests me however i get error on the Super(); line saying that a constructor must be the first statement.
newName.setOnClickListener(new OnClickListener() {
private ArrayList<String> nameList;
public void OnClickListener(ArrayList<String> nameList){
super(); // error line
this.nameList = nameList;
}
// do rest of code
Any thoughts?