Possible Duplicate:
Looping through editTexts to check values
I have a layout with about 100 editTexts (15 rows, 10 columns), all named based on their row / column IDs (e.g. box0101, box0102 etc.).
I have a method clearBoard() that is called when a ‘clear’ button is clicked (see code below). It is intended to loop through all of the boxes (box0101, box0102, box0103 etc.) and replace the contents with “” – making them blank.
The error that comes up in the LogCat says java.lang.NoSuchFieldException: box0101
at java.lang.Class.getDeclaredField(Class.java:631) – but there is definitely a box0101 defined in my xml and i reference it several other times during the code with no problem.
Any ideas?
From XML
<EditText
android:gravity="center"
android:layout_marginLeft="10dp"
android:id="@+id/box0101"
android:layout_width="30dp"
android:layout_height="30dp"
android:background="@drawable/boxoutlineone" />
<EditText
android:gravity="center"
android:id="@+id/box0201"
android:layout_width="30dp"
android:layout_height="30dp"
android:background="#000000" />
<EditText
android:gravity="center"
android:id="@+id/box0301"
android:layout_width="30dp"
android:layout_height="30dp"
android:background="#000000" />
<EditText
android:gravity="center"
android:id="@+id/box0401"
android:layout_width="30dp"
android:layout_height="30dp"
android:background="#000000" />
In Activity:
final EditText box0101 = (EditText)findViewById(R.id.box0101);
final EditText box0201 = (EditText)findViewById(R.id.box0201);
final EditText box0301 = (EditText)findViewById(R.id.box0301);
final EditText box0401 = (EditText)findViewById(R.id.box0401);
final EditText box0501 = (EditText)findViewById(R.id.box0501);
etc…
public void clearBoard() {
final int ROW_COUNT = 14;
final int COL_COUNT = 9;
final String ROWS[] = {"01","02","03","04","05","06","07","08","09","10","11","12","13","14","15"};
final String COLS[] = {"01","02","03","04","05","06","07","08","09","10"};
for(int i=0; i<ROW_COUNT; i++) {
for(int j=0; j<COL_COUNT; j++) {
String a = ROWS[i];
String b = COLS[j];
int editTextId=getResId("box"+a+b,this,id.class);
EditText et=(EditText)findViewById(editTextId);
et.setText("");
}
}
}
public static int getResId(String variableName, Context context, Class<?> c) {
try {
Field idField = c.getDeclaredField(variableName);
return idField.getInt(idField);
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
I don’t know why you decided to use the
Fieldclass to get theidinstead of the more practicalResources.getIdetifiermethod:Or, based on those
EditTextbeing in aTableLayout, you could just pass a reference to theTableLayoutinto a method which will traverse it with the methodgetChildAt(position).