Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
261 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.

See Question&Answers more detail:os

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

1 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...