Dan
Dan

Reputation: 2344

Can I populate an AlertDialog with items from a sharedPreferences file?

I have set up the SharedPreferences like below:

Editor editor = getSharedPreferences("FileName", MODE_PRIVATE).edit();
        editor.clear();
        editor.putString("chicago", "Chicago, IL");
        editor.putString("london", "London, UK");
            editor.putString("sanjose", "San Jose, CA");
            editor.putString("washington", "Dulles, VA");
        editor.commit();

At the moment I am populating the AlertDialog from an array, and I want to use the SharedPreferences file so I can eventually dynamically add items etc.

The code I use to populate at the moment is:

private void openServerDialog() {
        new AlertDialog.Builder(this)   
        .setTitle(R.string.server_title)
        .setItems(R.array.serverchoice, 
                new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialoginterface,
                    int i) {
                setServer(i);   
            }
        })
        .show();
    }

So I just want to stop using the array "serverchoice" and instead use the strings from the SharedPreferences file.

Thanks in advance

Upvotes: 1

Views: 1297

Answers (2)

Jeff
Jeff

Reputation: 820

You can use the getString() method of the SharedPreferences object to retrive a string from the shared preferences. See the documentation for SharedPreferences.

EDIT: Adjusted answer after a comment by the OP.

private void openServerDialog() {
    SharedPreferences sharedPrefs = getSharedPreferences("FileName", MODE_PRIVATE);
    Map<String, ?> sharedPrefsMap = sharedPrefs.getAll();
    ArrayList<String> stringArrayList = sharedPrefsMap.values();
    CharSequence[] prefsCharSequence = stringArrayList.toArray(new CharSequence[stringArrayList.size()]);

    new AlertDialog.Builder(this)   
    .setTitle(R.string.server_title)
    .setItems(prefsCharSequence, 
    new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialoginterface,
            int i) {
            setServer(i);   
        }
    })
    .show();
}

Upvotes: 1

knvarma
knvarma

Reputation: 974

Use getAll() method in SharedPreferences to get all the keys. And get all the keys and values and display in dialog.

SharedPreferences prefs = getSharedPreferences("FileName", MODE_PRIVATE);
    Map<String, ?> map = prefs.getAll();
    Set<String> keys = map.keySet();
    for(String key : keys) {
        Log.d(TAG, "key : " + key);
            Log.d(TAG, "value : " + map.get(key));
    }

Upvotes: 0

Related Questions