簡體   English   中英

android從字符串創建數組並添加到數組列表

[英]android create array from string and add to array list

嗨,我正在嘗試創建一個聯系人列表,我有一個聯系人數組,並且我遍歷每個聯系人並獲取姓氏的第一個字符。 然后,我試圖用該字符的值創建一個數組並將其添加到我的最終數組中。 然后,我想檢查該數組是否已存在於我的最終數組中。 如果沒有將其添加到數組中。

目的是讓我最終得到一個數組列表,該數組列表將成為列表視圖中的標頭。 有誰知道如何創建一個空數組並將其命名為字符串的值(稍后我將向該數組中添加內容)? 然后將其添加到數組列表中?

到目前為止,這是我嘗試過的方法,但是我正在努力使自己轉回正題

for (int i=0; i<contactsJSONArray.length(); i++) {
  singleContactDict = contactsJSONArray.getJSONObject(i);
  Log.v("Main", "Contact singleContactDict " + i +"= " + singleContactDict);
  String firstname = singleContactDict.getString("first_name");
  String lastname = singleContactDict.getString("last_name");

  char firstLetterInLastname = lastname.charAt(0);
  Log.v("Main", "firstLetterInLastname = " + firstLetterInLastname);
  headerWithLetterArray.add((firstLetterInLastname).toArray);
}

數組類似於[a,b,c,d],它們沒有名稱。 如果您的意思是JSONArray,並且要存儲的所有內容都是JSONObcject,請嘗試:

parentJson.put(lastname.substring(0,1), new JSONArray());

您可以嘗試使用“地圖”作為最終集合。 您姓氏的第一個字符可以是映射中的鍵,並且真實姓名將成為值(內部值可以是數組列表)。

當您要向列表中添加新聯系人時,可以先在地圖中查找帶有第一個字母的鍵。 如果是,則獲取為arraylist的值,然后向其添加新聯系人。

這樣,您將有很多由map中的單個字母標記的arraylist,可在循環中使用它來填充列表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM