我正在尝试获取一个JSON答案类型但是要大到50 MB的Android Studio抛出新的Exception OutOfMemory
class MyClass extends AsyncTask<Void, Void, Void>
{
String result="";
@Override
protected Void doInBackground(Void... params){
HttpClient httpClient=new DefaultHttpClient();
String URL="http://82.79.121.114:1001/api/search/category/3,1,1";
try{
HttpGet httpGet = new HttpGet(URL);
httpGet.setHeader("Authorization", "Bearer " + AccesToken);
HttpResponse httpResponse=httpClient.execute(httpGet);
//Log.e("EROARE!!!!!!","EROARE!!!!!");
HttpEntity httpEntity=httpResponse.getEntity();
InputStream is=httpEntity.getContent();
result=convert(is);
}catch (Exception e){
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid){
Toast.makeText(MainActivity.this,result,Toast.LENGTH_SHORT).show();
if(result.length() == 0 || result == null)
{
Toast.makeText(MainActivity.this,result.Toast.LENGTH_SHORT).show();
if(result.length() == 0 || result == null)
{
Toast.makeText(MainActivity.this,"Nu merge!!!",Toast.LENGTH_SHORT).show();
}
}
public String convert(InputStream is) throws IOException {
BufferedReader reader = null;
StringBuffer buffer = new StringBuffer();
try {
reader = new BufferedReader(new InputStreamReader(is,"UTF-8"),8192);
int read;
char[] chars = new char[1024];
while ((read=reader.read(chars)) != -1)
buffer.append(chars, 0, read);
}
finally {
if (reader != null)
reader.close();
}
return buffer.toString();
}
答案 0 :(得分:0)
您的JSON对象太大了,因为大多数设备都没有这么大的堆。如果您拥有服务器端,则应更改发送给客户端的响应,并按顺序处理几个单独的响应。
此外,我建议您重新考虑为什么一次发送这么多数据。即使在普通的互联网连接上也需要很长时间才能加载。
答案 1 :(得分:0)
如果确实OutOfMemory问题与您的REST服务返回的数据大小有关,那么您在服务器端和客户端都做错了。移动应用程序应该关心用户数据流量以及他们的电池,因此不是一次性加载整个JSON,也可以将其拆分为页面并仅加载第一页。一旦用户对更多内容感兴趣(可能您在那里使用ListView来显示这些类别),那么您将加载下一页,依此类推。请在此处查看Android的无尽列表模式: https://github.com/codepath/android_guides/wiki/Endless-Scrolling-with-AdapterViews