Search code examples
javaandroidsubmenu

Handling selected items from a checkable menu


I am using this tutorial to create a submenu with checkable items. So, far everything works but I can't figure out how to handle the selected items as I am new to serializable. This is the link to the tutorial

https://stackoverflow.com/questions/7072347/how-to-select-multiple-checkboxes-in-submenu-on-android?answertab=active#tab-top

   public static final String SETTING_CHECK_BOX = "SETTING_CHECK_BOX";

private ArrayList < SettingCheckBox > settingList;

@Override
public void onCreate(Bundle savedInstanceState) {
    // ... 
    settingList = new ArrayList < SettingCheckBox > ();
    settingList.add ( new SettingCheckBox ( "Option A" ) );
    settingList.add ( new SettingCheckBox ( "Option B" ) );
    // ... add more items
    // restore any previously saved list
    if ( savedInstanceState != null ) {
        settingList = (ArrayList < SettingCheckBox >) savedInstanceState.getSerializable ( SETTING_CHECK_BOX );
    }
    // ...
}

         protected void onActivityResult ( int requestCode , int resultCode , Intent data ) {
            if ( resultCode != RESULT_OK || data == null )
                return;
            settingList = (ArrayList < SettingCheckBox >) data.getSerializableExtra ( SETTING_CHECK_BOX );

    //how can I log print the list of items that have been checked
    // What should go here ? such that i can do other things after getting a list of items that were checked ?

     //This is my try

            Object[] mStringArray = settingList.toArray();

               for(int i = 0; i < mStringArray.length ; i++){
               Log.d("***Checked items*",(String)mStringArray[i]);
         }

        }

Solution

  • Are you getting any error from that code? If not, it means that your settingList is properly initialized with the parsed value from data.getSerializableExtra ( SETTING_CHECK_BOX );, which is a list of SettingCheckBox object. From the link you provided, the code for SettingCheckBox object class is included. What you do with the data inside the object depends on your use case.


    EDIT: In response to comments.

    If by names, you mean the SettingCheckBox text description, you can iterate over your settingList directly like so:

    for(int i = 0; i < settingList.size(); i++){
        Log.d("***Checked items*", settingList.get(i).getDescription());
    }