java json写入内存_java – JSON和内存问题

我正在尝试从Web加载大量数据到我的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.

标签:json,java,android

来源: https://codeday.me/bug/20190703/1363875.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值