Dynamically added views do not reset? - java

I have a LinearLayout in which I am adding some CheckBoxes dynamically, they are adding perfectly well on first call, when I am calling the same method with different values, then they are not appearing in that LinearLayout, old values are not getting replaced with new values.
I checked values in LogCat and they seem fine, whatever I'm passing is being displayed in LogCat but not appearing in LinearLayout.
Here's my method that adds the view:
private void setOptions(int questionID2) {
ArrayList<String> options = pustakDB.getOptions(questionID2);
Log.e("optionsInAct", options.toString() + " size " + options.size());
OptionView = new LinearLayout(this);
OptionView.setOrientation(LinearLayout.VERTICAL);
RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
p.addRule(RelativeLayout.BELOW, img.getId());
p.addRule(RelativeLayout.RIGHT_OF, questionNumber.getId());
rel.addView(OptionView, p);
int i = 0;
while (i < options.size()) {
CheckBox c = new CheckBox(this);
c.setText(options.get(i));
c.setId(i);
OptionView.addView(c);
i++;
}
}
Edit: "rel" here is RelativeLayout.

// put this somewhere else
OptionView = new LinearLayout(this);
OptionView.setOrientation(LinearLayout.VERTICAL);
RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
p.addRule(RelativeLayout.BELOW, img.getId());
p.addRule(RelativeLayout.RIGHT_OF, questionNumber.getId());
rel.addView(OptionView, p);
private void setOptions(int questionID2) {
ArrayList<String> options = pustakDB.getOptions(questionID2);
Log.e("optionsInAct", options.toString() + " size " + options.size());
// this will remove all views from OptionView
OptionView.removeAllViews();
int i = 0;
while (i < options.size()) {
CheckBox c = new CheckBox(this);
c.setText(options.get(i));
c.setId(i);
OptionView.addView(c);
i++;
}
}
Try this and see if it works.

Related

How do I set margins for my Android app table?

I am trying a add rows to my table by pressing a button, I can add the rows but I don't know how to add layout to the added row.
Here is my code:
public void testRow(View view) {
// get a reference for the TableLayout
TableLayout table = (TableLayout) findViewById(R.id.accountTable);
// create a new TableRow
TableRow row = new TableRow(this);
TextView x = new TextView(this);
x.setText("text ");
row.addView(x);
TextView y = new TextView(this);
y.setText("text ");
row.addView(y);
TextView z = new TextView(this);
z.setText("text ");
row.addView(z);
// add the TableRow to the TableLayout
table.addView(row);
}
You should add TableRow to TableLayout with LayoutParams, then you can also set the margins with it:
LayoutParams params = table.generateDefaultLayoutParams();
params.leftMargin = ...
params.rightMargin = ...
table.addView(row, params);

how to add dynamic grid layout in android by only programmatically?

I want to add layout dynamically in my android app using java code only, not using XML code. Kindly help me with this. Advance thank you.
with using this code I had done this :
public void makeSeat()
{
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.setMargins(3,3,3,3);
GridLayout gl = (GridLayout) findViewById(R.id.grid_main);
int column = 4;
int row = 5;
int i_total = 4*5;
int i_busSeatNo = 1;
gl.setAlignmentMode(GridLayout.ALIGN_BOUNDS);
gl.setColumnCount(column);
gl.setRowCount(row + 1);
CheckBox btn;
for(int i =0, c = 0, r = 1; i < i_total; i++, c++)
{
if(c == column)
{
c = 0;
r++;
i_busSeatNo++;
}
if (r == c+1 ){
i_busSeatNo = r;
}
btn = new CheckBox(this);
btn.setGravity(Gravity.CENTER);
btn.setBackgroundResource(R.drawable.chbox);
btn.setButtonDrawable(R.drawable.chbox);
btn.setHeight(val_seat);
btn.setWidth(val_seat);
btn.setText(""+i_busSeatNo); //(r+" "+c); //r+" "+c
int cnt = Integer.parseInt(r+""+c);
btn.setId(cnt);
final CheckBox finalBtn = btn;
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(DynamicBus.this,
"id: " + finalBtn.getId() + "\nNo: " + finalBtn.getText(),
Toast.LENGTH_SHORT).show();
}
});
if(c != column-1) {
i_busSeatNo = i_busSeatNo+5;
}
gl.addView(btn, i);
GridLayout.LayoutParams param =new GridLayout.LayoutParams();
param.height = val_seat;
param.width = val_seat;
param.rightMargin = 7;
param.topMargin = 7;
param.setGravity(Gravity.CENTER);
param.columnSpec = GridLayout.spec(c);
if (r==1)
param.rowSpec = GridLayout.spec(r,1);
btn.setLayoutParams (param);
}
}
Output :
what I get :
https://i.stack.imgur.com/FqynC.png
what I want :
https://i.stack.imgur.com/QZCTI.png

radio group not working and vertical alignment android

JSONArray jsonQuestion = new JSONArray(obj.get("question").toString());
for (int iii = 0; iii < jsonQuestion.length(); iii++) {
LinearLayout lll = new LinearLayout(Questionnaire.this);
lll.setOrientation(LinearLayout.VERTICAL);
JSONObject obj2 = (JSONObject) jsonQuestion.get(iii);
System.out.println(obj2.get("question"));
TextView tv = new TextView(Questionnaire.this);
tv.setText(obj2.get("question").toString());
lll.addView(tv);
JSONArray jsonAnswer = new JSONArray(obj.get("answer").toString());
Log.d("Reading Answer: ", jsonAnswer + "");
for (int iiii = 0; iiii < jsonAnswer.length(); iiii++) {
JSONObject obj3 = (JSONObject) jsonAnswer.get(iiii);
System.out.println(obj2.get("questiosysid").toString().matches(obj3.get("questionid").toString()));
if (obj2.get("questiosysid").toString().matches(obj3.get("questionid").toString())) {
TextView tv1 = new TextView(Questionnaire.this);
tv1.setText(obj3.get("inputname").toString());
RadioGroup group = new RadioGroup(Questionnaire.this);
group.setOrientation(RadioGroup.HORIZONTAL); // RadioGroup.HORIZONTAL or RadioGroup.VERTICAL
if (obj3.get("inputtype").toString().matches("radio")) {
RadioButton newRadioButton = new RadioButton(Questionnaire.this);
newRadioButton.setId(Integer.parseInt(obj3.get("answerid").toString()));
newRadioButton.setText(obj3.get("inputname").toString());
group.addView(newRadioButton);
lll.addView(group);
}
}
}
ll.addView(lll);
}
This is my code for dynamically adding radio button.
Problem is when I select one option then select anther it does not deselect the previous one. Why doesn't it deselect the the first one selecting another when they are both added to same radio group. Also it is not placing the radio buttons next to each other but on top of each other when the orientation is set to horizontal
UPDATE
I moved my declaration of
RadioGroup group = new RadioGroup(Questionnaire.this);
group.setOrientation(RadioGroup.HORIZONTAL); // RadioGroup.HORIZONTAL or RadioGroup.VERTICAL
out side parent for loop now i am getting
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
How should i deal with it?
you are added only one RadioButton in RadioGroup that's why you got many selected radio button. RadioGroup need minimum 2 RadioButton for check or Uncheck effect.
try this,I hope it may work.
JSONArray jsonQuestion = new JSONArray(obj.get("question").toString());
for (int iii = 0; iii < jsonQuestion.length(); iii++) {
LinearLayout lll = new LinearLayout(Questionnaire.this);
lll.setOrientation(LinearLayout.VERTICAL);
JSONObject obj2 = (JSONObject) jsonQuestion.get(iii);
System.out.println(obj2.get("question"));
TextView tv = new TextView(Questionnaire.this);
tv.setText(obj2.get("question").toString());
lll.addView(tv);
JSONArray jsonAnswer = new JSONArray(obj.get("answer").toString());
Log.d("Reading Answer: ", jsonAnswer + "");
RadioGroup group = new RadioGroup(Questionnaire.this);
group.setOrientation(RadioGroup.HORIZONTAL); // RadioGroup.HORIZONTAL or RadioGroup.VERTICAL
for (int iiii = 0; iiii < jsonAnswer.length(); iiii++) {
JSONObject obj3 = (JSONObject) jsonAnswer.get(iiii);
System.out.println(obj2.get("questiosysid").toString().matches(obj3.get("questionid").toString()));
if (obj2.get("questiosysid").toString().matches(obj3.get("questionid").toString())) {
TextView tv1 = new TextView(Questionnaire.this);
tv1.setText(obj3.get("inputname").toString());
if (obj3.get("inputtype").toString().matches("radio")) {
RadioButton newRadioButton = new RadioButton(Questionnaire.this);
newRadioButton.setId(Integer.parseInt(obj3.get("answerid").toString()));
newRadioButton.setText(obj3.get("inputname").toString());
group.addView(newRadioButton);
}
}
}
lll.addView(group);
ll.addView(lll);
}
try like this i have make code as you want.
ScrollView scrollView = (ScrollView) findViewById(R.id.templayout);
LinearLayout mLinearLayout = new LinearLayout(this);
mLinearLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
mLinearLayout.setOrientation(LinearLayout.VERTICAL);
scrollView.addView(mLinearLayout);
JSONArray jsonQuestion = new JSONArray(obj.get("question").toString());
for (int iii = 0; iii < jsonQuestion.length(); iii++) {
JSONObject obj2 = (JSONObject) jsonQuestion.get(iii);
System.out.println(obj2.get("question"));
TextView tv = new TextView(Questionnaire.this);
tv.setText(obj2.get("question").toString());
mLinearLayout.addView(tv);
JSONArray jsonAnswer = new JSONArray(obj.get("answer").toString());
Log.d("Reading Answer: ", jsonAnswer + "");
RadioGroup group = new RadioGroup(Questionnaire.this);
group.setOrientation(RadioGroup.HORIZONTAL); // RadioGroup.HORIZONTAL or RadioGroup.VERTICAL
for (int iiii = 0; iiii < jsonAnswer.length(); iiii++) {
JSONObject obj3 = (JSONObject) jsonAnswer.get(iiii);
System.out.println(obj2.get("questiosysid").toString().matches(obj3.get("questionid").toString()));
if (obj2.get("questiosysid").toString().matches(obj3.get("questionid").toString())) {
TextView tv1 = new TextView(Questionnaire.this);
tv1.setText(obj3.get("inputname").toString());
if (obj3.get("inputtype").toString().matches("radio")) {
RadioButton newRadioButton = new RadioButton(Questionnaire.this);
newRadioButton.setId(Integer.parseInt(obj3.get("answerid").toString()));
newRadioButton.setText(obj3.get("inputname").toString());
group.addView(newRadioButton);
}
}
}
mLinearLayout.addView(group);
}
}

How do I get the value of the contents inside a row of a tablelayout

I need to get the value of an EditText inside a row of a tablelayout. I create the table, the row and the edittext dynamically. I had help getting the childcount, but I still can't seem to get the text that is inputted by the user into the edittext. Here's the xml code creating the base layout.
<RelativeLayout xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = "com.example.neil.hvacbuilder.MainActivity" >
<ScrollView
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:id = "#+id/scrollView"
android:layout_alignParentLeft = "true"
android:layout_alignParentStart = "true"
android:layout_below = "#+id/imgPartPicked" >
<TableLayout
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:stretchColumns="*"
android:id = "#+id/tblLayoutContent"
android:layout_alignParentLeft = "true"
android:layout_alignParentStart = "true"
android:layout_alignParentBottom = "true" >
</TableLayout >
</ScrollView >
</RelativeLayout >
Here's the code that generates the row and the edittexts inside the row.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.part_detail);
Bundle bundle = getIntent().getExtras();
String btnName = bundle.getString("btnNameStored");
String btnOrig = bundle.getString("btnOrig");
TextView textView = (TextView) findViewById(R.id.txtBtnPushed);
textView.setText(btnOrig);
BufferedReader reader;
InputStream is = null;
// Get the name of the part picked and then grab the dimensions that are needed for that
// part.
try {
is = getAssets().open(btnName);
reader = new BufferedReader(new InputStreamReader(is));
String line = reader.readLine();
int lineLength = (line.length());
TableLayout table = (TableLayout) findViewById(R.id.tblLayoutContent);
while (line != null){
TableRow tblRow = new TableRow(this);
tblRow.setPadding(5, 30, 5, 5);
table.addView(tblRow);
line = line.toUpperCase();
// sets the max number of columns to 2 and iterates through the number of lines.
// filling each cell with a Text Box with the name of each dimension of the part
// that was picked. And a EditView for the user to put in the dimensions.
for (int col = 0; col < NUM_COL; col++) {
//This is the label of what measurement needs to be enter.
TextView lblName = new TextView(this);
// This is the number you enter for the measurement.
EditText txtPartMeasurement = new EditText(this);
txtPartMeasurement.setInputType(InputType.TYPE_CLASS_NUMBER |
InputType.TYPE_NUMBER_FLAG_DECIMAL);
// Set all the input attributes for the text boxes.
txtPartMeasurement.setTextSize(14);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
txtPartMeasurement.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_END);
}
txtPartMeasurement.setEnabled(true);
// Set all the input attributes for the labels of what needs to be entered.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
lblName.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
}
lblName.setBackgroundColor(getResources().getColor(R.color.colorPartMeasurements));
lblName.setFocusable(true);
lblName.setText(line);
lblName.setTextSize(14);
txtPartMeasurement.setTag(line);
// Add the labels and text boxes to the grid.
tblRow.addView(lblName);
tblRow.addView(txtPartMeasurement);
// Get the next line in the file if there is one.
line = reader.readLine();
}
};
}
catch (IOException e) {
e.printStackTrace();
}
}
Here's the code that gives me the values entered by thee user, but it not worky right.
#Override
public void onClick(View v) {
Button button = (Button) v;
String btnText = button.getText().toString();
switch (v.getId()) {
//This is the Save and Continue button. It saves the info entered and goes back to
// pick the next part needed.
case R.id.btnNextPartDetail:
TableLayout PartDetailLayout = ((TableLayout) findViewById(R.id.tblLayoutContent));
int childParts = PartDetailLayout.getChildCount();
if (PartDetailLayout != null) {
for (int i = 0; i < PartDetailLayout.getChildCount(); i++) {
View viewChild = PartDetailLayout.getChildAt(i);
if (viewChild instanceof EditText) {
// get text from edit text
String text = ((EditText) viewChild).getText().toString();
}
else if (viewChild instanceof TextView) {
// get text from text view
String text = ((TextView) viewChild).getText().toString();
//TODO: add rest of the logic
}
}
}
Toast.makeText(getApplicationContext(),
"Button Save/Continue Selected",
Toast.LENGTH_LONG).show();
break;
It gets me the count, but not the value.
I don't know what the id will be of each edittext so I add a tag as each is created. But the tag is also dynamic as it comes from a file.
So, my question is what am I doing wrong and how do I get the value of each edittext. Mind you, there can be 10 or 14 or more edittexts in the table.
Sorry for the long post, but I wanted to be as complete as possible.
Thanks.
Okay, Here's the working code. Again thanks
TableLayout PartDetailLayout = ((TableLayout) findViewById(R.id.tblLayoutContent));
int childParts = PartDetailLayout.getChildCount();
if (PartDetailLayout != null) {
for (int i = 0; i < childParts; i++) {
View viewChild = PartDetailLayout.getChildAt(i);
if (viewChild instanceof TableRow) {
int rowChildParts = ((TableRow) viewChild).getChildCount();
for (int j = 0; j < rowChildParts; j++) {
View viewChild2 = ((TableRow) viewChild).getChildAt(j);
if (viewChild2 instanceof EditText) {
// get text from edit text
String txtEdit = ((EditText) viewChild2).getText()
.toString();
} else if (viewChild2 instanceof TextView) {
// get text from text view
String txttext = ((TextView) viewChild2).getText().toString();
//TODO: add rest of the logic
}
}
}
}
}
The possible problem is that you check childs of TableLayout, but your EditText and TextView are in TableRow, so you need to check childs of childs.
I assume, that would be like that:
TableLayout PartDetailLayout = ((TableLayout) findViewById(R.id.tblLayoutContent));
iTableLayout PartDetailLayout = ((TableLayout) findViewById(R.id.tblLayoutContent));
int childParts = PartDetailLayout.getChildCount();
if (PartDetailLayout != null) {
for (int i = 0; i < childParts; i++) {
View viewChild = PartDetailLayout.getChildAt(i);
if (viewChild instanceof TableRow) {
int rowChildParts = ((TableRow) viewChild).getChildCount();
for (int j = 0; j < rowChildParts; j++) {
View viewChild2 = ((TableRow) viewChild).getChildAt(j);
if (viewChild2 instanceof EditText) {
// get text from edit text
String text = ((EditText) viewChild2).getText().toString();
} else if (viewChild2 instanceof TextView) {
// get text from text view
String text = ((TextView) viewChild2).getText().toString();
//TODO: add rest of the logic
}
}
}
}
}

getting text from dynamically created edittext into a button android java

I have created dynamically edittext on my android application like below:
protected void onCreate(Bundle savedInstanceState) {
RelativeLayout layout = (RelativeLayout) findViewById(R.id.linearLayout1);
final EditText[] Et = new EditText[10];
int prevTextViewId = 0;
int add = 0;
int add1 = 0;
for (int a = 0; a < Arr.length; a++) {
Et[a] = new EditText(this);
RelativeLayout.LayoutParams param = new RelativeLayout.LayoutParams(
(int) LayoutParams.WRAP_CONTENT,
(int) LayoutParams.WRAP_CONTENT);
param.leftMargin = 25;
param.topMargin = (a + 1) * (100 + add1);
Et[a].setPadding(5, 23, 5, 5);
Et[a].setLayoutParams(param);
Et[a].setSingleLine(false);
Et[a].setHorizontalScrollBarEnabled(false);
Et[a].setWidth(280);
Et[a].getText().toString();
layout.addView(Et[a]);
add = add + 25;
add1 = add1 + 15;
}
}
And I want to get text from dynamically created edittext into a button like below:
btn_doneAnswer = (Button) findViewById(R.id.btn_doneAnswer);
btn_doneAnswer.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
for (int a = 0; a < Arr.length; a++) {
Et[a] = new EditText(this);
String text += Et[a].getText().toString();
}
Bundle bundle = new Bundle();
Intent i_backToAddItem = new Intent(
AnswerActivityMultiText.this,
QuestionActivityDynamic.class);
bundle.putString("text", text);
bundle.putString("MultiQues", MultiQues);
i_backToAddItem.putExtras(bundle);
startActivity(i_backToAddItem);
}
});
But I am getting error below in the button onclick method at this line Et[a] = new EditText(this);:
The constructor EditText(new View.OnClickListener(){}) is undefined
another below error at this line += in the button onclick method:
Syntax error on token "+=", = expected
Kindly suggest me how I am getting text from dynamically created edittext into a button.
Waiting for reply.
Thanks
you dont have to initialize the EditText again in the onClick. You should directly use the EditText object to get the text. So the line
Et[a] = new EditText(this);
is not required at all!
And for the error with '+=' operator, you are declaring the string and using the operator(+=) in one line. you have to split up the the declaration part out of the for loop and then use '+='. Here's the complete code :
btn_doneAnswer = (Button) findViewById(R.id.btn_doneAnswer);
btn_doneAnswer.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String text;
for (int a = 0; a < Arr.length; a++) {
text += Et[a].getText().toString();
}
Bundle bundle = new Bundle();
Intent i_backToAddItem = new Intent(
AnswerActivityMultiText.this,
QuestionActivityDynamic.class);
bundle.putString("text", text);
bundle.putString("MultiQues", MultiQues);
i_backToAddItem.putExtras(bundle);
startActivity(i_backToAddItem);
}
});
Your problem is in this lines:
for (int a = 0; a < Arr.length; a++) {
Et[a] = new EditText(this);
String text += Et[a].getText().toString();
}
In this line:
Et[a] = new EditText(this);
this is the onClickListener object, you must have class.this (where class is the class name of file that this code is created).
In this other line:
String text += Et[a].getText().toString();
You always create a new String, and instead of created, you make an add. It is a Java concept fail.
You must do this:
String text = "";
for (int a = 0; a < Arr.length; a++) {
Et[a] = new EditText(class_name.this);
text += Et[a].getText().toString();
}

Categories