2012-03-25 152 views
1

我對Java很陌生,目前正在編寫一個Android應用程序。在我的「快捷鍵」課,我有這段代碼(更多的課程,但不能對你有用,我不認爲):如何將字符串轉換爲字符串[] // Android開發// Java

final String[] items = new String[]{ "Please select a category",scanner.getCategorys() }; 
     @SuppressWarnings({ "unchecked", "rawtypes" }) 
     ArrayAdapter<CharSequence> adapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item, items); 
     adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
     selection.setAdapter(adapter); 

我有另一個類名爲「掃描儀」,裏面有這樣代碼:

String categorys = "test"; 

public String getCategorys() { 
    return categorys; 
} 

這並不工作,並在我的微調,我可以在我的「請選擇類別」相同的值選項(即「測試」)填補。問題是,我希望能夠選擇多個類別。如果我這樣做,在「快捷鍵」類:

final String[] items = new String[]{ "Please select a category","test","test2" }; 

它的工作,但我想從「掃描儀」類設置,所以我嘗試這樣做:只是

String[] categorys = "test","test2"; 

public String[] getCategorys() { 
    return categorys; 
} 

但給我的錯誤:

String cannot be converted to String[] 

我將不勝感激的任何幫助。

回答

2

這是錯誤的:

String[] categorys = "test","test2"; 

將其更改爲

String[] categorys = {"test","test2"}; 
+0

謝謝,去掉了一些錯誤的錯誤,但我仍然遇到錯誤,我把scanner.getCategorys()。我編輯了這篇文章。 – 2012-03-25 12:56:12

+0

是的。只需將'String [] categorys {「請選擇一個類別」,「test」,「test2」}''。然後像這樣初始化你的項目:'String [] items = scanner.getCategorys()' – 2012-03-25 13:02:34

+0

非常感謝人,它的工作。 – 2012-03-25 13:08:44

1

在你最後的代碼示例,你必須把你的周圍的字符串{ },就像這樣:

String[] categorys = { "test","test2" }; 

public String[] getCategorys() { 
    return categorys; 
} 

根據以上你的編輯,你不能一個String []添加到現有的String [] 。您需要將從getCategorys()獲得的字符串[]中的每個項目添加到另一個陣列。在這種情況下,我可能會切換到ArrayList<string>,所以您不必決定數組的大小,然後添加每個項目。

+0

謝謝,去掉了一些錯誤,但我仍然得到我放哪兒scanner.getCategorys() – 2012-03-25 12:52:12

1

如下

String[] categorys = {"test","test2"}; 

我會打電話的變量作爲 '類別' 可以初始化的categorys。

編輯: scanner.getCategorys()不能用作構造函數期望的字符串而不是字符串數組。 uncocoder指出了一個好主意,就是使用ArrayList。然後你可以使用add方法來包含「請選擇一個類別」。

+0

謝謝,這刪除了一些錯誤,但我仍然遇到錯誤,我把scanner.getCategorys()。我編輯了這篇文章。 – 2012-03-25 12:55:38

+0

@zeokila更新了我的答案 – 2012-03-25 13:06:53

0

我對電子書籍使用ArrayList,它的快速和容易的這樣

ArrayList<String> strings = new ArrayList<String>(); 
strings.add("SOME TEXT"); 
strings.get(0); 
//and more