2013-10-09 31 views
2

我會什麼,我想實現相同的密鑰 - 不同價與一個HashMap

意向

軟件開始一個for循環解析XML數據。處理數據的for循環將持續到50(因爲我得到50個不同的結果)。我最初做的是,doInBackground -method解析整個XML數據並將其保存到TextView中並顯示它。但是現在我想添加一個啓動屏幕,只要數據加載就顯示出來。

XML文件的構建方式與任何其他常規XML文件相同,所以當我通過for-loop時,鍵總是相同的,但值不同。

途徑

什麼我已經做是創建一個多維數組,但不幸的是你不能使用字符串作爲索引。這就是地圖的用途。這是我的做法

stringArray[i]["source"] = sourceString; 

那麼,我試了一下地圖。但是地圖的問題是,當新密鑰再次出現時,它只會覆蓋先前的鍵值對。

所以我想通了一個字符串集合使用HashMap。我是這樣處理的; 首先,我創建的HashMap的

public HashMap <String, Collection<String>> hashMap = new HashMap<String, Collection<String>>(); 

然後我把數據HashMap的每個鍵。

hashMap.put("source"  , new ArrayList<String>()); 

這是我在for循環

hashMap.get("source").add(new String(((Node) sourceList.item(0)).getNodeValue())); 

做了之後,當完成時, - 方法開始一個新的意圖,並通過HashMap中的onPostExecute

protected void onPostExecute(Void result) { 
    super.onPostExecute(result); 
    Intent i = new Intent(SplashScreen.this, MainActivity.class); 
    i.putExtra("hashMap", hashMap); 
    startActivity(i); 
    finish(); 
} 

而在我的MainActivity我這樣做是爲了獲得數據

Intent intent = getIntent(); 
HashMap<String, String> hashMap = (HashMap<String, String>)intent.getSerializableExtra("hashMap"); 
rankingDate = new TextView(this); 
rankingDate.setText("RankingDate: " + hashMap.get("rankingDate")); 
layout.addView(rankingDate); 

但是這會導致一個ClassCastException:`的ArrayList不能在這一行

定投爲java.lang.String」

source.setText("source: " + hashMap.get("source"));

我想這是因爲hashMap.get("source")包含源數據的所有值。所以,我試圖將所有數據保存在一個字符串數組。但日沒有工作,但我不知道爲什麼。 Eclipse告訴我,Type mismatch: cannot convert from String to String[]

有什麼建議嗎?我渴望解決這個問題。

回答

5

你有一個錯字:

HashMap<String, String> hashMap = (HashMap<String, String>)intent.getSerializableExtra("hashMap"); 

應該是:

HashMap<String, Collection<String>> hashMap = (HashMap<String, Collection<String>>)intent.getSerializableExtra("hashMap"); 
+0

您好,感謝答案。但是現在我仍然有如何讀出的問題。我的理解是否正確,如果我現在要做Collectionsource = hashMap.get(「source」) - 我現在已經有了source-Collection中XML文件的所有源代碼?或者什麼是讀出數據的最佳方式。如果我可以將所有數據保存在一個數組中,這將是完美的,因爲我需要通過索引 – Musterknabe

+1

進行讀取。我個人會將'Collection '替換爲'List '。現在,假設你需要第二個元素的鍵爲'foo',然後使用:'String element = map.get(「foo」)。get(1);'。 –

+0

再次感謝您的回答,但如果可以的話,我必須再次問您一個問題。當我這樣做時它告訴我方法get(int)對於Collection類型是未定義的' 所以,我現在必須改變我的HashMap嗎?或者我會如何獲得第一個索引。 – Musterknabe

0

您在您的主要活動錯誤地鑄造你的HashMap中。

試試這個:

HashMap<String, Collection<String>> hashMap = (HashMap<String, Collection<String>>)intent.getSerializableExtra("hashMap"); 

希望這有助於:)

1

使用地圖的列表。 你可以調用list.get(index).get(「source」)並稍後獲取結果。

半僞代碼:

List<HashMap<String,String>> list = new ArrayList<HashMap<String,String>> 

foreach(entry in document) 
    map = new HashMap<String,String>(); 
    foreach(xml in entry) 
    map.put(xml,xml.value) 
    end 
    list.put(index++,map) 
end 
相關問題