user4081263
user4081263

Reputation:

Populating Spinner using a HashMap?

I am trying to populate a spinner using items from a custom class I created via a simple adapter, containing a HashMap. My app keeps crashing when I use setSimpleAdapter(), so I commented it out. But when I use spinner1.setAdapter(dataAdapter), it shows no items on the spinner. Here's my code:

This is in my onCreate():

spinner1 = (Spinner) findViewById(R.id.spinner1);

        ArrayAdapter <CharSequence> dataAdapter =
                new ArrayAdapter <CharSequence> (this, android.R.layout.simple_spinner_item );
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        spinner1.setAdapter(dataAdapter);

        //setSimpleAdapter();

        // Spinner item selection Listener
        addListenerOnSpinnerItemSelection();

        // Button click Listener
        addListenerOnButton();

// Add spinner data
public void addListenerOnSpinnerItemSelection(){

    spinner1.setOnItemSelectedListener(new CustomOnItemSelectedListener());
}

//get the selected dropdown list value
public void addListenerOnButton() {

    spinner1 = (Spinner) findViewById(R.id.spinner1);

    btnSubmit = (Button) findViewById(R.id.btnSubmit);

    btnSubmit.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            final AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
            alertDialog.setTitle("X");
            alertDialog.setMessage("" + String.valueOf(spinner1.getSelectedItem()));
            alertDialog.setButton("Close", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    //Dismisses alert
                    alertDialog.dismiss();
                }
            });

            alertDialog.show();

        }

    });

}

Can anyone point me in the right direction? I have been googling for like an hour now. Any help will be appreciated.

Upvotes: 2

Views: 6217

Answers (1)

darnmason
darnmason

Reputation: 2732

Well you didn't post half enough code, but say you have a HashMap<String, Object> then you'd wanna do something like this, passing the array of values into the constructor:

Collection<Object> vals = hashMap.values();
Object[] array = vals.toArray(new Object[vals.size()]);
ArrayAdapter<CharSequence> dataAdapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, array);

Just replace Object with whatever your custom class is and ensure that you override toString() to define what should be displayed as text.

Upvotes: 2

Related Questions