How to handle duplicate values for list preference?

91 views Asked by At

I am creating the currency format feature with list preference.

List of entries are as follows:

<string-array>
    .....
    <item>Australia</item>
    <item>Canada</item>
    <item>United Kingdom</item>
    <item>United States</item>
    <item>Uruguay</item>
    .....
</string-array>

And the corresponding list of values:

<string-array>
    .....
    <item>$</item>
    <item>$</item>
    <item>£</item>
    <item>$</item>
    <item>$U</item>
    .....
</string-array>

When I select Australia, the United States becomes selected. This is because both entries have the same value and the system chooses the last item if there are duplicate values. How should we overcome this issue easily? I can use unique value with a prefix or suffix to solve the duplicity but this will lead me to do more work to encode and decode the value whenever needed.

I have tried to set the preference dynamically with no luck:

....
CharSequence[] entries = currencyPreference.getEntries();
        for (int index = 0; index < entries.length; index++) {
            if (entries[index].equals(entryCurrency)) {
                currencyPreference.setValueIndex(index);
            }
        }
.....

Updated:

After searching a lot I have concluded that I had to use another list to accomplish this.

<string-array name="entry_values_currency">
    <item>0</item>
    <item>1</item>
    <item>2</item>
    <item>3</item>
    <item>4</item>
</string-array>
<string-array name="currency_symbols">
    <item>$</item>
    <item>$</item>
    <item>£</item>
    <item>$</item>
    <item>$U</item>
</string-array>

And get the symbol as follows:

String currency = getResources().getStringArray(R.array.currency_symbols)[Integer.parseInt(currencyPreference.getValue())];
1

There are 1 answers

0
Prajwal Waingankar On

In your case, you can use HASHSET java collection library. Hashset is basically used when you need to store unique data. - Declare a hashet of type String. - Extract the strings from the list array and store them one by one in the hashset using the for loop with condition size and increment. - Then declare an ArrayList of type String. - Create the for loop with condition hashset size and increment and use arraylist 'addAll()' to store the hashset data into your new arraylist. - The above step is because hashset doesnt store data in an indexing way and so it becomes trouble while getting the index specific data.

    Hashset<String> hashset = new Hashset<>();
    hashset.add("your list array data");

    Arraylist<String> arraylist = new Arraylist<>();
    arraylist.addAll(hashset);

These is how you will declare and initialize the hashset and arraylist.