我有一个for循环,我正在为循环中的HashMap添加值。基本上我有一个帖子,它有评论。一篇帖子有8条评论,我需要HashMap的内容如下图所示:
for (int i2 = 0; i2 < conversationArray.length(); i2++) {
JSONObject conversationArray1 = conversationArray.getJSONObject(i2);
contentConversation = conversationArray1.getString("content");
commenterId = conversationArray1.getString("commenterId");
commenterName = conversationArray1.getString("commenterName");
commenterPhotos = conversationArray1.getString("commenterPhotos");
postIdForComments = conversationArray1.getString("postId");
lastDateUpdatedConversation = conversationArray1.getString("lastDateUpdated");
dateCreatedConversation = conversationArray1.getString("dateCreated");
commentDescription.add(contentConversation);
commentUserName.add(commenterName);
commentProfileImageLink.add(commenterPhotos);
commentProfileImageHashMap.put(postIdForComments, commenterPhotos);
commentDescriptionHashMap.put(postIdForComments, contentConversation);
commentUserNameHashMap.put(postIdForComments, commenterName);
}
但是,现在我的hashmap只包含第一个值。只有在第一次迭代中,值才会被添加到HashMap中,如何在所有8次迭代中为hashmap添加值。
PS:所有八个值的PostID应相同。
我当前的代码:
//Android Manifest -- i have set all activities as DEFAULT except LAUNCHER activity.
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
@Override// In Main Activity I have put this code to exit app when back is pressed
public void onBackPressed() {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
请让我知道我应该在代码中做出哪些更改,以实现我的目标。欢迎提出所有建议。
答案 0 :(得分:2)
使用Map<String, List<String>>
存储每篇帖子的评论列表:
Map<String, List<String>> mapOfPosts = new HashMap<>();
List<String> post1Comments = new ArrayList<>();
// Collect comments of a certain post
post1Comments.add("comment1");
post1Comments.add("comment2");
...
// Attach comments to post
mapOfPosts.put("post1", post1Comments);
// Repeat this for all posts