Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
160 views
in Technique[技术] by (71.8m points)

java - How to get data from each dynamically created EditText in Android?

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 EditTexts 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.

question from:https://stackoverflow.com/questions/5923587/how-to-get-data-from-each-dynamically-created-edittext-in-android

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In every iteration you are rewriting the ed variable, so when loop is finished ed only points to the last EditText instance you created.

You should store all references to all EditTexts:

EditText ed;
List<EditText> allEds = new ArrayList<EditText>();

for (int i = 0; i < count; i++) {   

    ed = new EditText(Activity2.this);
    allEds.add(ed);
    ed.setBackgroundResource(R.color.blackOpacity);
    ed.setId(id);   
    ed.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
            LayoutParams.WRAP_CONTENT));
    linear.addView(ed);
}

Now allEds list hold references to all EditTexts, so you can iterate it and get all the data.

Update:

As per request:

String[] strings = new String[](allEds.size());

for(int i=0; i < allEds.size(); i++){
    string[i] = allEds.get(i).getText().toString();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...