JSON从数据库中读取4700条记录

时间:2011-09-29 00:35:40

标签: android json

我的Android应用程序使用此代码通过JSONArray从Web上的mysql数据库读取和导入4700条记录:

@Override
        protected String doInBackground(Void... params) {
            try{
                httpclient = new DefaultHttpClient();
                HttpGet httpget = new HttpGet("http://www.example.com/preleva_prodotti.php");       
                HttpResponse response = httpclient.execute(httpget);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();
            }catch(Exception e){
                //Log.e("log_tag", "Error in http connection "+ e.toString());
                httpclient.getConnectionManager().shutdown();
                return result = "no_server";
            }

            //convert response to string
            try{
                BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                String k = reader.readLine();
                while ((line = k) != null) {
                sb.append(line + "\n");
                }
                is.close();
                result=sb;
            }catch(Exception e){
                return result = "no_server";
            }
            //parse json data
            try{
                JSONObject json= new JSONObject(result);
                JSONArray jArray = json.getJSONArray("array");
                            return is_full="ok_insert";
            }catch(JSONException e){
                Log.e("log_tag", "Error parsing data "+e.toString());
                return is_full = "no_dati";
            }
        }

但是在这一行:

while ((line = k) != null) {
        sb.append(line + "\n");
}

出现错误:内存不足。 怎么解决这个问题?

1 个答案:

答案 0 :(得分:2)

我对Java不太熟悉,所以请耐心等待,但这似乎与语言无关。

尽管如此,问题似乎是k永远不会更新。一旦k被分配(k = reader.readLine()),您(无限期地)重新分配line 相同的值(因此无限循环,因此内存不足)。

我认为你在寻找:

            String k = reader.readLine();
            while ((line = k) != null) {
              sb.append(line + "\n");
              k = reader.readLine(); // or some facsimile
            }

请注意,我现在重新分配k(虽然我不确定k = line的冗余;似乎浪费了变量,imho)