gpt4 book ai didi

java - JSON 和内存问题

转载 作者:太空宇宙 更新时间:2023-11-03 10:20:09 39 4
gpt4 key购买 nike

我正在尝试从网络加载大量数据到我的 android 应用程序,但我一直收到此错误:

07-18 10:16:00.575: E/AndroidRuntime(30117): java.lang.OutOfMemoryError: [memory exhausted]

并且已经阅读了很多关于 JSON 的内容。我找到了一些解决方案,但没有任何帮助。

这是我的代码:

public class HistoricoAdapter extends BaseAdapter {
private Context ctx;
JSONArray jsonArray;

public HistoricoAdapter(Context ctx) {
this.ctx = ctx;

String readHttp = readHttp();

try {
// transforma a string retornada pela função readHttp() em array
jsonArray = new JSONArray(readHttp);
} catch (Exception e) {
e.printStackTrace();
}

}

public String readHttp() {

// Acessa a URL que retorna uma string com os dados do banco
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("some url");
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();

int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} else {
Log.e(this.toString(), "Erro ao ler JSON!");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

return builder.toString();
}

public int getCount() {
return jsonArray.length();
}
public boolean isEmpty(){

if(jsonArray.toString().isEmpty()){
return true;
}
else {
return false;
}
}

public Object getItem(int position) {
JSONObject ob = null;
try {
ob = jsonArray.getJSONObject(position);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return ob;
}

public long getItemId(int arg0) {
return 0;
}

public View getView(int position, View view, ViewGroup arg2) {

LayoutInflater layout = (LayoutInflater) ctx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

View v = layout.inflate(R.layout.listar_compromisso, null);

try {
JSONObject obj = (JSONObject) getItem(position);



} catch (Exception ex) {

}

return v;
}
}

谁能预测我为什么会收到此错误?

最佳答案

如果您收到此错误,则您的 JSON 必须太大而无法缓冲到内存中。

问题是org.json太基础了,无法处理。

您需要一个高级库来流式传输响应,例如 GSON Jackson .

关于java - JSON 和内存问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24826051/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com