Dynamically checking CheckBoxes in Android - android

I have 3 row in table, where every row has 3 checkbox. I want to check appropriate CheckBox according to its id.
I have to check following ids CheckBox.
tempArray =[1-2-3,3-2,null];
i am already splitting these data and putting in string array(setopts).more see my code.
Null for no check any CheckBox with this row.
I am doing this code in my project.
Vector<CheckBox> chkBoxList = new Vector<CheckBox>();
Vector<TextView> txtViewList = new Vector<TextView>();
// mat_elemItemSetChk.get(0).size() OF VALUE IS 3
for (int n = 0; n < mat_elemItemSetChk.get(0).size(); n++) {
LinearLayout llayout = new LinearLayout(getContext());
ll.setOrientation(android.widget.LinearLayout.VERTICAL);
cb = new CheckBox(getContext());
tv = new TextView(getContext());
for (int r = 0; r < tempArray.size() ; r++) {
isContains=tempArray.get(r).contains(individualValueSeparator);
if(isContains){
setOpts = tempArray.get(r).split("\\-");
for (int k = 0; k < setOpts.length; k++)
{
ItemValue iv = (ItemValue) mat_elemItemSetChk.get(0).get(n);
if (((int) iv.getId()) == Integer.parseInt(setOpts[k]))
{
mat_elemItemSetChk.get(n).get(Integer.parseInt(setOpts[k])-1);
cb.setChecked(true);
}
}
}else{
if(tempArray.get(r).toString().equalsIgnoreCase("null")||tempArray.get(r).toString()!=null){
String temp;
String px[]= null;
temp = tempArray.get(r).toString();
ItemValue iv = (ItemValue) mat_elemItemSetChk.get(0).get(n);
if (((int) IV.getId()) == Integer.parseInt(temp))
{
mat_elemItemSetChk.get(0).get(Integer.parseInt(temp) - 1);
cb.setChecked(true);
}
}else{
cb.setChecked(false);
}
}
}
tv.setText(mat_elemItemSetChk.get(0).get(n) .toString());
llayout.addView(cb);
llayout.addView(tv);
chkBoxList.add(cb);
txtViewList.add(tv);
ll.addView(llayout);
// this.addView(tableLayout);
}
Thank you in advance.

make an array selchkboxlist and store the selected checkbox id in it and check condition like selchkboxlist.isEmpty() if true then then show error msg other wise go ahed...
selchkboxlist=new ArrayList<String>();
cbs = new CheckBox[8];
// generate dynamic item check box code
for(int k = 0; k<8; k++)
{
cbs[k] = new CheckBox(getApplicationContext());
#SuppressWarnings("deprecation")
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
rl.addView(cbs[k], params);
int j =k+1;
cbs[k].setText("ITEM" + j);
cbs[k].setTextColor(Color.parseColor("#000000"));
cbs[k].setId(k+1);
cbs[k].setPadding(70, 20, 10, 10);
// check box on click listener for add in to produduct array with quntity
cbs[k].setOnClickListener( new View.OnClickListener()
{
public void onClick(View v)
{
String chk = null;
if (((CheckBox) v).isChecked()) {
chk = Integer.toString(v.getId());
selchkboxlist.add(chk);
} else {
selchkboxlist.remove(chk);
}
}
});
}
// button on click listener code
b.setOnClickListener(new OnClickListener() {
#SuppressLint("SdCardPath")
public void onClick(View v) {
if (! selchkboxlist.isEmpty()) {
shoe erroe msg here
}else{
go ahed
}
}
});

Related

how can i get value from dynamically generated edittexts?

I am getting only a single value.how can i get data from all of the editText which i have created dynamically so that i can pass all editText data using comma after every editText .
Here is my code:
Diagnolist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText ed;
Integer count = 1;
final List<EditText> allEds = new ArrayList<EditText>();
for (int i = 0; i < count; i++) {
ed = new EditText(MainActivity.this);
allEds.add(ed);
ed.setId(i);
ed.setHint("add diagonis");
ed.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
addDiagnosis.addView(ed);
}
Toast_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String[] strings = new String[(allEds.size())];
String st = "";
for(int i=0; i < allEds.size(); i++){
strings[i] = allEds.get(i).getText().toString();
st = strings[i]+"," +st;
Toast.makeText(MainActivity.this, st, Toast.LENGTH_SHORT).show();
}
}
});
}
});
do changes as per below code.
final List<EditText> allEds = new ArrayList<EditText>();
declare above list after class define.
Diagnolist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText ed;
Integer count = 1;
for (int i = 0; i < count; i++) {
ed = new EditText(MainActivity.this);
allEds.add(ed);
ed.setId(i);
ed.setHint("add diagonis");
ed.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
addDiagnosis.addView(ed);
}
Toast_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String[] strings = new String[(allEds.size())];
String st = "";
for(int i=0; i < allEds.size(); i++){
strings[i] = allEds.get(i).getText().toString();
st += strings[i]+",";
Toast.makeText(MainActivity.this, st, Toast.LENGTH_SHORT).show();
}
}
});
}
});
I'm not sure what you mean, so correct me if i am wrong. I think you want to get a comma-separated String of all values.
I would just change the onClick to following:
#Override
public void onClick(View view) {
String st;
for(EditText ed : allEds){
st += "," + ed.getText().toString();
}
st = st.substring(1); // cut leading comma
Toast.makeText(MainActivity.this, st, Toast.LENGTH_SHORT).show();
}

Get all the selected radio button and check box value created dyamically?

I want to save all the selected answer(checkbox and radiobutton) and its corresponding question which is set in dynamic Textview in sqlite db ,
but the problem is when i am clicking "save button" only last selected
radio button value is saved to sqlite , not all selected value and not able to get all selected check box value also .
Please help me .
save= (Button) findViewById(R.id.save);
save.setOnClickListener(this);
ll = (LinearLayout) findViewById(R.id.linearLayout1);
for (int j = 0; j < Questions.length; j++) {
tv = new TextView(this);
tv.setId(j);
tv.setText(Questions[j].getQuestionNo() + "."
+ Questions[j].getQuestion());
ll.addView(tv);
Answer[] answer = Questions[j].getAnswer();
if (Questions[j].getMultipleChoice().equalsIgnoreCase("false")) {
rg = new RadioGroup(this);
rg.setOrientation(RadioGroup.VERTICAL);
RadioButton[] rb = new RadioButton[answer.length];
for (int i = 0; i < answer.length; i++)
{
// add radio buttons
rb[i] = new RadioButton(this);
rb[i].setText(answer[i].getLabel());
int id = Integer.parseInt(j + "" + i);
rb[i].setId(id);
rg.addView(rb[i]);
}
ll.addView(rg);
else
{
// add checkboxes
for (int i = 0; i < answer.length; i++) {
cb = new CheckBox(this);
cb.setText(answer[i].getLabel());
int id = Integer.parseInt(j + "" + i);
cb.setId(id);
ll.addView(cb);
}
}
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.save:
if (rg.getCheckedRadioButtonId() != -1) {
int id = rg.getCheckedRadioButtonId();
View radioButton = rg.findViewById(id);
int radioId = rg.indexOfChild(radioButton);
RadioButton btn = (RadioButton) rg.getChildAt(radioId);
String answer = (String) btn.getText();
//only last selected radio button value is coming
}
// not able to get all the selected checkbox value
break;
default:
break;
}
}
I don't know android.But the issue arise me in struts2.I solved that issue by generating dynamic checkbox like below.
<s:iterator value="samplelist">
<input type="checkbox" value="true" style="margin-top:2px;" name="p_<s:property value='profileId'/>
</s:iterator>
so i have found out if it is checked or not in java code by using the for loop
for(int i=0;i<samplelist.size();i++)
request.getParameter("P_something");

How to make sure at least 1 checkbox is checked?

Hi I am making some sort of quiz application and I want to make sure the user checks at least 1 check box.
I am creating the the check boxes like this:
LinearLayout mLinearLayout = (LinearLayout) findViewById(R.id.linear1);
arrGroup = new ArrayList<RadioGroup>();
try
{
for (int i = 0; i < question.length ; i++)
{
if(question[i].multichoice == true)
{
TextView title2 = new TextView(this);
title2.setText(question[i].questionName);
title2.setTextColor(Color.BLACK);
mLinearLayout.addView(title2);
for(int zed = 0; zed < question[i].answers.length; zed++)
{
final CheckBox box = new CheckBox(this);
box.setText(question[i].answers[zed].answer);
box.setId(zed);
mLinearLayout.addView(box);
int flag = 0;
if(box.isChecked() == true)
{
flag = 1;
}
if(flag == 1)
{
Toast.makeText(getApplicationContext(), "hi", Toast.LENGTH_SHORT).show();
}
}
}
else
{
// create text button
TextView title = new TextView(this);
title.setText(question[i].questionName);
title.setTextColor(Color.BLACK);
mLinearLayout.addView(title);
// create radio button
final RadioButton[] rb = new RadioButton[question[i].answers.length];
RadioGroup radGr = new RadioGroup(this);
// take a reference of RadioGroup view
arrGroup.add(radGr);
radGr.setOrientation(RadioGroup.VERTICAL);
radGr.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
checkQuestionsAnswer();
}
});
for (int j = 0; j < question[i].answers.length; j++) {
rb[j] = new RadioButton(this);
radGr.addView(rb[j]);
rb[j].setText(question[i].answers[j].answer);
}
mLinearLayout.addView(radGr);
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
But I cant figure out how to make sure the user has checked at least 1 box.
Maybe you can try this method?
private boolean checkSelectionExists() {
boolean selectionExists = false;
selectionExists = (boolean) ((CheckBox) findViewById(R.id.main_checkbox1)).isChecked() ? true : false ||
(boolean) ((CheckBox) findViewById(R.id.main_checkbox2)).isChecked() ? true : false ||
(boolean) ((CheckBox) findViewById(R.id.main_checkbox3)).isChecked() ? true : false;
return selectionExists;
}
Add your checkboxes to a list as you create them. then use the
checkbox.isChecked()
routine in a loop to make sure at least 1 is checked.
Look here for the checkbox API
http://developer.android.com/reference/android/widget/CheckBox.html
and here for a list:
http://developer.android.com/reference/java/util/List.html\
// Added List
List<Checkbox> ansList = new List<Checkbox>();
// YOUR CODE with the list addition
for (int i = 0; i < question.length ; i++){
if(question[i].multichoice == true){
TextView title2 = new TextView(this);
title2.setText(question[i].questionName);
title2.setTextColor(Color.BLACK);
mLinearLayout.addView(title2);
for(int zed = 0; zed < question[i].answers.length; zed++){
final CheckBox box = new CheckBox(this);
box.setText(question[i].answers[zed].answer);
box.setId(zed);
// Since a test, make sure no answer is checked
box.setChecked(false);
// Add the checkbox to YOUR list of boxes
ansList.add(box);
mLinearLayout.addView(box);
}
}
}
// Later you can check with this
boolean atLeastOne = false;
for (int i = 0; i < question.length ; i++){
if(question[i].multichoice == true){
for(int zed = 0; zed < question[i].answers.length; zed++){
if(ansList.get(zed).isChecked()) atLeastOne = true;
}
}
}
if(true == atLeastOne){
// Do whatever you want to do if at least one is checked
}
I have NOT actually run or checked this code, but this should get you started, and it SHOULD work.
I am giving a quick logic that come after reading your question,
create a class level boolean variable named isCheckButtonClicked
set by default its value to false
Now on each checkbox's click event set its value to true
Now at the final if you found it's value to true that means atleast one checkbox was cliked
Just make a flag and check every time, if a check-box is true make it = "1"and at last check whether it is "1" or not
Something like
Box[0]=name_of_first_Checkbox;
Box[1]=name_of_second_Checkbox;
// and so on..
int flag = 0;
for (int i = 0; i < x ; i++){
if(Box[i].isChecked())
{
flag =1;
}
}
if(flag==1){
//At least 1 box is checked
}

Android Quiz application - making sure all questions are answered

As you can see below, I am dynamically creating some sort of quiz with different types of questions (RadioButtons and CheckBoxes).
So I can generate them correctly and they appear as they should.
At the end of the questions there is a normal Button.
And I want to make it available for click only after all the questions have been answered.
I have a function to make sure that all the RadioButtons are answered.
But since I have two types of buttons I can't figure out how to make sure that the questions with the CheckBox answers have at least 1 checked answer.
I have the following code:
ArrayList<RadioGroup> arrGroup;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
buttHole = (Button) findViewById(R.id.button1);
buttHole.setEnabled(false);
getQuestions();
//Creating the list of Questions
LinearLayout mLinearLayout = (LinearLayout) findViewById(R.id.linear1);
arrGroup = new ArrayList<RadioGroup>();
try
{
for (int i = 0; i <= question.length; i++)
{
if(question[i].multichoice == true)
{
TextView title2 = new TextView(this);
title2.setText(question[i].questionName);
title2.setTextColor(Color.BLACK);
mLinearLayout.addView(title2);
for(int zed = 0; zed < question[i].answers.length; zed++)
{
CheckBox box = new CheckBox(this);
box.setText(question[i].answers[zed].answer);
box.setId(zed);
mLinearLayout.addView(box);
}
}
else
{
// create text button
TextView title = new TextView(this);
title.setText(question[i].questionName);
title.setTextColor(Color.BLACK);
mLinearLayout.addView(title);
// create radio button
final RadioButton[] rb = new RadioButton[question[i].answers.length];
RadioGroup radGr = new RadioGroup(this);
// take a reference of RadioGroup view
arrGroup.add(radGr);
radGr.setOrientation(RadioGroup.VERTICAL);
radGr.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
checkQuestionsAnswer();
}
});
for (int j = 0; j < question[i].answers.length; j++) {
rb[j] = new RadioButton(this);
radGr.addView(rb[j]);
rb[j].setText(question[i].answers[j].answer);
}
mLinearLayout.addView(radGr);
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
public boolean checkQuestionsAnswer()
{
int count = arrGroup.size();
for (int i = 0; i < count; i++)
{
if (arrGroup.get(i).getCheckedRadioButtonId() == -1)
{
Toast.makeText(getApplicationContext(), "Not all questions are answered!", Toast.LENGTH_SHORT).show();
return false;
}
}
Toast.makeText(getApplicationContext(), "Thank you!", Toast.LENGTH_SHORT).show();
buttHole.setEnabled(true);
//Return true if all answer are given
return true;
}
If you have less than 10 answers per question set the id of the checkboxes to (i*10)+zed for example. This way you could loop through the answers like this
for(int i=0; i<question.length; i++){
boolean questionAnswered = false;
for(int zed = 0; zed < question[i].answers.length; zed++) {
CheckBox box = (CheckBox) findViewById(i*10+zed);
if(box != null && box.isChecked()) {
questionAnswered = true;
...
}
}
}
I didn't try this code, and it's just a quick and dirty hint, but I hope it helps.

Getting id of imageview

I am making a number of imageViews programmatically in a loop and assigning them ids. But when in onClick method I need to get the id of images, it is returning the id of the last image only. How do I get the id of the image that is clicked?
The code I am using:
for (int j = 0; j < 5; j++) {
TableRow tr = new TableRow(this);
imageUrl = "http://ondamove.it/English/images/users/";
imageUrl = imageUrl + listObject.get(j).getImage();
image = new ImageView(this);
image.setPadding(20, 10, 0, 0);
image.setId(j+1);
tr.addView(image);
try {
new DownloadFileAsync(image, new URL(imageUrl))
.execute(imageUrl);
images.add(image);
//images = new ImageView[5];
}
catch (Exception e) {
e.printStackTrace();
}
tr.addView(image);
table.addView(tr, new TableLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
image.setOnClickListener(clickImageListener);
Following is the onclicklistener.
private OnClickListener clickImageListener = new OnClickListener() {
public void onClick(View v) {
imageId = image.getId();
Intent fullScreenIntent = new Intent(v.getContext(),FullImageActivity.class);
fullScreenIntent.putExtra(ProfilePageNormalUser.class.getName(),imageId);
ProfilePageNormalUser.this.startActivity(fullScreenIntent);
}
};
Inside the onClick(View v) method you can call v.getId() - this will return you the ID of the View being clicked. Hope this helps.
Try this out:
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int index = 0;
for (int i = 0; i < image.length; i++)
{
if (image[i].getId() == v.getId())
{
index = i;
break;
}
}
Toast.makeText(this, "Image clicked index => "+index, Toast.LENGTH_SHORT).show();
}

Categories

Resources