我正在尝试从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 – Streaming
> Jackson – Processing model: Streaming API