2011-07-26 96 views
0

我在使用Android Lists以及如何将它们转换为在Spinner中使用。将一个字符串数组放入一个Spinner非常简单,因此,我认为对List做同样的处理也很简单。但是在这个时候,我无法弄清楚如何让List成为与Spinner的ArrayAdapter一起使用的正确格式。我有一个帐户名称和一个微调列表,我如何使用列表填充微调?

这是我从数据库中抓取帐户名称的列表代码:

//---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; 
    } 

在返回的“名单”,有什么事情我需要做来填充我的微调?下面的代码显然是一个字符串数组,但是,我失去了我需要做什么才能使List与类似的功能一起工作。这是我的非工作ArrayAdapter代码(account_name_array被设置为返回“名单”,从上面):

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); 

我知道我的方式偏离了轨道在这里,我知道ArrayAdapter期待一个字符串数组,但是,就像我说的,我需要朝着正确的方向努力。很显然,我需要将List转换为字符串数组,或者改变我将Spinner调整为List的方式。 Android对我来说很难掌握,有很多数据结构和更多的数据类型规则,比我用来从PHP背景获得的更多。

非常感谢您的帮助!

+0

这是显示错误吗? –

回答

2

使用toArray将列表转换为数组。

List<String> list = new ArrayList<String>(); // Your list 
// Populate it 

// Then get an array: 
String[] array = list.toArray(new String[0]); 
+0

谢谢,简单!你能否确认我正确理解这一点?是否将“new String [0]”初始化为一个临时数组,.toArray函数需要将ArrayList转换为一个字符串数组?是否应该计算结果的数量并以最佳方式初始化新的String []? – AutoM8R

+1

'toArray'的参数有两个目的:第一个是传递要返回的数组类型。第二个(可选)用途是保存结果:如果传入的数组足够大,结果将返回到该数组中。如果不是,则会创建一个新的数组。 – trutheality

1

我也有类似的问题,而不是从列表去一个微调,我只是改变了我是从我的分贝拉动方式,我写在我的数据库返回的行数的另一种方法:

public int RowCount() { 
    String count = "Select COUNT(_id) from " + TABLE_NAME; 
    return (int) db.compileStatement(count).simpleQueryForLong(); 
} 

然后我宣布一个数组:

String []myArray = new String[db.RowCount()]; 

我然后使用游标填充的阵列,因为它似乎你已经知道该怎么做。

+0

谢谢,不过,我想保留它作为一个ArrayList在这一点上,所以我可以使用它的列表功能。 – AutoM8R

2

如果account_name_array是ArrayList,则需要将其转换为String []并将其传递给适配器。

String[] account_names = account_name_array.toArray(new String[account_name_array.size()]); 
account_name_adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, account_names); 
相关问题