Reputation: 21
In my Android App that where i use Java in Android Studio I want to use a loop to get the inserted Texts from my EditText fields
Could you please help me?
for (int i=0; i==player; i++ ){
myArray[i] = "player"+i.getText().toString();
}
I have EditTextfields which can be declared as player0 until player15. And Player is my total amount of EditTextfields.
I want to write all the inputs into an array but i get always an error for the part"player"+i
" is there an other solution how to handle that?
Upvotes: 0
Views: 69
Reputation: 1082
if you have all the edit text fields in the same layout (Linear layout....) you can simply access every EditText using a loop by accessing them as childs of the layout suppose in the xml file you have a linear layout
<LinearLayout
android:id="@+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
notice that we gave the layout an id (linearLayout) now from your java code you can simply populate the array by using the following loop
LinearLayout linear= (LinearLayout)findViewById(R.id.linearLayout);
for(int i=0;i<linear.getChildCount();i++)
{
EditText field=linear.getChildAt(i);
array[i]=field.getText().toString();
}
unlike the method you are trying to use this method is more dynamic where you dont have to provide ids for all the editTexts just a single id for your main layout and you would not have to declare a static array with all the ids in your java code
Upvotes: 0
Reputation: 12463
Simply put, Java does not work that way. You can't generate a variable name from a string. The easiest way to get what you want is an array.
EditText[] players = {
player0, player1, player2, player3, player4,
player5, player6, player7, player8, player9,
player10, player11, player12, player13, player14, player15
};
List<String> texts = new ArrayList<>(players.length);
for (EditText player : players) {
texts.add(players[i].getText().toString());
}
Upvotes: 1