Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/214.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java JSON和内存问题_Java_Android_Json - Fatal编程技术网

Java JSON和内存问题

Java JSON和内存问题,java,android,json,Java,Android,Json,我正试图将大量数据从web加载到我的android应用程序中,我遇到了以下错误: 07-18 10:16:00.575: E/AndroidRuntime(30117): java.lang.OutOfMemoryError: [memory exhausted] 并且已经读了很多关于JSON的书。我找到了一些解决办法,但没有什么真正帮助我 这是我的代码: public class HistoricoAdapter extends BaseAdapter { private Conte

我正试图将大量数据从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
肯定太大,无法缓冲到内存中

这个问题太基本了,无法解决

您需要一个高级库来流式处理响应,例如


此代码存在一些问题。我注意到的第一件事是您没有在异步任务中调用web请求。您希望用于所有长时间运行的操作,并且必须将其用于web调用

AsyncTask必须是要使用的子类。子类将重写至少一个方法(doInBackground(Params…),并且通常会重写第二个方法

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
 protected Long doInBackground(URL... urls) {
     int count = urls.length;
     long totalSize = 0;
     for (int i = 0; i < count; i++) {
         totalSize += Downloader.downloadFile(urls[i]);
         publishProgress((int) ((i / (float) count) * 100));
         // Escape early if cancel() is called
         if (isCancelled()) break;
     }
     return totalSize;
 }

 protected void onProgressUpdate(Integer... progress) {
     setProgressPercent(progress[0]);
 }

 protected void onPostExecute(Long result) {
     showDialog("Downloaded " + result + " bytes");
 }
}

也许你的json太大了你测试过真实的设备或模拟器吗?我在真实的设备上运行我们正在讨论的是多少MB?它真的很大,所以有没有其他方法来实现它,因为它很大?@JoãoPedroSegurado好的,我在gson中添加了一些链接,我必须安装它吗?我是巴西人,我的英语有一些问题,可以吗你帮我,我怎么能导入它?我仍然有很多问题,你能给我一些基于我的代码的例子吗?
Gson gson = new Gson();
int[] ints = {1, 2, 3, 4, 5};
String[] strings = {"abc", "def", "ghi"};

(Serialization)
gson.toJson(ints);     ==> prints [1,2,3,4,5]
gson.toJson(strings);  ==> prints ["abc", "def", "ghi"]