How can I add extra TableRows to my TableLayout depending on cursor?
I have a database with different results in my database in my Android project. I want to fetch these results and show them in a tablelayout. In the tablelayout I want to add a row for each result, and write the column "date" on one textview, and the "result" on the second textview. Both textviews are on the same row. I fe开发者_高级运维tch the data and store it in a cursor.
My question is: How do I use the cursor and add a row depending on how much data there is in my database?
Right now I try to add a row for each row in the cursor like this:
TableLayout tl = (TableLayout)findViewById(R.id.table_layout2);
TableRow tr = new TableRow(this);
tr.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
TextView mTvDate = new TextView(this);
TextView mTvResult = new TextView(this);
int x=0;
for(int i=0;i<c.getCount();i++){
mTvDate.setText(date[x]);
mTvResult.setText(""+nocorrect[x]+" av "+ noqs[x] +" ("+ proc[x]+ "%)");
mTvDate.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
mTvResult.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
tr.addView(mTvDate);
tr.addView(mTvResult);
tl.addView(tr,new TableLayout.LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
}
But I think I need to create a NEW tablerow, cause I get this error message:
02-22 09:22:17.543: ERROR/AndroidRuntime(333): Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
But I don't want to remove it, I want to add more. Any ideas? Thanks!
Hi try this i think you adding same row every time. so just declare it every loop iteration.
TableLayout tl = (TableLayout)findViewById(R.id.table_layout2);
int x=0;
for(int i=0;i<c.getCount();i++){
TableRow tr = new TableRow(this);
tr.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
TextView mTvDate = new TextView(this);
TextView mTvResult = new TextView(this);
mTvDate.setText(date[x]);
mTvResult.setText(""+nocorrect[x]+" av "+ noqs[x] +" ("+ proc[x]+ "%)");
mTvDate.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
mTvResult.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
tr.addView(mTvDate);
tr.addView(mTvResult);
tl.addView(tr,new TableLayout.LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
}
精彩评论