How to set text for multiple EditTexts in Android - java

First of all i would like to introduce you with my application, so you have a better point of view what i need. I have database with three tables days, weeks, weekdays and in one Activity i'm fetching all items from days table by selected week, but i don't know how to set text to all members of that class Day. I will show you in following example what i want.
I have achieved setting text to multiple EditTexts, but with many repetition. I want to do this with arrays and loop. I have succeed initializing all EditTexts using array and loop, but i don't know how to implement setting text for all EditTexts.
This is repetition part:
for (int i = 0; i < days.size(); i++) {
// Monday
Day day1 = days.get(0);
etNasteMonday.setText(String.valueOf(day1.getNaste()));
etInsulinMondayBeforeBreak.setText(String.valueOf(day1.getInsulinBeforeBreak()));
etDiabetesMondayAfterBreak.setText(String.valueOf(day1.getDiabetesAfterBreak()));
etDiabetesMondayBeforeLaunch.setText(String.valueOf(day1.getDiabetesBeforeLaunch()));
etInsulinMondayBeforeLaunch.setText(String.valueOf(day1.getInsulinBeforeLaunch()));
etDiabetesMondayAfterLaunch.setText(String.valueOf(day1.getDiabetesAfterLaunch()));
etDiabetesMondayBeforeDinner.setText(String.valueOf(day1.getDiabetesBeforeDinner()));
etInsulinMondayBeforeDinner.setText(String.valueOf(day1.getInsulinBeforeDinner()));
etDiabetesMondayAfterDinner.setText(String.valueOf(day1.getDiabetesAfterDinner()));
etDiabetesMondayBeforeSleep.setText(String.valueOf(day1.getDiabetesBeforeSleep()));
etInsulinMondayAfterSleep.setText(String.valueOf(day1.getInsulinBeforeSleep()));
// Tuesday
Day day2 = days.get(1);
etNasteUtorak.setText(String.valueOf(day2.getNaste()));
etInsulinUtorakPreDorucka.setText(String.valueOf(day2.getInsulinBeforeBreak()));
etDiabetesUtorakPosleDorucka.setText(String.valueOf(day2.getDiabetesAfterBreak()));
etDiabetesUtorakPreRucka.setText(String.valueOf(day2.getDiabetesBeforeLaunch()));
etInsulinUtorakPreRucka.setText(String.valueOf(day2.getInsulinBeforeLaunch()));
etDiabetesUtorakPosleRucka.setText(String.valueOf(day2.getDiabetesAfterLaunch()));
etDiabetesUtorakPreVecere.setText(String.valueOf(day2.getDiabetesBeforeDinner()));
etInsulinUtorakPreVecere.setText(String.valueOf(day2.getInsulinBeforeDinner()));
etDiabetesUtorakPosleVecere.setText(String.valueOf(day2.getDiabetesAfterDinner()));
etDiabetesUtorakPredSpavanje.setText(String.valueOf(day2.getDiabetesBeforeSleep()));
etInsulinUtorakPredSpavanje.setText(String.valueOf(day2.getInsulinBeforeSleep()));
}
What should i do to make this more efficient and easier for program to read and how to implement within this code:
List<String> values = new ArrayList<>();
int[] ids = new int[]{R.id.et_naste_monday, R.id.et_insulin_monday_before_breakf, R.id.et_posle_dorucka_monday, R.id.et_pre_rucka_moday,
R.id.et_insulin_monday_pre_rucka, R.id.et_posle_rucka_monday, R.id.et_pre_vecere_moday, R.id.et_insulin_monday_pre_vecere, R.id.et_posle_vecere_monday,
R.id.et_pred_spavanje_moday, R.id.et_insulin_monday_pred_spavanje};
List<Day> days = mDatabase.getAllDaysByWeek(week.getTitle());
for (int id : ids) {
EditText t = (EditText) findViewById(id);
values.add(t.getText().toString());
t.addTextChangedListener(this);
applyChangedEditTextColor(false, values, t);
for (Day day : days) {
// Here i should do the same part as i done it in above example
}
}

Create a custom view with all these edittexts, and set a method populate(Day day) in which you will fill all those setTexts. Then you can do
mondayView.populate(day.get(0));
tuesdayView.populate(day.get(1));
More info about custom views:
https://developer.android.com/training/custom-views/index.html
https://www.toptal.com/android/android-customization-how-to-build-a-ui-component-that-does-what-you-want

Related

How can I get and set a string resource dynamically in a for-loop using a findViewById() method?

In my app, I want a counter from 0 to 8 to decide the number of players in a game.
Below there are 8 possible fields to write a name inside, which are all set to invisible. If the players-counter is set to 3 players, there should be the first 3 fields visible. Depending on the actual number of the counter, the visibility of the fields changes (1player = first field, 5 players = first 5 fields).
When the +1 (player) button is clicked, a certain method is activated. I tried to run a for-loop everytime the button is clicked. In this for-loop from 0 to "whatever amount" (max. 8 players) the actual fields should be found with "findById" and set to visible.
I tried it with a string resource (.xml) and I can get the text of the resource but with my thought process, I have to update the string resource to every number of the field (if 3 players: "field_" + "1", "field_" + "2", "field_" + "3").
How can I get and (most importantly) set/update a string resource for this specific purpose?
(Switch is too inefficient and I can't use a string with the findViewBy Id()-method by updating the String (not string resource) like mentioned before.
Please help, and accept the fact that I'm new to Android Studio for one week!)
You can use "getIdentifier" which takes a String parameter. So you can set the type as "id" in the second parameter of this method. This method returns the id of the view you want, but beware, it will throw a "FATAL EXCEPTION" if the id of the View doesn't exist. With this id, you can use findViewById to fetch the TextView and change its visibility. The "getIdentifier" method can be called from the "getResources()" method.
Below you can see what it would be like to make visible a TextView that has the id "textView1":
int id = getResources().getIdentifier("textView1", "id", getPackageName());
TextView textView = findViewById(id);
textView.setVisibility(View.VISIBLE);
Below you can see how you would make 8 TextView with id 1 to 8 visible:
TextView textView;
for (int i = 1; i <= 8; i++) {
int id = getResources().getIdentifier("textView" + i, "id", getPackageName());
textView = findViewById(id);
textView.setVisibility(View.VISIBLE);
}
So, just put the limit at i <= x , with x being the limit of players who will play:
TextView textView;
for (int i = 1; i <= totalPlayers; i++) {
int id = getResources().getIdentifier("textView" + i, "id", getPackageName());
textView = findViewById(id);
textView.setVisibility(View.VISIBLE);
}
Do you just want to make some EditTexts visible and others not? Personally I'd keep it simple, do the lookups once (in onCreate or wherever) and store the references in a list. Then when you need to display n fields, you can just iterate over the list and set the first n to VISIBLE and the rest to INVISIBLE.
I feel like it's fine to just list all the EditText IDs (R.id.field_1 etc) and generate your list of actual Views from that, but if that repetition bothers you, there's a few things you could do. Like:
set a tag attribute on each field in the XML, and use findViewWithTag to look them up, generating the lookup strings programmatically, like "field_" + i
do a similar thing with the resource ID, like in #Moises's answer
lookup their containing layout, use getChildCount and [getChildAt] to iterate over the views in that layout, and use isInstance to collect all the EditTexts in order3
create and add the EditTexts in code - you probably don't want to do this, but you could!
I'm not really sure what you mean about the string resource or what you're trying to do - I'd honestly just make a list of R.id.field_1 etc, iterate over that to do findViewById on each and store those in a new list, and you're done. Also my Java's a bit rusty so sorry no example code!

Loop through an ArrayList to find missing values and create a dummy object

I have a list which stores a object named GoldNetValue containing date and gold rate.There will be a difference of 10 minutes between the two records in the list and, in some cases no data will be available during the particular time interval.
Sample values as below
{GoldNetValue[2018-03-02 13:20 ,87], GoldNetValue[2018-03-02 13:30 ,86.4],GoldNetValue[2018-03-02 13:40 ,85.6]],GoldNetValue[2018-03-02 13:50 ,85.8]],GoldNetValue[2018-03-02 14:10 ,86.1]],GoldNetValue[2018-03-02 14:30 ,86.8]]
i need to loop through the list and create a new GoldNetValue object with missing date field and noDataAvailable flg enabled,then insert it back into the list. The difference is always 10 minutes.
int diffMins = 10;
Date tempDate = new Date();
for(int i= 0; i < goldNetList.size(); i++)
{
GoldNetValue goldValue = (GoldNetValue) goldNetList.get(i);
if(goldValue.getDate() != null && goldValue.getGoldRate() != null)
{
tempDate = goldValue.getDate();
}
if() // logic yet to be implemented
}
lets say from 13:30 to 13:50 pm , there is only one record available , i need to create an object with date as 13:40 and noDataFlag enabled and store it back to the list.
i am a newbie just started to learn coding.
How can i populate through the list and create objects with flag enabled with these type of value combinations?
Thank you for your time

How to Iterate over entire android listview

I have a listview where user choose how much for each item he wants, so I need to iterate over each row to get the name (Ovo, Presunto, Queijo, etc), the quantity (the number between the "+" and "-" buttons) and the price. This is already working fine, but I have the following problem: If you look at the bottom of the listview you can know that there are more items, in this picture there are 9 items, but there are 15, and if the user scrolls I will can not iterate over the "hidden" items of listview.
Today I have this code, where I try iterate over the elements of listview:
for (int i = 0; i < listView.getCount(); i++) {
v = listView.getChildAt(i);
if(v != null){
value = (TextView) v.findViewById(R.id.edOptionValue);
nome = (TextView) v.findViewById(R.id.tvOptionName);
tvPrice = (TextView) v.findViewById(R.id.tvPrice);
String price = tvPrice.getText().toString();
//more code here
}
}
listView.getCount() gets the correct number of items (15 items), but when i==10 listView.getChildAt(i) is getting null.
Is there some way to iterate over all items of a listview, incluing the "hidden" elements ?
You should not iterate the list views, instead you should keep all that data (price/quantity) in a list and iterate over that if you really need to do that. That list can be used to populate the ListView as well.

Modifying each object of a List in for each loop in Android

I'm fetching items from database. I have a few Edit Texts and I need to get text from these editable texts and pass that text, update too objects of a List I get from database. I'm getting values from Edit Texts. This is how it looks in code:
String getNasteMonday = etNasteMonday != null ? etNasteMonday.getText().toString() : null;
String getInsulinMondayBeforeBreak = etInsulinMondayBeforeBreak != null ? etInsulinMondayBeforeBreak.getText().toString() : null;
List<Day> days = mDatabase.getAllDaysByWeek(week.getTitle());
double nasteValue = convertStringToDouble(getNasteMonday);
double insulinBeforeBreakValue = convertStringToDouble(getInsulinMondayBeforeBreak);
for (Day day : days) {
day.setNaste(nasteValue);
day.setInsulinBeforeBreak(insulinBeforeBreakValue);
mDatabase.updateDay(day);
}
In this case I have three tables in database, one for storing days, and one for storing weeks and one for storing days by weeks. I'm fetching data in this case by week name and every Week object has 7 days and I need to store different values for each day in that Week. Now, what I'm getting is that in this foreach loop I'm storing the same value for all 7 days and I don't want that. I want to do something like this for example:
for (Day day1 : days) {
day1.setNaste(nasteValue);
}
for (Day day2 : days) {
day2.setNaste(nasteValue2);
}
EDIT:
How to show text in EditText when i have fetched data from database:
I should set text from an array of Strings.
List<String> values = new ArrayList<>();
int[] ids = new int[]{R.id.et_naste_monday, R.id.et_insulin_monday_before_breakf, R.id.et_posle_dorucka_monday, R.id.et_pre_rucka_moday,
R.id.et_insulin_monday_pre_rucka, R.id.et_posle_rucka_monday, R.id.et_pre_vecere_moday, R.id.et_insulin_monday_pre_vecere, R.id.et_posle_vecere_monday,
R.id.et_pred_spavanje_moday, R.id.et_insulin_monday_pred_spavanje};
List<Day> days = mDatabase.getAllDaysByWeek(week.getTitle());
int count = 0;
for (int id : ids) {
EditText t = (EditText) findViewById(id);
values.add(t.getText().toString());
t.addTextChangedListener(this);
applyChangedEditTextColor(false, values, t);
// Here i should implement some logic like and apply for all edittexts
// for (Day day : days) {
//
// }
}
Since you have a lot of EditText to use. I would create some Arrays to store the instance an recover those in a loop.
EditText[] nasteEdit = new EditText[]{ /* your seven instance of editText for naste value in correct order */};
List<Day> days = mDatabase.getAllDaysByWeek(week.getTitle());
int cntDays = 0;
for (Day day : days) {
String getNasteMonday = nasteEdit[cntDays] != null ? nasteEdit[cntDays].getText().toString() : null;
double nasteValue = convertStringToDouble(getNasteMonday);
day.setNaste(nasteValue);
// SAME FOR OTHER ATTRIBUTE
mDatabase.updateDay(day);
cntDays++;
}
During the loop, I get the correct EditText and create the value. I keep you for-iterative loop here and use an external counter but this should work.
You just need to do this for every attributes Day have and this will work.
The array need to have the instance of the EditText, so don't waste you time to get the text of each ;)
Hope this will work, I can't test it write now.
I have found a solution. The better approach would be to use regular for loop and using method get() from List, for getting the position of element in a list.
for (int i = 0; i < days.size(); i++) {
Day day1 = days.get(0);
day1.setNaste(3.0);
Day day2 = days.get(1);
day2.setNaste(2.0);
Day day3 = days.get(2);
Day day4 = days.get(3);
Day day5 = days.get(4);
Day day6 = days.get(5);
Day day7 = days.get(6);
}
If you need to update some data from database then you will declare object Day outside the for loop and call that object in update method from database:
database.updateDay(day1);
database.updateDay(day2);

how to select the ages which are less than or greater than from drop down in grails and groovy

I have a requirement that should have one drop down containing some conditions on age.
like less than 10days,between 10 to 30 days,between 1 month to 3 months,between 4 month to 12 months,between 1yr to 2 yr.
I have domain class containing one property age(integer).and i am calculating age form dob to current date and storing in DB.I have search criteria to search based on age in search page,So how can i display these condition vales in drop down and when i select one option how to display the result based on age.
presently i am displaying all ages in drop down form the DB, please find the code and help me in doing this, if its not clear please write the comments so that i can explain u.
this is my drop down contaning all dobs
<td><span id="availableAge" ></span></td>
This is my script to get dobs from controller with an ajax call
function generateAge(data){
var list ="<select style='width:100px' id='age' name='age'><option value=''>-Select-</option>";
var opt;
for(var i=0; i<data.ageDetails.length; i++){
opt = "<option value="+data.ageDetails[i].age+">";
opt = opt+data.ageDetails[i].age;
opt = opt+"</option>";
list = list+opt;
}
list = list+"</select>";
var listObj = document.getElementById("availableAge");
if(listObj){
listObj.innerHTML = list;
}
}
It's a bad idea to store age in DB, as it changes all the time - better stick with DOB.
As the option set is fixed, make something like an enum for it, use its values() to render a select
enum AgeCriteriaEnum { NONE, LESS_THAN_10, BETWEEN_10_AND_30, ... so on }
and just do a switch() like:
AgeCriteriaEnum ageEnum = AgeCriteriaEnum.valueOf(params.ageEnum)
Date today = new Date()
Patient.withCriteria {
switch(ageEnum) {
case AgeCriteriaEnum.NONE:
break;
case AgeCriteriaEnum.LESS_THAN_10:
ge('dob', today-10)
break;
case AgeCriteriaEnum.BETWEEN_10_AND_30:
lt('dob', today-10)
ge('dob', today-30)
break;
//... so on
}
}

Categories