Whiss Whiss - 1 year ago 85
Android Question

Android - Loop to collect all editText values

I have around 50 EditText fields and I want to get their values using a loop. Getting the values individually as below works fine:

SharedPreferences settings = getSharedPreferences(filename, 0);
SharedPreferences.Editor editor = settings.edit();
editor.clear(); //not sure if this is required

final EditText t1 = (EditText) findViewById(R.id.text1Value);
String T1 = t1.getText().toString();

final EditText t2 = (EditText) findViewById(R.id.text2Value);
String T2 = t2.getText().toString();
editor.putstring("text2", T2);

................................ and so on till EditText t50.

I have tried achieving this through the loop below but couldn't get it to work.

for(int x=1; x<50; x++)
EditText et[x] = (EditText) findViewById(R.id.text[x]Value);
String t[x] = et[x].getText().toString();
String Ref = "text" + x;
editor.putString(Ref, t[x]);

Answer Source

You can try this by creating an array of the ids of the textview and looping through the array. Try this:

int[] ids = new int[]{R.id.text1Value,R.id.text2Value,R.id.text3Value};//and so on

int i =1;
for(int id : ids){
    EditText t = (EditText) findViewById(id);
    String Ref = "text" + i;
    editor.putString(Ref, t.getText().toString());