Reputation: 101
I am creating a project in which I prompt the user with a table. And he has to fill in the values. And when he clicks on submit, at the back end I have to check all those values are correct or not.
Here is a sample pick of the table and code
As you can see i have given the id's as "fcfs_p1_ct" for p1 and "fcfs_p2_ct" for p2. Now at the back end when I have to check the values entered by the user. I have to create objects of the respective Edit Texts.
Now one way is to create n number of if else conditions and create the objects for each edited text manually. Can this process be done through loops? For example for p1
String str = findViewById(R.id.fcfs_p1_ct).getText().toString;
similarly for p2
String str = findViewById(R.id.fcfs_p2_ct).getText().toString;
and so on for n number of processes.
As the only changing variable in the statements is the process number. Please suggest me a way to do the same for a loop
Upvotes: 2
Views: 986
Reputation: 406
You can simply keep these ids in an ArrayList of Integer like;
ArrayList<Integer> ids = new ArrayList<>();
ids.add(R.id.editText1);
ids.add(R.id.editText2);
When the user presses submit, you can go through that array and do what you want. If you would like to change the corresponding value at the end, you can keep a Map instead of ArrayList.
But my personal suggestion is that using a ListView or RecyclerView. You can repeat views with an Adapter and keep your data as instances of a class so that you can avoid these kind of codes.
Upvotes: 1
Reputation: 6961
This kind of situations in android are not handled by loops, once you realize that your layout (XML) requires lots of View
id assignments, it's recommended to use an Adapter
. There are many ready-to-go Adapters
available in android SDK, such as ArrayAdapter
, BaseAdapter
, CursorAdapter
etc.
Which Adapter
to choose depends entirely on your choice of View
/layout you wish to inflate and the data type and source you're willing to use.
In your situation, I'd recommend starting with a simple ListView
, and using a custom Adapter
(class that extends BaseAdapter
). There are many tutorials out there on how to implement this, which are by the way quite easy to follow.
Upvotes: 2