Solution 1 :
The general ways for not repeating code are usually loops and functions. In this case you should add your EditTexts to an array like data structure and loop over them.
For example:
You could store the edit Texts in a Hash map and then use a loop to add them to the form:
new HashMap<EditText, String>() {{
put(R.id.et1, "name");
put(R.id.et2, "phone");
//etc...
}}.forEach((editText, s) -> formData.put(s, editText.getText().toString()));
If you don’t mind using uninformative names you can just use an array:
EditText[] toAdd = new EditText[]{findViewById(R.id.et1), findViewById(R.id.et2)};
for (int i = 0; i < toAdd.length; i++) {
formData.put("data" + i, toAdd[i].getText().toString());
}
Or for a nice mix of both, you can use the ID of the EditText as the name
EditText[] toAdd = new EditText[]{findViewById(R.id.et1), findViewById(R.id.et2)};
for (EditText editText : toAdd) {
formData.put(getResources().getResourceEntryName(editText.getId()), editText.getText().toString());
}
Problem :
I’d like to efficiently extract data from the EditText fields in a form, without having to repeat the same code multiple times. Here’s my current implementation for four EditTexts:
EditText editText1 = (EditText) findViewById(R.id.editText1);
String message1 = editText1.getText().toString();
formData.put("data1", message1);
EditText editText2 = (EditText) findViewById(R.id.editText2);
String message2 = editText2.getText().toString();
formData.put("data2", message2);
EditText editText3 = (EditText) findViewById(R.id.editText3);
String message3 = editText3.getText().toString();
formData.put("data3", message3);
EditText editText4 = (EditText) findViewById(R.id.editText4);
String message4 = editText4.getText().toString();
formData.put("data4", message4);