I have successfully created EditTexts depending on the user input in Android, and also I have assigned them unique ID's using setId()
method.
Now what I want to do is to get values from the dynamically created EditText
s when the user tap a button, then store all of them in String variables. i.e. value from EditText having id '1' should be saved in str1 of type String, and so on depending on the number of EditTexts.
I am using getid()
, and gettext().toString()
methods but it seems a bit tricky... I cannot assign each value of EditText to a String variable. When I try to do that a NullPointerException
occurs, and if it is not the case where no user input data is shown, I display it in a toast.
Heres, the code:
EditText ed;
for (int i = 0; i < count; i++) {
ed = new EditText(Activity2.this);
ed.setBackgroundResource(R.color.blackOpacity);
ed.setId(id);
ed.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
linear.addView(ed);
}
How do I now pass the value from each EditText to each different string variable? If some body could help with a sample code it would be nice.
In every iteration you are rewriting the
ed
variable, so when loop is finisheded
only points to the last EditText instance you created.You should store all references to all EditTexts:
Now
allEds
list hold references to all EditTexts, so you can iterate it and get all the data.Update:
As per request:
for multiple edittext
I have a for loop generating dynamic TextViews within TableRows from a JSON string. Here's what I did:
I am using findViewById(row.getId()) to set the dynamic TextView text data to EditText fields in my app. For those of you who do not understand JSON, there are several good tutorials out there (I'm sure there are great explanations here on Stack Overflow) for the Android platform. I'm still an Android newbie, but I hope this is helpful to some of you out there.
this is because EditText.gettext() return Editable , so toString will not work . try String.valueOf(edittext.gettext) .
if u sure that u r getting d right EditText but prob. is how 2 pass its test to string den code is
else use setTeg(Edittext) n get editText by getTag on button click .
You can also do like this by taking an Array of EditText. You should store all references to all EditTexts:
and you can use for loop to get the value from the EditText .