Reputation: 5
First of all thanks for taking time to look at my question
I have an array of editText and an array of doubles, I have a listener for the editText, whenever I enter a new value into the editText I would like to update the value in the double array
So I thought I could use a for loop to scan through all the editText and in each iteration, it would update the elements in the double array,
right now I have the code as follows
however, in the method "public void onTextChanged" when I try to use x from the "FOR" loop it is giving me an error saying that x in accessed within inner class and must be declared final, but I do not want x to be final, can somebody help me find a way to do this?
In other posts people suggested setting x as global variable, and maybe in the for loop when x reaches a certain value reset it to 0?
Thank you in advance
public class Test1 extends AppCompatActivity {
//In Test1 activity scope
EditText editText1;
EditText EditText2;
EditText EditText3;
String Results;
//I have my double array
double doubleArray[] = new double[] {
0.0,
0.0,
0.0,
};
//declare the doubles that will be assigned in the double array
double double1 = 0.0;
double double2 = 0.0;
double double3 = 0.0;
/*My editText array, here is where I'm struggling,
I don't know how and where to create an editText array,
or if I'm using the correct syntax, also I feel that
editText1,2,and 3 should not be initialized here*/
EditText[] editTextArray = new EditText[] {
(EditText)findViewById(R.id.editText1),
(EditText)findViewById(R.id.editText2),
(EditText)findViewById(R.id.editText3),
};
//In the onCreate method
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_Test1);
for (int x = 0; x < editTextArray.length; x++) {
editTextArray[x].addTextChangedListener(new TextWatcher(){
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
try {
Results = editTextArray[x].getText().toString();
if (Results.equals("")) {
Results = "0.0" ;
doubleArray[x] = Double.parseDouble(Results);
}
else {
doubleArray[x] = Double.parseDouble(Results);
}
LetsFillTheVariables();
}
catch(NumberFormatException e){}
}
});
}
private void LetsFillTheVariables() {
double1 = doubleArray[0];
double2 = doubleArray[1];
double3 = doubleArray[2];
}
}
Upvotes: 0
Views: 29
Reputation: 81
You can create a temporary final variable:
for (int x = 0; x < editTextArray.length; x++) {
final int idx = x;
editTextArray[idx].addTextChangedListener(new TextWatcher(){
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
try {
Results = editTextArray[idx].getText().toString();
if (Results.equals("")) {
Results = "0.0" ;
doubleArray[idx] = Double.parseDouble(Results);
}
else {
doubleArray[idx] = Double.parseDouble(Results);
}
}
catch(NumberFormatException e){}
}
});
}
Upvotes: 1