Search code examples
androidandroid-mapviewandroid-alertdialogitemizedoverlay

How to persist options selected in AlertDialog spawned from ItemizedOverlay onTap method


In the description of how to add a list of options to an AlertDialog the official Android documentation alludes to saving a users preferences with one of the "data storage techniques." The examples assume the AlertDialog has been spawned within an Activity class.

In my case I've created a class that extends ItemizedOverlay. This class overrides the onTap method and uses an AlertDialog to prompt the user to make a multi-choice selection. I would like to capture and persist the selections for each OverlayItem they tap on.

The below code is the onTap method I've written. It functions as written but doesn't yet do what I'd hope. I'd like to capture and persist each selection made by the user to be used later. How do I do that? Is using an AlertDialog in this manner a good idea? Are there better options?

protected boolean onTap(int index)
{
    OverlayItem item = _overlays.get(index);
    final CharSequence[] items = { "WiFi", "BlueTooth" };
    final boolean[] checked = { false, false };

    AlertDialog.Builder builder = new AlertDialog.Builder(_context);
    builder.setTitle(item.getTitle());
    builder.setMultiChoiceItems(items, checked, new
        DialogInterface.OnMultiChoiceClickListener()
        {
          @Override
          public void onClick(DialogInterface dialog, int item,
              boolean isChecked)
              {
                  // for now just show that the user touched an option
                  Toast.makeText(_context, items[item],
                    Toast.LENGTH_SHORT).show();
              }
        });
    builder.setPositiveButton("Okay", new DialogInterface.OnClickListener()
    {
        @Override
        public void onClick(DialogInterface dialog, int id)
        {
            // should I be examining what was checked here?
            dialog.dismiss();
        }
    });

    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
    {
        @Override
        public void onClick(DialogInterface dialog, int id)
        {
            dialog.cancel();
        }
    });

    AlertDialog alert = builder.create();
    alert.show();
    return true;
}

Solution

  • Well you could create a HashMap<OverLayItem, List<String>> or HashMap<OverLayItem, List<Boolean>> to store the setting for each item if you only need to access it in memory, or if you need more persistent store you can use either the preferences or a database or other means as explained in the link you provided. Then you'd update the hashmaps or your database in the positive onClick().