[英]Java/Android: java.lang.OutOfMemoryError while building a JSON object
[英]Java Android Json OutOfMemoryError
我正在嘗試解碼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
。
您的for循環是導致錯誤的原因
for (int i = 0; i < cards.size(); i++ )
而且在for循環中使用cards.size()並不是最佳實踐。 改為使用
int count = cards.size();
始終在for循環中使用此int。 這比舊的要快。 因為在舊代碼中, 每次 for循環都會計數卡
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.