Si8
Si8

Reputation: 9225

How to store and retrieve what was selected from a single choice item

I have the following code:

protected void showSelectToDialog() {
        boolean[] checkedDate = new boolean[toDate.length];
        int count = toDate.length;

        DialogInterface.OnClickListener setD2 = new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //TODO Auto-generated method stub
                onChangeSelectedTo(which);
            }
        };

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Select To Year");
        builder.setSingleChoiceItems(toDate, count, setD2);

        builder.setCancelable(true);
        builder.setPositiveButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                dialog.dismiss();
            }
        });
        dialog2 = builder.create();
        dialog2.show();
    }

    protected void onChangeSelectedTo(int j) {
        bTo.setText(toDate[j]);
        sTo = ((AlertDialog)dialog2).getListView().getCheckedItemPosition();
        blTo = true;
        displayToast(String.valueOf(sTo));
        to = j;
        dialog2.dismiss();
    }

What I am looking to do is, when the dialog loads the first time and the user selects a choice it is stored. So the next time the user opens the dialog, it will remember what was select and scroll to that choice.

How do I accomplish that?

Upvotes: 1

Views: 443

Answers (2)

Rohan Kandwal
Rohan Kandwal

Reputation: 9336

Save the selected choice's position for the first time using Shared Preferences. Then at the start of showSelectToDialog() check if any value exists in Shared Preferences, if so, then set the value of count from the Shared Preferences else set value of count to toDate.length.

Upvotes: 1

SpacePrez
SpacePrez

Reputation: 1086

I can't see the rest of your code, but all you have to do is save the user's choice in a variable somewhere else, and then read that choice every time you open the dialogue. It could be a static variable on the class, or it could be an instance variable of the class, or it could be a public field of some other class you have access to, like a parent object. You just need to assign it when you close the dialogue, and read it back and initialize the value to what you read when you open the dialogue.

Upvotes: 1

Related Questions