[英]Java / Android - JSON Parsing to Create New Multi-Message Chat Only Results in One Message
I'm attempting to parse a JSON Array into multiple messages - however in my current implementation each subsequent message in my Array overwrites the value of msg instead of creating a new message for each message value in the array. 我正在尝试将JSON数组解析为多个消息-但是,在当前的实现中,数组中的每个后续消息都会覆盖msg的值,而不是为数组中的每个消息值创建新消息。 I understand I'll need to create a new message inside my for loop - but I can't seem to figure out how to do so programmatically.
我知道我需要在for循环内创建一条新消息-但我似乎无法弄清楚如何以编程方式进行操作。
Any suggestions are appreciated. 任何建议表示赞赏。
{"messages":[{"message":"User has joined.","type":"agent","created":"2016-11-26 12:56:02","name":"Test User"},{"message":"Hello World?","type":"agent","created":"2016-11-26 12:56:05","name":"Test User"}]}
private void populateMessages(JSONObject msgObj) {
for (int i = 0; i < msgObj.length(); i++) {
messages = ChatMessage.fromJson(msgObj);
mAdapter.clear();
mAdapter.addAll(messages);
mListView.invalidateViews();
mAdapter.notifyDataSetChanged();
}
}
public static ChatMessage fromJson(JSONObject jsonObject) {
ChatMessage msg = new ChatMessage();
try {
JSONArray items = jsonObject.getJSONArray("messages");
for (int i = 0; i < items.length(); i++) {
JSONObject json_data = items.getJSONObject(i);
if(json_data.getString("message") != null)
msg.message = json_data.getString("message");
if(json_data.getString("type") != null)
msg.type = json_data.getString("type");
if(json_data.getString("name") != null)
msg.name = json_data.getString("name");
if(msg.message.equals("Waiting for user.")){
if(json_data.getString("created") != null)
msg.created = convertInitalTime(json_data.getString("created"));
}
else{
if(json_data.getString("created") != null)
msg.created = convertTime(json_data.getString("created"));
}
}
} catch (JSONException e) {
e.printStackTrace();
return null;
}
return msg;
}
private void populateMessages(JSONObject msgObj) {
messages = ChatMessage.fromJson(msgObj);
mAdapter.clear();
mAdapter.addAll(messages);
mListView.invalidateViews();
mAdapter.notifyDataSetChanged();
}
public static ArrayList<ChatMessage> fromJson(JSONObject jsonObject) {
ArrayList<ChatMessage> messages = new ArrayList<>();
try {
JSONArray items = jsonObject.getJSONArray("messages");
for (int i = 0; i < items.length(); i++) {
ChatMessage msg = new ChatMessage();
....
....
messages.add(msg);
}
}
return messages;
}
Move your new object in for loop
and use ArrayList
在
for loop
移动新对象并使用ArrayList
Remove for loop in populteMessage
在
populteMessage
删除for循环
And in java prefer setter and getters 在Java中,更喜欢使用setter和getters
Thats all.. 就这样..
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.