【发布时间】:2015-10-03 06:59:31
【问题描述】:
我有一个 Android 应用程序。 首先,应用程序执行同步过程。在这个过程中,服务器向设备发送一个 JSON 对象作为字符串,通过它可以构建可用的问卷。
GetQuestionnairesResponse.java:
public class GetQuestionnairesResponse extends ResponseHandler
{
public GetQuestionnairesResponse(String result, AsyncRequest request)
{
super(result, request);
}
@Override
public void handleResponse()
{
DataSyncActivity caller = (DataSyncActivity) request.getCaller();
BackgroundManager bckMng = BackgroundManager.getInstance(caller);
PreferencesManager preference = PreferencesManager.getInstance(null);
boolean status = true;
int numOfWrongJsonVer = 0;
int totalNumOfQuestionnaires = 0;
// Handle data from server
// Creating JSON Parser instance
try
{
QuestionnaireDataSource questionnaireDS = new QuestionnaireDataSource(caller);
questionnaireDS.open();
JSONArray jArr = new JSONArray(result);
JSONObject j = null;
totalNumOfQuestionnaires = jArr.length();
for (int i = 0; i < jArr.length(); i++)
{
j = jArr.getJSONObject(i);
long questId = j.getLong("questionnaireId");
long surveyId = j.getLong("surveyId");
String questName = j.getString("name");
String desc = j.getString("description");
int version = j.getInt("questionnaireVersion");
int jsonVersion = j.getInt("jsonVersion");
if (jsonVersion == PreferencesManager.jsonVersion)
{
// Save the pages part
String filename = questId + "_" + version + "_" + jsonVersion + ".json";
HelpFunctions.writeJSON(filename, j.toString());
Questionnaire quest = questionnaireDS.createQuestionnaire(questId, questName, desc, surveyId, version, jsonVersion, filename);
if (quest == null)
throw new RuntimeException("Cant save the questionnaire: " + questName);
}
else
{
numOfWrongJsonVer ++;
}
}
questionnaireDS.close();
}
catch (Exception e)
{
status = false;
if (e.getMessage() != null)
Log.e(TAG, e.getMessage());
}
caller.setInSync(false);
...
}
我从服务器获得的结果,我将其解析为 Json 数组。 在某些情况下,结果可能是 3 兆字节。
我找到的解决方案是在 manifest.xml 中添加一个属性:
android:largeHeap="true"
它解决了这个问题。我不知道为什么,但问题在最后一天再次出现。 我很乐意得到如何解决问题的建议。 问题是json对象没有按预期解析,所以它
【问题讨论】:
-
而不是通过
Gson和Jakson等自用第三方库将Json转换为对象。请勿在此问题上使用largHeap。当您想自行转换时,您将所有 json 复制到内存中,并且由于您的 json 非常大(在我的猜测中),您会得到OOM错误 -
你能用一个小例子说明你的意思吗?