I am struggling with Android Lists and how to convert them for use in a Spinner. Putting a string array into a Spinner is very simple, therefore, I figured doing the same with a List would also be simple. At this time however I can not figure out how to get the List into the proper format for use with the Spinner’s ArrayAdapter.
Here’s my code for grabbing a list of account names from the database:
//---retrieves all the accounts matching the account_type---
public List getAccounts(String account_type) {
List<String> list = new ArrayList<String>();
Cursor cursor = this.db.query(DBACCOUNTS, new String[] {
ID,
ACCOUNTTYPE,
ACCOUNTNUMBER,
ACCOUNTNAME},
ACCOUNTTYPE + " = " + "'" + account_type + "'",
null,
null,
null,
null,
null);
if (cursor.moveToFirst()) {
do {
//---account_name column number is 3---
list.add(cursor.getString(3));
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return list;
}
From the returned “list”, what do I need to do to populate my spinner? The following code is obviously for a string array, however, I am lost as to what I need to do to make a List work with similar functionality. Here’s my non-working ArrayAdapter code (account_name_array is set to be the returned “list” from above):
account_name_spinner = (Spinner) findViewById(R.id.account_name_spinner);
account_name_adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, account_name_array);
account_name_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
account_name_spinner.setAdapter(account_name_adapter);
I know I am way off track here, I know that ArrayAdapter is expecting a string array, however, like I said, I need a good push in the right direction. Obviously I need to either convert my List into a string array, or change the way I am adapting the Spinner to the List. Android has been quite difficult for me to grasp, there are a lot of data structures and much more data type rules than I am use to coming from a PHP background.
You’re help is greatly appreciated!
Use
toArrayto convert your list into an array.