Joe Cade Joe Cade - 1 month ago 32
Java Question

Load Spinner Values Dynamically

I'm trying to load values into my spinner dynamically, but i get an error here "this, android.R.layout.simple_spinner_item, colors" The error is:

Error:(109, 52) error: no suitable constructor found for ArrayAdapter(GuestListFragment,int,String[])
constructor ArrayAdapter.ArrayAdapter(Context,int,int) is not applicable
(argument mismatch; GuestListFragment cannot be converted to Context)
constructor ArrayAdapter.ArrayAdapter(Context,int,String[]) is not applicable
(argument mismatch; GuestListFragment cannot be converted to Context)
constructor ArrayAdapter.ArrayAdapter(Context,int,List) is not applicable
(argument mismatch; GuestListFragment cannot be converted to Context)

// Spinner
colorSpinner = (Spinner) guestView.findViewById(R.id.dateSpinner);

// Array of choices
String colors[] = {"Red","Blue","White","Yellow","Black", "Green","Purple","Orange","Grey"};

// Update Spinner
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, colors);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
colorSpinner.setAdapter(spinnerArrayAdapter);

Answer

Try the following code:

String items[] = new String[2];
items[0] = String.valueOf("Item #1");
items[0] = String.valueOf("Item #2");

ArrayAdapter<String> spinnerArrayAdapter =
    new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, items);

spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

Spinner spinner = (Spinner) findViewById(R.id.spinner);
spinner.setAdapter(spinnerArrayAdapter);

if you are within a fragment replaces "this" by "getContext () '