Whiss Whiss - 8 months ago 46
Android Question

Android - Loop to collect all editText values & store in SharedPreferences

I have a heap of editTexts that i need to collect and store in my saved preferences. My code works when I do each one separately (as seen below), but I have about 50 to collect and can't seem to work out how to loop through and collect them all without having to code each one.. Is it possible? Working code is below:

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);

final EditText t3 = (EditText) findViewById(R.id.text3Value);
String T3 = t3.getText().toString();
editor.putstring("text3", T3);

I know this isn't right but I need to do something along the lines of:

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]);


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());