-1

How do I store Items from AlertDialog - multipleChoiceItems in a one variable. Also with a separator , . I need it in order to pass to remote server and extract it using the php - explode function.

Here's my demo code: MainActivity.java

final RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl);
    Button btn = (Button) findViewById(R.id.btn);
    final TextView tv = (TextView) findViewById(R.id.tv);

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Build an AlertDialog
            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

            // String array for alert dialog multi choice items
            String[] colors = new String[]{
                    "Red",
                    "Green",
                    "Blue",
                    "Purple",
                    "Olive"
            };

            // Boolean array for initial selected items
            final boolean[] checkedColors = new boolean[]{
                    false, // Red
                    true, // Green
                    false, // Blue
                    true, // Purple
                    false // Olive

            };

            // Convert the color array to list
            final List<String> colorsList = Arrays.asList(colors);`

builder.setMultiChoiceItems(colors, checkedColors, new DialogInterface.OnMultiChoiceClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which, boolean isChecked) {

                    // Update the current focused item's checked status
                    checkedColors[which] = isChecked;

                    // Get the current focused item
                    String currentItem = colorsList.get(which);

                    // Notify the current action
                    Toast.makeText(getApplicationContext(),
                            currentItem + " " + isChecked, Toast.LENGTH_SHORT).show();
                }
            });

I want to store the selected Items in currentItem variable.

So the sample output will be like this (in Logcat) : Red,Green,Blue,Purple

RoCkDevstack
  • 3,517
  • 7
  • 34
  • 56

1 Answers1

1

You Can use this in your setMultiChoiceItems onClick event :

 currentItem = currentItem+colorsList.get(which)+",";

Toast.makeText(context,"Appended String :    
"+currentItem,Toast.LENGTH_LONG).show();

and declare your variable :

String currentItem=""; globally

When sending to server just do this :

currentItem=currentItem.substring(0,currentItem.length()-1);

it will remove an extra "," at the end.

Edit :

For your question in comment in your button onClick event use this:

 for(int i=0;i<colors.length;i++)
     currentItem = currentItem+colors[i]+",";

     Toast.makeText(context,"Appended String : "+currentItem,Toast.LENGTH_LONG).show();
Ashish Shukla
  • 1,027
  • 16
  • 36