check all or uncheck all dynamically created checkboxes in android - android

1.here all my code.
2.for create dynamic checkbox for check or uncheck all checkboxes
{ final String[][] itemContainer = new String[30][7];
TableLayout tblItemDetail;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_code_release);
tblItemDetail = (TableLayout)findViewById(R.id.tblItemDetail);
try {
sqlItem = "";
sqlItem = "SELECT * from itm_mst";
rs = objDbConnect.getResultSet(sqlItem);
if (rs.next()) {
int i1 = 1;
do {
itemContainer[itemCount][0]=Integer.toString(i1++);
itemContainer[itemCount][6]="N"; //checkbox value
itemCount++;
} while (rs.next());
tblItemDetail.removeAllViews();
if (itemCount > 0) {
CheckBox tvchkall = new CheckBox(ItemCodeRelease.this); //header row checkbox for ckeck or uncheck all checkbox
tvchkall.setGravity(Gravity.CENTER);
tvchkall.setPadding(20, 0, 20, 0);
tvchkall.setText("Y");
headerRow1.addView(tvchkall);
tvchkall.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(buttonView.isChecked())
{
for(int a = 0 ; a < itemContainer.length ; a++)
{
for(int b = 0 ; b < itemContainer[a].length ; b++)
{
CheckBox chkb = (CheckBox)tblItemDetail.findViewById(a);
if ( chkb == null )
continue;
chkb.setChecked(true);
Log.i("Checkbox serrch","checked "+chkb.getText()+"ID +chkb.getId());
if(a == chkb.getId())
{
itemContainer[a][6] = "Y";
}
else
{
Log.i("Checkbox serrch","unchecked"+chkb.getText()+"ID "+chkb.getId());
itemContainer[a][6] = "N";
}}}}
});
tblItemDetail.addView(headerRow1);
int alternateRow1 = 0;
for (i = 0; i < itemCount; i++) {
TableRow bodyRow1 = new TableRow(ItemCodeRelease.this);
if (alternateRow1 % 2 == 0) {
bodyRow1.setBackgroundResource(R.color.statusalternateRow);
}
else {
bodyRow1.setBackgroundResource(R.color.statusRow);
}
final CheckBox cb1 = new CheckBox(ItemCodeRelease.this); //body row of checkbox
cb1.setId(i);
cb1.setGravity(Gravity.CENTER);
cb1.setPadding(20, 0, 20, 0);
bodyRow1.addView(cb1);
cb1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
for(int a = 0 ; a < itemContainer.length ; a++)
{
for(int b = 0 ; b < itemContainer[a].length ; b++)
{
if(buttonView.isChecked())
{
Log.i("Checkbox serrch","checked "+buttonView.getText()+"ID "+buttonView.getId());
if(a == buttonView.getId())
{
itemContainer[a][6] = "Y";
continue;
}}
else
{
itemContainer[a][6] = "N";
}}}}
});
bodyRow1.addView(tvBodySRNo1);
tblItemDetail.addView(bodyRow1);
alternateRow1++;
}}}
} catch (Exception e) { e.printStackTrace(); }}

Update [26-01-2016] : You can follow this to Check/UnCheck Dynamically created CheckBoxes.
Inside onCreate(Bundle bundle) { ... } add this :
Few Notes :
You need to give the Base Layout an ID if you use:
setContentView(R.layout.new_layout);
That is, when you set ContentView using layout xml.
You may need to create dummy ids in ids.xml in values folder for usability.
Please keep in mind that you can apply a similar logic for Layout created dynamically instead of using layout xml.
Please keep in mind that you can use similar logic for other Compound Buttons instead of CheckBox.
//Get Base Layout
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.base_layout);
//Create new CheckBox
CheckBox mainCheckBox = new CheckBox(this);
//Create a new ids.xml in values folder and add dummy id there. Than use that dummy id for dynamically created views
mainCheckBox.setId(R.id.main_cb);
//Give a name to it
mainCheckBox.setText(R.string.mainCB);
//Add it to Base layout
linearLayout.addView(mainCheckBox, 0);
//Create other CheckBoxes...
CheckBox[] checkBoxes = new CheckBox[5];
for (int i = 0; i < 5; i++) {
checkBoxes[i] = new CheckBox(this);
checkBoxes[i].setText(String.format(Locale.getDefault(), "Child CheckBox %d", i + 1));
checkBoxes[i].setId(i+101);
linearLayout.addView(checkBoxes[i], i+1);
}
//Creating each checkbox individually:
CheckBox checkBox = new CheckBox(this);
checkBox.setText("Child CheckBox 6");
//Either add an integer value
checkBox.setId(106);
/*
* Or else use a dummy id
* checkBox.setId(R.id.child_cb);
*/
linearLayout.addView(checkBox, 6);
//Set listener to main CheckBox
mainCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//Create an array of integer type to store all ids of child CBs
int[] ids = new int[] { 101, 102, 103, 104, 105, 106 };
/*
* You can also do
* int[] ids = new int[] { 101, 102, 103, 104, 105, R.id.child_cb };
*/
if(isChecked) {
Toast.makeText(getBaseContext(), "Checked", Toast.LENGTH_SHORT).show();
checkChildCBs(ids);
} else {
Toast.makeText(getBaseContext(), "Unchecked", Toast.LENGTH_SHORT).show();
unCheckChildCBs(ids);
}
}
});
Method to check all CheckBoxes
private void checkChildCBs(int[] ids) {
//Create CheckBox array of same size as that of ids
CheckBox[] checkBoxes = new CheckBox[ids.length];
//Run loop to check them
for (int i = 0; i < ids.length; i++) {
checkBoxes[i] = (CheckBox) findViewById(ids[i]);
checkBoxes[i].setChecked(true);
}
}
Method to unCheck all CheckBoxes
private void unCheckChildCBs(int[] ids) {
//Create CheckBox array of same size as that of ids
CheckBox[] checkBoxes = new CheckBox[ids.length];
//Run loop to unCheck them
for (int i = 0; i < ids.length; i++) {
checkBoxes[i] = (CheckBox) findViewById(ids[i]);
checkBoxes[i].setChecked(false);
}
}
/res/values/ids.xml :
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item type="id" name="main_cb" />
<item type="id" name="child_cb" />
</resources>
Update : You can follow the below code to enable/disable Dynamically created CheckBoxPreferences.
Create a new file named preferences.xml in /res/xml/ directory :
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android"
android:key="pref_screen">
</PreferenceScreen>
Than in your PreferenceActivity in onCreate() :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Add preference xml file from /res/xml/
addPreferencesFromResource(R.xml.preferences);
}
Now we will create CheckBoxPreference dynamically :
// Get PreferenceScreen using the key as stated in preferences.xml
PreferenceScreen prefScreen = (PreferenceScreen) findPreference("pref_screen");
// Now create a CheckBoxPreference array. The size of the array will be the number of required CheckBoxPreferences.
CheckBoxPreference[] cbPrefs = new CheckBoxPreference[5]; // You can set any number you want. This will allow you to create 5 CheckBoxPreferences.
// Run loop to create CheckBoxPreferences and add them to the PreferenceScreen.
for (int i = 0; i < cbPrefs.length; i++) {
cbPrefs[i] = new CheckBoxPreference(getActivity());
cbPrefs[i].setTitle("Dynamically created multiple Pref " + (i+1));
cbPrefs[i].setKey("multiple_dynamic_pref_key_" + (i+1));
prefScreen.addPreference(cbPrefs[i]); // Adds the newly created CheckBoxPreference to the PreferenceScreen
}
/*
IF you want, you can also create new CheckBoxPreference individually like this :
cbPrefs[0] = new CheckBoxPreference(getActivity());
cbPrefs[0].setTitle("My Preference");
cbPrefs[0].setKey("my_pref_key");
prefScreen.addPreference(cbPrefs[0]);
cbPrefs[1] = new CheckBoxPreference(getActivity());
cbPrefs[1].setTitle("Some Name");
cbPrefs[1].setKey("some_pref_key");
prefScreen.addPreference(cbPrefs[1]);
and so on and so forth...
*/
// Now create and add a Preference to the PreferenceScreen
Preference preference = new Preference(getActivity());
preference.setTitle("Preference");
prefScreen.addPreference(preference);
// Now set onPreferenceClickListener to newly created preference.
preference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
String[] prefKeys = new String[] {"multiple_dynamic_pref_key_1", "multiple_dynamic_pref_key_2",
"multiple_dynamic_pref_key_3", "multiple_dynamic_pref_key_4",
"multiple_dynamic_pref_key_5"};
changePrefsState(prefKeys, cbPrefs);
return false;
}
});
Finally your onCreate() will look like this :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Add preference xml file from /res/xml/
addPreferencesFromResource(R.xml.preferences);
// Get PreferenceScreen using the key as stated in preferences.xml
PreferenceScreen prefScreen = (PreferenceScreen) findPreference("pref_screen");
// Now create a CheckBoxPreference array. The size of the array will be the number of required CheckBoxPreferences.
CheckBoxPreference[] cbPrefs = new CheckBoxPreference[5]; // You can set any number you want. This will allow you to create 5 CheckBoxPreferences.
// Run loop to create CheckBoxPreferences and add them to the PreferenceScreen.
for (int i = 0; i < cbPrefs.length; i++) {
cbPrefs[i] = new CheckBoxPreference(getActivity());
cbPrefs[i].setTitle("Dynamically created multiple Pref " + (i+1));
cbPrefs[i].setKey("multiple_dynamic_pref_key_" + (i+1));
prefScreen.addPreference(cbPrefs[i]); // Adds the newly created CheckBoxPreference to the PreferenceScreen
}
// Now create and add a Preference to the PreferenceScreen
Preference preference = new Preference(getActivity());
preference.setTitle("Preference");
PreferenceScreen.addPreference(preference);
// Now set onPreferenceClickListener to newly created preference.
preference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
String[] prefKeys = new String[] {"multiple_dynamic_pref_key_1", "multiple_dynamic_pref_key_2",
"multiple_dynamic_pref_key_3", "multiple_dynamic_pref_key_4",
"multiple_dynamic_pref_key_5"};
changePrefsState(prefKeys, cbPrefs);
return false;
}
});
}
// This function is called when you click on preference to check/uncheck CheckBoxPrefs.
private void changePrefsState(String[] prefKeys, CheckBoxPreference[] checkBoxPreferences) {
try {
for (int i = 0; i < prefKeys.length; i++) {
checkBoxPreferences[i] = (CheckBoxPreference) findPreference(prefKeys[i]);
// Check if CheckBozPreference is Checked. If yes than unCheck it else Check it
if (checkBoxPreferences[i].isChecked())
checkBoxPreferences[i].setChecked(false);
else
checkBoxPreferences[i].setChecked(true);
}
} catch(Exception e) {
Toast.makeText(getActivity().getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
Old :
private void someFunction() {
String[] prefKeys = new String[] {"pref_key_1", "pref_key_2", "pref_key_3", "pref_key_4", "pref_key_5"};
CheckBoxPreference[] cbPrefs = new CheckBoxPreference[prefKeys.length];
changePrefsState(prefKeys, cbPrefs);
}
private void changePrefsState(String[] prefKeys, CheckBoxPreference[] checkBoxPreferences) {
try {
for (int i = 0; i < prefKeys.length; i++) {
checkBoxPreferences[i] = (CheckBoxPreference) findPreference(prefKeys[i]);
// Check if CheckBozPreference is Checked. If yes than unCheck it else Check it
if (checkBoxPreferences[i].isChecked())
checkBoxPreferences[i].setChecked(false);
else
checkBoxPreferences[i].setChecked(true);
}
} catch(Exception e) {
Toast.makeText(getActivity().getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
The above example works for both Dynamically created preferences and XML defined preferences.
You just need to pass the keys and pref type.
You can make different changePrefsState(arg1, arg2) { ... } for different Preference types.

main checkbox for check all checkbox.
CheckBox tvchkall = new CheckBox(ItemCodeRelease.this);
tvchkall.setId(101);
tvchkall.setOnClickListener(getOnClickDoSomething(tvchkall));
listner that check all checkbox which is dynamicall creater.
View.OnClickListener getOnClickDoSomething(final CheckBox chk) {
return new View.OnClickListener() {
public void onClick(View v) {
if (chk.getId() == 101) {
if (chk.isChecked()) {
for (int a = 1; a < tblItemDetail.getChildCount(); a++) {
itemContainer[a][6] = "Y";
CheckBox cb1 = (CheckBox) ((TableRow) tblItemDetail.getChildAt(a)).getChildAt(1);
cb1.setChecked(true);
}
} else {
for (int a = 1; a < tblItemDetail.getChildCount(); a++) {
itemContainer[a][6] = "N";
CheckBox cb11 = (CheckBox) ((TableRow) tblItemDetail.getChildAt(a)).getChildAt(1);
}
}
} else {
if (chk.isChecked()) {
for (int a = 0; a < itemContainer.length; a++) {
for (int b = 0; b < itemContainer[a].length; b++) {
if (a == chk.getId()) {
itemContainer[a][6] = "Y";
}
}
}
} else {
for (int a = 0; a < itemContainer.length; a++) {
for (int b = 0; b < itemContainer[a].length; b++) {
if (a == chk.getId()) {
itemContainer[a][6] = "N";
}
}
}
}
}
}
};
}

Related

Recycler view with multiple layout items duplicate radio buttons on scroll

RecyclerView containing multiple layouts such as one row containing Edittext, radioButtons another row containing checkbox etc
Now when I input in first edit text and scroll the list then same inputed value gets copied in the last edit text visible on the screen.
Also if there are two radio buttons visible say radio1 and radio 2 then on scroll this becomes
radio1
radio2
radio1
radio2
i.e. radio1 and radio 2 are duplicated on scroll.
Can any one suggest some solution for the same?
Code for dynamic Edit Text
private void configureViewHolderText(final ViewHolderText holderText, final int position) {
if (questionsArrayList != null && questionsArrayList.size() > 0) {
String hint = questionsArrayList.get(position).getHelperText();
int characterLength = questionsArrayList.get(position).getCharLimit();
boolean isQuestionRequired = questionsArrayList.get(position).isRequired();
if (isQuestionRequired) {
holderText.getTv_dynamic_star().setVisibility(View.VISIBLE);
}
holderText.getTv_dynamic_text_view().setText(questionsArrayList.get(position).getQuestionText());
if (characterLength > 0) {
holderText.getEt_dynamic_edit_text().setFilters(new InputFilter[]{new InputFilter.LengthFilter(characterLength)});
}
if (hint != null && hint.equals("null") == false && hint.equals("") == false) {
holderText.getEt_dynamic_edit_text().setHint(hint);
} else {
holderText.getEt_dynamic_edit_text().setHint("Enter Answer");
}
holderText.getEt_dynamic_edit_text().addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
editTextInput = holderText.getEt_dynamic_edit_text().getText().toString();
// SubmitAnswerRequest submitAnswerRequest = new SubmitAnswerRequest();
// SubmitAnswerRequest.answers answers = submitAnswerRequest.new answers();
// hashAnswerInput.put(questionsArrayList.get(position).get_id(), editTextInput);
/*hashQuestionText.put(questionsArrayList.get(position).get_id(), questionsArrayList.get(position).getQuestionText()) ;
hashQuestionId.put(questionsArrayList.get(position).get_id(), questionsArrayList.get(position).get_id()) ;
hashAnswerType.put(questionsArrayList.get(position).get_id(), questionsArrayList.get(position).getAnswerType());*/
/* for(Map.Entry map : hashAnswerInput.entrySet() )
{
dynamicEditTextAnswer = String.valueOf(map.getValue());
//answers.setAnswerText(inputAnswer);
}*/
/*if(dynamicEditTextAnswer!= null)
{*/
SubmitAnswerRequest submitAnswerRequest = new SubmitAnswerRequest();
SubmitAnswerRequest.answers answers = submitAnswerRequest.new answers();
answers.setQuestionText(questionsArrayList.get(position).getQuestionText());
answers.setQuestionId(questionsArrayList.get(position).get_id());
answers.setAnswerText(editTextInput);
answers.setAnswerType(questionsArrayList.get(position).getAnswerType());
answersArrayList.put(questionsArrayList.get(position).get_id(),answers);
/* }*/
/*for(Map.Entry map : hashQuestionText.entrySet() )
{
String inputAnswer = String.valueOf(map.getValue());
answers.setQuestionText(inputAnswer);
}
for(Map.Entry map : hashQuestionId.entrySet() )
{
String inputAnswer = String.valueOf(map.getValue());
answers.setQuestionId(inputAnswer);
}
for(Map.Entry map : hashAnswerType.entrySet() )
{
String inputAnswer = String.valueOf(map.getValue());
answers.setAnswerType(inputAnswer);
}*/
// SubmitAnswerRequest submitAnswerRequest = new SubmitAnswerRequest();
// SubmitAnswerRequest.answers answers = submitAnswerRequest.new answers();
// answers.setQuestionText(questionsArrayList.get(position).getQuestionText());
// answers.setQuestionId(questionsArrayList.get(position).get_id());
// answers.setAnswerText(editTextInput);
// answers.setAnswerType(questionsArrayList.get(position).getAnswerType());
// answersArrayList.add(answers);
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
}
Code for dynamic radio button
private void configureViewHolderRadioGroup(final ViewHolderRadioGroup holderRadioGroup, final int position) {
if (questionsArrayList != null && questionsArrayList.size() > 0) {
ArrayList<String> radioOptionsList = new ArrayList<String>();
for (int j = 0; j < questionsArrayList.get(position).getOptions().size(); j++) {
String radioItemName = questionsArrayList.get(position).getOptions().get(j).getOptionText();
radioOptionsList.add(radioItemName);
}
holderRadioGroup.getTv_dynamic_text_view().setText(questionsArrayList.get(position).getQuestionText());
boolean isQuestionRequired = questionsArrayList.get(position).isRequired();
if (isQuestionRequired) {
holderRadioGroup.getTv_dynamic_star().setVisibility(View.VISIBLE);
}
int totalCount = questionsArrayList.get(position).getOptions().size();
final RadioButton[] rb = new RadioButton[totalCount];
for (int i = 0; i < totalCount; i++) {
rb[i] = new RadioButton(context);
rb[i].setText(radioOptionsList.get(i));
rb[i].setId(i);
holderRadioGroup.getRg_dynamic_radio_group().addView(rb[i]); //the RadioButtons are added to the radioGroup instead of the layout
holderRadioGroup.getRg_dynamic_radio_group().setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
for (int i = 0; i < group.getChildCount(); i++) {
RadioButton rg = (RadioButton) group.getChildAt(i);
if (rg.getId() == checkedId) {
radioInput = rg.getText().toString();
Toast.makeText(context, radioInput, Toast.LENGTH_SHORT).show();
SubmitAnswerRequest submitAnswerRequest = new SubmitAnswerRequest();
SubmitAnswerRequest.answers answers = submitAnswerRequest.new answers();
answers.setQuestionText(questionsArrayList.get(position).getQuestionText());
answers.setQuestionId(questionsArrayList.get(position).get_id());
answers.setAnswerText(radioInput);
answers.setAnswerType(questionsArrayList.get(position).getAnswerType());
// answersArrayList.add(answers);
answersArrayList.put(questionsArrayList.get(position).get_id(),answers);
ArrayList<String> relatedQuestionsId = new ArrayList<String>();
relatedQuestionsId = questionsArrayList.get(position).getOptions().get(i).getRelatedQuestionIds();
if (relatedQuestionsId != null && relatedQuestionsId.size() > 0) {
for (int k = 0; k < relatedQuestionsId.size(); k++) {
((LinearLayout) holderRadioGroup.getLl_parent_radio_child()).removeAllViews();
getRadioChildQuestions(relatedQuestionsId, holderRadioGroup, k);
}
}
return;
}
else if(rg.getId() != checkedId) {
ArrayList<String> relatedQuestionsId = new ArrayList<String>();
/*for (int j = 0; j < questionsArrayList.get(position).getOptions().size(); j++) {*/
relatedQuestionsId = questionsArrayList.get(position).getOptions().get(i).getRelatedQuestionIds();
if (relatedQuestionsId != null && relatedQuestionsId.size() > 0) {
for (int k = 0; k < relatedQuestionsId.size(); k++) {
((LinearLayout) holderRadioGroup.getLl_parent_radio_child()).removeAllViews();
}
}
}
}
}
});
}
}
}
The recycler view reuses your view holders instances.
So if you are scrolling and a layout is leaving the screen at the top, it gets reused, when the same layout should be used for a new item at the bottom.
You need to reset all dynamic attribues in the onBindViewHolder-method.
For a better understanding set two debug points inside your recycler view adapter:
One inside the onCreateViewHolder-method and one inside the onBindViewHolder-method.
EDIT:
A sample for a working Recycler View Adapter can be found here: https://github.com/olLenz/Movies-with-Kotlin/blob/master/base/src/main/java/com/lenz/oliver/movieswithkotlin/ui/home/HomeAdapter.kt
The onCreateViewHolder-method creates a new instance of the ViewHolder.
The onBindViewHolder-method just calls the bind-method on a created ViewHolder instance. This bind-method sets all dynamic information to the given layout on every call.

Select Checkboxes when click menu item

When I press "select all" i want to checked all check boxes which have every listview item it is my layout::
enter code here
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle item selection
switch (item.getItemId())
{
case R.id.mark_all:
{
CheckBox checkBox = (CheckBox) findViewById(R.id.checkBox);
checkBox.setChecked(true);
return true;
}
default:
return super.onOptionsItemSelected(item);
}
}
this code selects only one checkbox which has first listview item.thank you
Use a for loop to get all the checkboxes
here an example:
boolean check = lv.isItemChecked(0);
for(int i = 0; i <= size; i++)
lv.setItemChecked(i, !check);
use for loop and get the view which contains check box:
for(int i = 0; i < listview.getChildCount(); i++)
{
View v = listview.getChildAt(i);
CheckBox ch = v.findViewById(R.id.checkbox);
ch.setSelected(true);
}
first add SparseBooleanArray in your class
SparseBooleanArray mChecked = new SparseBooleanArray();
now add this function to check:
if check is true than :all item checked
size = no of list vew item
public void setAllChecked(boolean check) {
int size = getCount();
if (check) {
for (int i = 0; i < size; i++) {
mChecked.put(i, true);
notifyDataSetChanged();
}
} else {
for (int i = 0; i < size; i++) {
mChecked.put(i, false);
notifyDataSetChanged();
}
}
now before returning the view check the check box status
CheckbixID.setChecked((mChecked.get(position) == true ? true : false));

Getting R.id for generated checkboxes

I am dynamically generating checkboxes in my program like so:
public void addNewItem(String item, TableLayout tablel) {
TableRow row = new TableRow(this);
TableRow.LayoutParams params = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT);
row.setLayoutParams(params);
CheckBox item1 = new CheckBox(this);
item1.setText(item);
row.addView(item1);
tablel.addView(row, i);
i++;
From what I've been able to test, this work fine for adding checkboxes to my table. The problem I'm encountering is that I want to be able to have something happen when a checkbox is checked, which I am unsure of how to do without knowning the id. Is there some way to get around this or get the id of the checkbox that has been checked when the onCheckBoxClick() method is called?
You don't need to know the ID because you already have the checkbox as on object.
Use this:
item1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(item1.isChecked()){
System.out.println("Checked");
}else{
System.out.println("Un-Checked");
}
}
});
An other possibility:
item1.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if ( isChecked )
{
// perform logic
}
}
});
Assign id via code (programmatically)
1.Manually set ids using someView.setId(int);
2.The int must be positive, but is otherwise arbitrary.
Then you can access that id.
It think this would help you.
You have created TableRow and CheckBox you should set id pragmatically like this
public void addNewItem(String item, TableLayout tablel) {
TableRow row = new TableRow(this);
row.setId(i);//i is a positive int value
TableRow.LayoutParams params = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT);
row.setLayoutParams(params);
CheckBox item1 = new CheckBox(this);
row.setId(j);//j is a positive int value
item1.setText(item);
row.addView(item1);
tablel.addView(row, i);
i++;
You can check this SO question
int chkBoxId = 10;
int tableRowId = 100;
String texts[] = {"Text1", "Text2", "Text3", "Text4", "Text5"};
CheckBox[] chkBoxes;
private TableLayout tableLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dynamic_chk_box);
tableLayout = (TableLayout) findViewById(R.id.tableLayout);
chkBoxes = new CheckBox[texts.length];
for(int i = 0; i < 5; i++) {
TableRow row = new TableRow(this);
TableRow.LayoutParams params = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT);
row.setLayoutParams(params);
chkBoxes[i] = new CheckBox(this);
chkBoxes[i].setId(chkBoxId++);
row.setId(tableRowId);//tableRowId is a positive int value
chkBoxes[i].setText(texts[i]);
row.addView(chkBoxes[i]);
tableLayout.addView(row, i);
tableRowId++;
}
for (int i = 0; i < texts.length; i++) {
final int j = i;
chkBoxes[j].setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(isChecked) {
int checkedId = chkBoxes[j].getId();
Toast.makeText(DynamicCheckBoxActivity.this,
String.valueOf(checkedId),
Toast.LENGTH_SHORT).show();
} else {
int unCheckedId = chkBoxes[j].getId();
System.out.println("Uncheck ===> " + String.valueOf(unCheckedId));
}
}
});
}
}

selected check boxes count and passing it to another activity

i have 4 check boxes in 1st activity and i wanna store only those user selected check boxes and have to show in another activity my question is how can i count the user selected checkboxes. please help with me logic
int x = 0;
public void onCheckboxClicked(View view) {
checked = ((CheckBox) view).isChecked();
if (((CheckBox) view).isChecked() == true) {
int i = 0;
while (i != 4) {
x = i + 1;
i++;
}
}
}
On Submit Button
if(x!=0) {
show alert();
and passing check boxes selected count
}
You can run a loop and find the number of CheckBox views and then accordingly get the count of checked CheckBoxes
Ex:
main = (LinearLayout) findViewById(R.id.main);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
count = 0;
int childcount = main.getChildCount();
for (int i=0; i < childcount; i++){
View view = main.getChildAt(i);
if (view instanceof CheckBox) {
if(((CheckBox) view).isChecked())
count++;
}
}
text.setText("count: " + count);
}
});
First put checkboxes in an array:
ArrayList<CheckBox> checkList = new ArrayList<CheckBox>();
you can do it with:
for(int i=0 ; i<4; i++)
{
checkList.add(YOURCHECKBOX) ;
}
than you can check which CB are checked (implement where you want it to save only those which are checked..) with:
for(int i=0 ; i<checkList.size(); i++)
{
if(checkList.get(i).isChecked() == true)
{
YOURCODE
}
}

How to save multiple values in SQLite Database in Android?

I have a textView which is a DropDownList. Under this textview, there will be multiple options with checkboxes beside it. The User can choose one or more from the options.
I include my code for this dropdownlist and how did I populate it with my array.
MainActivity.java
private void initializeCustomerSegment()
{
final ArrayList<String> consumerSegments = new ArrayList<String>();
List<String> consumerSegment = databaseHandler.setItemOnConsumerSeg();
consumerSegments.addAll(consumerSegment);
checkSelectedConsumerSegment = new boolean[consumerSegments.size()];
//initialize all values of list to 'unselected' initially
for (int i = 0; i < checkSelectedConsumerSegment.length; i++) {
checkSelectedConsumerSegment[i] = false;
}
final TextView tv_ConsumerSegment = (TextView) findViewById(R.DropDownList.tv_ConsumerSegment);
tv_ConsumerSegment.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(!expandedConsumerSegment){
//display all selected values
String selected = "";
int flag = 0;
for (int i = 0; i < consumerSegments.size(); i++) {
if (checkSelectedConsumerSegment[i] == true) {
selected += consumerSegments.get(i);
selected += ", ";
flag = 1;
}
}
if(flag==1)
tv_ConsumerSegment.setText(selected);
expandedConsumerSegment =true;
}
else{
//display shortened representation of selected values
tv_ConsumerSegment.setText(BrandListAdapter.getSelected());
expandedConsumerSegment = false;
}
}
});
//onClickListener to initiate the dropDown list
TextView tv_customerSegment = (TextView)findViewById(R.DropDownList.tv_ConsumerSegment);
tv_customerSegment.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
initiatePopUpCustomerSegment(consumerSegments,tv_ConsumerSegment);
}
});
}
private void initiatePopUpCustomerSegment(ArrayList<String> customerSegments, TextView tv_CustomerSegment){
LayoutInflater inflater = (LayoutInflater)S_10th_IReportMain.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//get the pop-up window i.e. drop-down layout
LinearLayout layoutCustomerSegment = (LinearLayout)inflater.inflate(R.layout.pop_up_window_customersegment, (ViewGroup)findViewById(R.id.PopUpView1));
//get the view to which drop-down layout is to be anchored
RelativeLayout layout4 = (RelativeLayout)findViewById(R.id.relativeLayout4);
pwConsumerSegment = new PopupWindow(layoutCustomerSegment, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, true);
//Pop-up window background cannot be null if we want the pop-up to listen touch events outside its window
pwConsumerSegment.setBackgroundDrawable(new BitmapDrawable());
pwConsumerSegment.setTouchable(true);
//let pop-up be informed about touch events outside its window. This should be done before setting the content of pop-up
pwConsumerSegment.setOutsideTouchable(true);
pwConsumerSegment.setHeight(LayoutParams.WRAP_CONTENT);
//dismiss the pop-up i.e. drop-down when touched anywhere outside the pop-up
pwConsumerSegment.setTouchInterceptor(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
pwConsumerSegment.dismiss();
return true;
}
return false;
}
});
//provide the source layout for drop-down
pwConsumerSegment.setContentView(layoutCustomerSegment);
//anchor the drop-down to bottom-left corner of 'layout1'
pwConsumerSegment.showAsDropDown(layout4);
//populate the drop-down list
final ListView listCustomerSegment = (ListView) layoutCustomerSegment.findViewById(R.DropDownList.dropDownCustomerSegment);
ConsumerSegmentListAdapter adapter = new ConsumerSegmentListAdapter(this, customerSegments, tv_CustomerSegment);
listCustomerSegment.setAdapter(adapter);
}
I also have this line of code in order for me to save the data...
String cSegment = checkSelected.toString();
Cursor rcSegment = databaseHandler.getReport_SubBrandCode(subBrand);
String SubBrandCode = rcSegment.getString(rcSegment.getColumnIndex(Constants.CONSUMERSEGMENT_CODE));
My question is, how can I save those multiple data in a single column in SQLite?
first, you need to get the value of the selected item on your multi select spinner. Try this:
ArrayList<String> content = new ArrayList<String>();
for (int j = 0; j < checkSelected.length; j++)
{
if(checkSelected[j]==true)
{
String values = BrandListAdapter.mListItems.get(j);
content.add(values);
}
}
Toast.makeText(getApplicationContext(), content.toString(), Toast.LENGTH_SHORT).show();
I toast the arraylist content just to check if it really contains the value I select. Then when you see the right value on your toast then you could save it on your database. Hope it helps! charot :D

Categories

Resources