0

I am Using hashsetList to create a new list for my spinner without duplicates but java gives errors when I add this within the Spinner. Ithe project works fine when duplicates are shown from mySQL.

Here is the extract of MainActivity.java before I created the hashsetList.

  @Override
    protected void onPostExecute(Void args) {
        // Locate spinner1 in activity_main.xml
        Spinner spinner1 = (Spinner) findViewById(R.id.spinner1);

        // Spinner adapter

        spinner1.setAdapter(new ArrayAdapter<String>(MainActivity.this,
                android.R.layout.simple_spinner_dropdown_item,typesofjobs));

       Collections.sort(typesofjobs);

When I added the following hashsetList code to eliminate duplicates and run it, the project crashes.

  @Override
    protected void onPostExecute(Void args) {
        // Locate spinner1 in activity_main.xml
        Spinner spinner1 = (Spinner) findViewById(R.id.spinner1);


        Set<String> hashsetList = new HashSet<String>(typesofjobs);
        // Spinner adapter

        spinner1.setAdapter(new ArrayAdapter<String>(MainActivity.this,
                android.R.layout.simple_spinner_dropdown_item, (List<String>) hashsetList));

        Collections.sort(typesofjobs);

Am I putting hashsetList in the wrong place or using it incorrectly? I am just trying to replace "typesofjobs" with the non duplicate version. Is there a better way I could eliminate my spinner duplicates?

1
  • What is your error output and do you know the exact line where your program is crashing? Commented Oct 30, 2015 at 8:51

1 Answer 1

1

You were on the right track when you used HashSet with your list to remove the duplicates. However, you made a mistake when you tried to cast this Set to a List, which won't work. Instead, in the code below I pass a LinkedHashSet created from your list of jobs into an ArrayList constructor. The resulting List will have all duplicate String job values removed.

@Override
protected void onPostExecute(Void args) {
    // Locate spinner1 in activity_main.xml
    Spinner spinner1 = (Spinner) findViewById(R.id.spinner1);

    List<String> typesofjobsunique = new ArrayList<>(new LinkedHashSet<>(typesofjobs));
    spinner1.setAdapter(new ArrayAdapter<String>(MainActivity.this,
            android.R.layout.simple_spinner_dropdown_item, typesofjobsunique));

    // not sure if you want to keep original list
    Collections.sort(typesofjobs);

Hat tip to this great SO post which discusses ways to remove duplicates from Java Lists.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.