我正在尝试解码 json 字符串并对内容做一些处理。我有这段代码,只要用户按下按钮就会运行:
public List<Card> readCards()
{
List<Card> cards = new ArrayList<Card>();
HttpReader httpReader = new HttpReader();
httpReader.setOnResultReadyListener(new HttpReader.OnResultReadyListener() {
@Override
public void resultReady(String result) {
JsonHelper jsonHelper = new JsonHelper();
List<Card> cards = jsonHelper.getCards(result);
for (int i = 0; i < cards.size(); i++ ) {
cards.add(new Card(cards.get(i).getId(), cards.get(i).getNaam(), cards.get(i).getMana(), cards.get(i).getAttack(), cards.get(i).getHealth(), cards.get(i).getEffect(), cards.get(i).getZeldzaamheid(), cards.get(i).getTypeId(), cards.get(i).getSubtypeId(), cards.get(i).getClassId(), cards.get(i).isGoud()));
}
}
});
httpReader.execute("http://jsonstring.com"); //link to json-file
return cards;
}
jsonHelper
类中的 getCards(result)
方法是这样的:
public List<Card> getCards(String jsonText) {
List<Card> list= new ArrayList<Card>();
try {
JSONArray jsonArrayCards = new JSONArray(jsonText);
for (int i = 0; i < jsonArrayCards.length(); i++) {
JSONObject jsonObjectCard = jsonArrayCards.getJSONObject(i);
Card card = new Card();
if ( jsonObjectCard.has("id")) { card.setId(jsonObjectCard.getString("id")); } else { card.setId("none"); }
if ( jsonObjectCard.has("name")) { card.setNaam(jsonObjectCard.getString("name")); } else { card.setNaam("none"); }
if ( jsonObjectCard.has("cost")) { card.setMana(jsonObjectCard.getInt("cost")); } else { card.setMana(0); }
if ( jsonObjectCard.has("attack")) { card.setAttack(jsonObjectCard.getInt("attack")); } else { card.setAttack(0); }
if ( jsonObjectCard.has("health")) { card.setHealth(jsonObjectCard.getInt("health")); } else { card.setHealth(0); }
if ( jsonObjectCard.has("text")) { card.setEffect(jsonObjectCard.getString("text")); } else { card.setEffect(""); }
card.setTypeId(1);
card.setSubtypeId(1);
card.setClassId(1);
list.add(card);
}
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return list;
}
完成此操作后,我尝试显示返回列表的大小,由于某种原因为 0。
第一次点击按钮后,应用卡住。日志显示 java.lang.OutOfMemoryError
json 文件是 <200 行,可能是 5kb,所以这应该不是问题。
如有任何帮助,我们将不胜感激。
最佳答案
您的程序陷入死循环。您正在将卡片添加到您的卡片列表中,该列表会不断增长,直到内存不足
for (int i = 0; i < cards.size(); i++ ) {
cards.add(new Card(cards.get(i).getId(),...
}
循环永远无法完成,因为您测试了 i < cards.size()
每个 new Card
添加 cards.size
增加。
关于Java Android Json OutOfMemoryError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27460893/