2013-02-04 37 views
1

我有一個非常長的項目列表(超過200)和一個顯示列表的數據庫。我有一個點擊事件會比較,如果第一個項目是一個「蘋果」,然後當你點擊它,事實就出現了一個「蘋果」。問題是這個列表不是SET列表,這意味着單詞「apple」可能在第一個位置,或者它可能位於第18個位置。是否有一種比較大型物品清單的更簡單方法?

我開始做一個如果語句比較像這樣:

case 0: 
if (text.equals("apple")) { 
[show facts about apple] 
} else if (text.equals("orange")) { 
[show facts about orange] 
//this would continue on to compare the ENTIRE LIST (about 500 lines per case) 
break; 

問題是,我得到了一條錯誤:

The code of method onListItemClick(ListView, View, int, long) is exceeding the 65535 bytes limit 

必須有一個更簡單的方法要做到這一點,對吧?

回答

0

首先,要解決你的「方法太長」問題,有幾種方法。

#1將您的所有描述移動到strings.xml中。

if (text.equals("apple")) { 
    result = getResources().getString(R.string.apple_description); 
} 

#2移動你的if-else成分離的方法。

case 0: 
    mydescription = getDescription(text); // getDescription() is the big if-else you have 

但.....它仍然是以這樣的方式非常糟糕代碼。

請考慮以下幾點:

#1的名稱和說明創建一個HashMap。

  • 蘋果 - 說明對於蘋果
  • 橙色 - 說明爲橙色

#2在你的名單適配器,設置標籤爲指標。

view.setTag("apple"); 

#3在onListItemClick,閱讀標籤,並得到說明。

String text = view.getTag(); 
String description = myhashmap.get(text).toString(); 

// If your hashmap is mapping name and string resource id then: 
String description = getResources().getString(Integer.parseInt(myhashmap.get(text))); 
+0

謝謝!該信息是有幫助的。 –

2

您可以將事實置於數據庫中,並使用項目來索引該表。然後,您的if將由數據庫評估。它看起來像select fact from facts where item='apple'。可能有幫助嗎?也很容易添加,刪除或更改信息。此外,藉助數據庫索引,查找(if-評估)非常快。

相關問題