I inflate an EditText and I setId(i++) | static int i = 0;
and this is the code :
buttonAdd.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
LayoutInflater layoutInflater =
(LayoutInflater) getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View addOne = layoutInflater.inflate(R.layout.row, null);
final EditText textOut = (EditText)addOne.findViewById(R.id.textout);
Button buttonRemove = (Button)addOne.findViewById(R.id.remove);
buttonRemove.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
((LinearLayout) addOne.getParent()).removeView(addOne);
}
});
container.addView(addOne);
textOut.setId(i++); }});
so, if I add an EditText, the Id will be 0 and if I add another EditText, the Id will be 1 .. etc
so, the user can select how many EditText he want, right ?
if the user add 3 EditText for example
How can my code knows ?
for example, if I want sum all the values of EditText, and the user add 3 EditTixt
I will do this
( EditText one = (EditText)findViewById(0) ) + ( EditText dodo = (EditText)findViewById(1) ) + ( EditText dodo = (EditText)findViewById(2) )
But, if I don't know how many EditTixt the user will add !
what can I do ?
thank you.
int count = 0;
int childcount = container.getChildCount();
for (int i=0; i < childcount; i++){
View v = container.getChildAt(i);
if(view.getTag.equals("edittext"){
count ++;
}
}
and change this line in your code
final View addOne = layoutInflater.inflate(R.layout.row, null);
addOne.setTag("edittext");
count return you total edittext added by user
take look on this code it will count edit text for you in your layout container
first you need to making changed in your code like this and it worked with me fine :
final ViewGroup addOne = (ViewGroup) layoutInflater.inflate(R.layout.test, null);
int count = 0 ;
for (int i = 0; i < addOne .getChildCount(); i++) {
if(addOne .getChildAt(i).getClass().getSimpleName().equals("EditText"))
count ++ ;
}
Related
I am developing an android application for a friend of mine that is a football trainer.
He asked me to create an application that is more of a table to count the stats of the players. The image below should clear things up:
Table of the application
As you can see, every time I press the upper left button I want to add a new player two a new row with a decrement button a counter and an increment button below each stat column.
I can currently do that but each player has 10 different column counters. So considering that I want to add 25 players for the maximum I should copy my code (250 times) with an incremented value in order to gain the same functionality for each player.
I've thought about using an array or a hashmap I'm just not sure what's the best practise to do it. Any suggestions are more than welcome.
Pre-declared variables for one player:
private int counter1 = 0;
private int counter2 = 0;
private int counter3 = 0;
private int counter4 = 0;
private int counter5 = 0;
private int counter6 = 0;
private int counter7 = 0;
private int counter8 = 0;
private int counter9 = 0;
private int counter10 = 0;
private TextView textCounter1;
private TextView textCounter2;
private TextView textCounter3;
private TextView textCounter4;
private TextView textCounter5;
private TextView textCounter6;
private TextView textCounter7;
private TextView textCounter8;
private TextView textCounter9;
private TextView textCounter10;
Routine that needs to be copied 250 times:
if (playersAdded == 1) {
//Set 1
ImageButton decrementButton1 = new ImageButton(getApplicationContext());
decrementButton1.setImageDrawable(decrementDrawableScaled);
decrementButton1.setLayoutParams(layoutParams);
textCounter1 = new TextView(getApplicationContext());
textCounter1.setText(String.valueOf(counter1));
textCounter1.setLayoutParams(layoutParams);
ImageButton incrementButton1 = new ImageButton(getApplicationContext());
incrementButton1.setImageDrawable(incrementDrawableScaled);
incrementButton1.setLayoutParams(layoutParams);
decrementButton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (counter1 > 0) {
counter1 -= 1;
textCounter1.setText(String.valueOf(counter1));
}
}
});
incrementButton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter1 += 1;
textCounter1.setText(String.valueOf(counter1));
}
);
//End of Set 1
}
Make class Player. (Learn Object-oriented programming)
Make row for one player. (Learn how to create listView, this tutorial should help you, or just google android listView)
Make listView with players row.
I have receipt and logs model in android app. Receipt hasMany logs.
I made query for group_by logs by sortID and grade.
//recieve RecepitID and query to group logs
final long forwardedId = (long) getIntent().getExtras().get(String.valueOf("recepitID"));
List<Logs> logsList = new Select().from(Logs.class).where("Receipt = " + forwardedId).groupBy("SortID, Grade").execute();
This grouping works fine. Problem is next. I need to have output like this (part in red circle):
but I get it like this:
And this is part of code how I done this.
public class LogsRecapitulation extends AppCompatActivity {
private ListView mainListView;
private BaseAdapter listAdapter;
private TextView logsCount;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recapitulation_listview);
mainListView = (ListView) findViewById(R.id.ListViewItem);
//recieve RecepitID and query to group logs
final long forwardedId = (long) getIntent().getExtras().get(String.valueOf("recepitID"));
List<Logs> logsList = new Select().from(Logs.class).where("Receipt = " + forwardedId).groupBy("SortID, Grade").execute();
TextView result = (TextView) findViewById(R.id.LogMassResult);
double sum = 0.0;
for (int i = 0; i < logsList.size(); i++) {
sum += logsList.get(i).getM3();
}
result.setText(String.format("%.2f m3", sum));
for (int i = 0; i < logsList.size(); i++) {
if (logsList.get(i).receipt.priceType.equals("Na panju")) {
TextView stumpPriceKN = (TextView) findViewById(R.id.sumPriceKN);
double sumPricekn = 0.0;
for (int j = 0; j < logsList.size(); j++) {
sumPricekn += logsList.get(j).price.stumpPrice_kn * logsList.get(j).getM3();
}
stumpPriceKN.setText(String.format("%.2f KN", sumPricekn));
} else {
TextView roadKN = (TextView) findViewById(R.id.sumPriceKN);
double roadPrKn = 0.0;
for (int j = 0; j < logsList.size(); j++) {
roadPrKn += logsList.get(j).price.roadPrice_kn * logsList.get(j).getM3();
}
roadKN.setText(String.format("%.2f KN", roadPrKn));
}
}
for (int i = 0; i < logsList.size(); i++) {
if (logsList.get(i).receipt.priceCorrection > 0 && logsList.get(i).receipt.priceType.equals("Na panju")) {
TextView corecctionPriceKn = (TextView) findViewById(R.id.correctionPriceKN);
double correcSumKN = 0.0;
for (int j = 0; j < logsList.size(); j++) {
correcSumKN += (logsList.get(j).price.stumpPrice_kn * logsList.get(j).getM3()) + ((logsList.get(j).price.stumpPrice_kn * logsList.get(j).getM3()) * logsList.get(j).receipt.priceCorrection / 100);
}
corecctionPriceKn.setText(String.format("%.2f KN", correcSumKN));
} else if (logsList.get(i).receipt.priceCorrection > 0 && logsList.get(i).receipt.priceType.equals("Šumska cesta")) {
TextView corecctionPriceKn = (TextView) findViewById(R.id.correctionPriceKN);
double correcSumKN = 0.0;
for (int j = 0; j < logsList.size(); j++) {
correcSumKN += (logsList.get(j).price.roadPrice_kn * logsList.get(j).getM3()) + ((logsList.get(j).price.roadPrice_kn * logsList.get(j).getM3()) * logsList.get(j).receipt.priceCorrection / 100);
}
corecctionPriceKn.setText(String.format("%.2f KN", correcSumKN));
} else {
TextView priceHolder = (TextView) findViewById(R.id.KorekcijaCijene);
TextView corecctionPriceKn = (TextView) findViewById(R.id.correctionPriceKN);
priceHolder.setText("");
corecctionPriceKn.setText("");
}
}
listAdapter = new RecapitulationArrayAdapter(logsList);
mainListView.setAdapter(listAdapter);
//display logs count
logsCount = (TextView) findViewById(R.id.logsCount);
logsCount.setText(String.valueOf(logsList.size()));
}
private class RecapitulationArrayAdapter extends BaseAdapter {
private LayoutInflater inflater;
private List<Logs> logsList;
public RecapitulationArrayAdapter(List<Logs> logsList) {
inflater = LayoutInflater.from(LogsRecapitulation.this);
this.logsList = logsList;
}
#Override
public int getCount() {
return logsList.size();
}
#Override
public Object getItem(int position) {
return logsList.get(position);
}
#Override
public long getItemId(int position) {
return logsList.get(position).getId();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.logs_recapitulation, parent, false);
}
Logs log = logsList.get(position);
((TextView) convertView.findViewById(R.id.rec_log_sort)).setText(log.sort_id);
((TextView) convertView.findViewById(R.id.rec_log_class)).setText(log.grade);
((TextView) convertView.findViewById(R.id.rec_log_count)).setText(String.valueOf(logsList.size()));
((TextView) convertView.findViewById(R.id.rec_logs_mass)).setText(String.format("%.2f m3", log.getM3()));
if (log.receipt.priceType.equals("Na panju")) {
((TextView) convertView.findViewById(R.id.rec_log_price_default)).setText(String.valueOf(log.price.stumpPrice_kn));
} else {
((TextView) convertView.findViewById(R.id.rec_log_price_default)).setText(String.valueOf(log.price.roadPrice_kn));
}
if (log.receipt.priceType.equals("Na panju")) {
((TextView) convertView.findViewById(R.id.rec_calculated_price)).setText(String.format("%.2f KN", log.price.stumpPrice_kn * log.getM3()));
} else {
((TextView) convertView.findViewById(R.id.rec_calculated_price)).setText(String.format("%.2f KN", log.price.roadPrice_kn * log.getM3()));
}
return convertView;
}
}
}
I'm using ActiveAndroid and displaying this in listview.
PROBLEM is with displaying these grouped items. I’m displaying them in BaseAdapter listView and it shows me only one item per group but it needs to show me multiple items (because it has more than 4 items in each group).
Can anyone give me advice what should I do to get output like on first image?
It looks like you are trying to get results similar to the following SQL:
select sort, grade, count(grade), sum(mass), price from logs where receiptid = forwardedId group by sort, grade;
You show the displayed count computed as logList.size(). Instead, if you are going to have the database group the records, you will want to get the count from the database as well.
A couple of things may also help.
1. Verify the SQL query directly against the database to verify you are starting with the intended result set. You can use the sqlite3 client to test assuming you are using an SQLite db.
2. Enable ActiveAndroid logging in ActiveAndroid.initialize
Also you might double check the parameter spelling to make sure you are referencing the intended intent parameter.
Once you verify that the query results are correct, you can focus on whether you are rendering it in the list as you wish.
Finally be wary of doing work on the UI thread.
User 'user650881' is right (I cannot vote since repo < 50).
Additionally to achieve the summary for the total table you may execute the following SQL query:
select /*sort, grade,*/ count(grade), sum(mass), price from logs where receiptid = forwardedId /*group by sort, grade*/;
if you would like to have the items grouped by different fields you may also try widow functions i.e.:
select count(grade) over(partition by fieldName)
and group by is eventually not necessary
In my activity, I am creating a dynamic radiogroup. I have some questions and answers in Sqlite database, retrieving them in activity and then set in RadioGroup. This is working fine. But after that, I want to get all ID of selected radio button by user to store them in database. In general, we do something like this when we have option's ID :
id1=rdgroup1.getCheckedRadioButtonId();
que1=(RadioButton)findViewById(id1);
ans1=que1.getId()+""; // so here I will get radio button's ID.
So my questions is, how will I get selected radio button's ID. Here's my code for dynamically creating radiogroup.
LinearLayout mLinearLayout = (LinearLayout) findViewById(R.id.linear1);
c1=db.rawQuery("SELECT * FROM QueTable WHERE AgeGroup='10-20'", null);
c1.moveToFirst();
int i = c1.getCount();
if(i > 0)
{
Log.w("START", "start");
while (i > 0)
{
TextView title = new TextView(this);
questions = c1.getString(1);
title.setText(questions);
title.setTextColor(Color.BLACK);
mLinearLayout.addView(title);
// create radio button
answers=c1.getString(2);
String[] answer = answers.split(",");
rb = new RadioButton[5];
rg = new RadioGroup(this);
rg.setOrientation(RadioGroup.VERTICAL);
int k = answer.length;
for (int j = 0; j < k; j++)
{
rb[j] = new RadioButton(this);
rg.addView(rb[j]);
rb[j].setText(answer[j]);
}
mLinearLayout.addView(rg);
c1.moveToNext();
i--;
}
}
The place where you create RadioButton set and Id to it
for (int j = 0; j < k; j++)
{
RadioButton rb = new RadioButton(this);
rb.setId(Somenumber + j)
rb[j] = rb;
rg.addView(rb[j]);
rb[j].setText(answer[j]);
}
Like this you can setId or also if you want you can add tag to process.
rb.setTag(SomeObject)
You need to set an ID for your programmatically created RadioButton in order to find it using findViewById as you show in your first code.
To set the ID for your RadioButton, you can use View.setId(). The documentation says:
Sets the identifier for this view. The identifier does not have to be
unique in this view's hierarchy. The identifier should be a positive
number.
The identifier does not have to be unique, but if it's not unique, findViewById will return the first occurence, so you can use the static method View.generateViewId added on API level 17.
If you are using lower APIs, you may want to write your own function to find a suitable (unused) ID. You can take a look at Android: View.setID(int id) programmatically - how to avoid ID conflicts?
Ok..So finally I got the solution. I am going to share complete code here that will create dynamically radiogroup and radiobuttons from database. Here is code below :
private static final int RB_ID = 100;
int k=0,len=0,r=0,p = 0,q=0, len = 0;
LinearLayout mLinearLayout = (LinearLayout) findViewById(R.id.linear1);
c1 = db.rawQuery("SELECT * FROM QueMotion WHERE AgeGroup ='"+Age+"' LIMIT 5", null);
c1.moveToFirst();
int i = c1.getCount();
rg = new RadioGroup[i];
rb = new RadioButton[i*5];
if (i > 0) {
Log.w("START", "start");
while (i > 0)
{
TextView title = new TextView(this);
questions = c1.getString(1);// retrive from database
title.setText(questions);
title.setTextColor(Color.BLACK);
title.setTypeface(null, Typeface.BOLD);
title.setPadding(0, 0, 0, 10);
mLinearLayout.addView(title);
answers = c1.getString(2);// retrive from database
String[] answer = answers.split(",");// will create options for radio button.
rg[p] = new RadioGroup(this);
rg[p].setOrientation(RadioGroup.VERTICAL);
len=len+answer.length;
for (int j = 0; j < answer.length; j++)
{
rb[q] = new RadioButton(this);
rg[p].addView(rb[q]);
rb[q].setId(k + RB_ID);
rb[q].setText(answer[j]);
k++;
q++;
}
mLinearLayout.addView(rg[p]);
c1.moveToNext();
i--;
p++;
}
//Submit button click
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
if (rg[0].getCheckedRadioButtonId() == -1)
{
Log.e("Nothing selected", "Nothing selected");
}
else
{
for (r = 0; r < len; r++) {
if (rb[r].isChecked()) {
RadioButton id = (RadioButton) findViewById(rb[r].getId());
String radioText = id.getText().toString();
c3.moveToFirst();
Log.e("RadioString", radioText);
} else {
Log.e("RadioString", "nothing");
}
}
}
}
});
i use following code to remove rows out off my tablelayout;
System.out.println(vi); gives me 4 unique rows and thats right but why my loop is not removing all rows at once. I need to click 3 times.
This code is placed in myOnclickHandler;
public void onClick(View v) {
TableLayout container = (TableLayout) v.getParent().getParent();
int childcount = container.getChildCount();
View vi;
for (int i = 0; i < childcount; i++) {
vi = container.getChildAt(i);
container.removeView(vi);
System.out.println(vi);
}
}
try it :
row = (TableRow)findViewById(R.id.row);
table.removeView(row);
use this it keep only header row.
if (table.getRootView() != null) {
int i = 1;
while (table.getChildCount() != 1) {
table.removeViewAt(i);
}
}
i have written something like this....
TableRow tr1;
TableRow tr2;
TextView txt9;
...
TableLayout tl = (TableLayout)findViewById(R.id.myTableLayout);
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(width, LayoutParams.FILL_PARENT);
for (int i = 0; i < strarr.length-1; i++)
{
strinarr = fun1.split(strarr[i].trim(),"^");
tr1 = (TableRow) new TableRow(this);
txt1=new TextView(this);
txt9.setText(strinarr[0]);
txt9.setBackgroundColor(intblue);
txt9.setTextColor(intwhite);
txt9.setClickable(true);
txt9.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Log.i("pagename",strpagename);
String currenttext = txt9.getText().toString());
}
}
});
tr1.addView(txt9);
tl.addView(tr1,new TableLayout.LayoutParams(layoutParams));
}
i am able to get text on click but the stupid thing is that i am getting text of last textview in the table on all the textview click event... if somebody could tell me how to catch textview's text on focus or touch it would be really help full...
change String currenttext = txt9.getText().toString()); to String currenttext = ((TextView)v).getText().toString());
You should probably maintain a list of ID's in the table and a list of corresponding texts. When the user clicks on the widget with the given ID, simply look up the text in the textlist and set it.
ArrayList qty = new ArrayList();
for(int i = 1; i <= 10; i++)
{
qty.add(i);
}
for(int i = 0; i < 5; i++)
{
TableRow tr = new TableRow(this);
Spinner tvQtySpinner = new Spinner(this);
tvQtySpinner.setOnItemSelectedListener(this);
ArrayAdapter<String> aa =
new ArrayAdapter<String> this, android.R.layout.simple_spinner_item, qty);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
tvQtySpinner.setAdapter(aa);
tr.addView(tvQtySpinner);
TextView tvRate = new TextView(this);
tvRate.setText(value.getPrice().toString());
tvRate.setTextColor(Color.YELLOW);
tr.addView(tvRate);
}
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id)
{
Integer value = (Integer) parent.getItemAtPosition(pos);
Float result = value*50;
tvRate.setText(String.valueOf(result));
}
Here I am having 5 rows, each row having 5 dynamic spinners and text views. I am getting the selected value from spinner and doing calculation and am trying to set that calculated result in particular rows TextView. But when I set the calculated value in TextView it will set on last rows TextView.