jsonarray在Android中退出记忆例外



在我的应用中,我在一天结束时将一些数据同步到应用服务器。对于此,我将所有数据包装为JSONOBJECT的JSONARRAY。该数据主要包括大约50个图片大小约为50kb(以及一些文本数据)。所有这些图片都是使用base64编码编码的。当图片上传(以及一些文本数据)的数量很少,但是当我上传大图时,,说大约50个然后在日志中看到所有数据都正确形成了JSONARRAY,但是当我尝试使用'array.tostring()'方法''方法'我遇到一个不记忆的例外时,我相信这是由于堆变得饱满(但是,当我尝试制作Android:gromheap =" true"中的一切都很好,但是我想避免使用这种方法,因为这不是一个好练习)。我的意图只是要将此JSONARRAY值写入文件中,然后将此文件分解为小块,然后将其发送到服务器。请指导我将jsonaray值写入文件的最佳方法,而不会导致oom问题。谢谢!

以下是jsonarray的格式:

[{"pid":"000027058451111","popup_time":"2014-01-13 23:36:01","picture":"...base64encoded string......","punching_time":"Absent","status":"Absent"},{"pid":"000027058451111","popup_time":"2014-01-13 23:36:21","picture":"...base64encoded string......","punching_time":"Absent","status":"Absent"}]

以下是我代码的主要片段:

            JSONObject aux;
            JSONArray array = new JSONArray();
            .
            .
            // Looping through each record in the cursor
            for (int i = 0; i < count; i++) {
                aux = new JSONObject();
                try {
                    aux.put("pid", c.getString(c.getColumnIndex("pid")));
                    aux.put("status", c.getString(c.getColumnIndex("status")));
                    aux.put("pop_time", c.getString(c.getColumnIndex("pop_time")));
                    aux.put("punching_time", c.getString(c.getColumnIndex("punching_time")));
                    aux.put("picture", c.getString(c.getColumnIndex("image_str"))); // stores base64encoded picture
                } catch (Exception e) {
                    e.printStackTrace();
                }
                array.put(aux); // Inserting individual objects into the array , works perfectly fine,no error here
                c.moveToNext(); // Moving the cursor to the next record
            }
            Log.d("Log", "length of json array - "+array.length()); // shows me the total no of JSONObjects in the JSONArray,works fine no error
            // HAD GOT OOM HERE
            //Log.d("Log", "JSONArray is - " + array.toString()); 
            if (array.length() != 0){
                try {
                    String responseCode = writeToFile(array);  //Writing the JSONArray value to file,which will then send file to server.
                    if(responseCode.equals("200"))
                        Log.d("Log","Data sent successfully from app to app server");
                    else    
                        Log.d("Log","Data NOT sent successfully from app to app server");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            .
            .
            private String writeToFile(JSONArray data) {
            Log.d("Log", "Inside writeToFile");
            File externalStorageDir = new File(Environment.getExternalStorageDirectory().getPath(), "Pictures/File");
            if (!externalStorageDir.exists()) {
                externalStorageDir.mkdirs();
            }
            String responseCode = "";
            File dataFile = new File(externalStorageDir, "File");
    /*      FileWriter writer;
            String responseCode = "";
            try {
                writer = new FileWriter(dataFile);
                writer.append(data);
                writer.flush();
                writer.close();
                responseCode = sendFileToServer(dataFile.getPath(), AppConstants.url_app_server); // Sends the file to server,worked fine for few pictures
            } catch (IOException e) {
                e.printStackTrace();
            }*/

            try {
                FileWriter file = new FileWriter("storage/sdcard0/Pictures/File/File");
                file.write(data.toString());        // GOT OOM here.
                file.flush();
                file.close();
                Log.d("Log","data  written from JSONArray to file");
                responseCode = sendFileToServer(dataFile.getPath(), AppConstants.url_app_server);    // Sends the file to server,worked fine for few pictures
            } catch (IOException e) {
                e.printStackTrace();
            }
            return responseCode;
        }

        public String sendFileToServer(String filename, String targetUrl) {
            .
            .
            // Sends the file to server,worked fine for few pictures
            .
            .
            return response;
        }

这是问题。您正在尝试将整个数据集加载到内存中。而且您的内存不足。

Android的JSON类(以及其他一些JSON库)旨在采用Java对象(在内存中),将其序列化为对象的解析树(例如JSONObjectJSONArray)(在内存中),然后将该树转换为一个树String(在内存中)并将其写出某个地方。

特别是在您的情况下(目前),当它将解析树转换为 String时,它会出现在内存中;String有效地使当时所需的内存量增加了一倍。

要解决您的问题,您有一些不同的选择,我将提供3:

  • 根本不使用JSON。重构只需将文件和信息发送到您的服务器。

  • 重构事物,因此您一次仅将X图像读为存储器并具有多个输出文件。其中x是一定数量的图像。请注意,如果您的图像大小变化很大/不可预测。

  • 切换使用杰克逊作为JSON库。它支持流动操作,在您在数组中创建每个对象时,您可以将JSON流式传输到输出文件。

编辑要添加:对于您的代码,使用杰克逊(Jackson)看起来像这样的东西:

// Before you get here, have created your `File` object
JsonFactory jsonfactory = new JsonFactory();
JsonGenerator jsonGenerator = 
    jsonfactory.createJsonGenerator(file, JsonEncoding.UTF8);
jsonGenerator.writeStartArray();
// Note: I don't know what `c` is, but if it's a cursor of some sort it
// should have a "hasNext()" or similar you should be using instead of
// this for loop
for (int i = 0; i < count; i++) {
    jsonGenerator.writeStartObject();
    jsonGenerator.writeStringField("pid", c.getString(c.getColumnIndex("pid")));
    jsonGenerator.writeStringField("status", c.getString(c.getColumnIndex("status")));
    jsonGenerator.writeStringField("pop_time", c.getString(c.getColumnIndex("pop_time")));
    jsonGenerator.writeStringField("punching_time", c.getString(c.getColumnIndex("punching_time")));
    // stores base64encoded picture
    jsonGenerator.writeStringField("picture", c.getString(c.getColumnIndex("image_str")));
    jsonGenerator.writeEndObject();
    c.moveToNext(); // Moving the cursor to the next record
}
jsonGenerator.writeEndArray();
jsonGenerator.close();

以上未经测试,但应该起作用(或至少使您朝正确的方向前进)。

首先。感谢布莱恩·罗奇(Brian Roach)协助我的十亿美元。他的投入帮助我解决了问题。我正在分享我的答案。

我想解决什么? - 在我的项目中,我有一些用户数据(名称,年龄,picture_time)和每个用户数据的一些相应图片。在EOD中,我需要将所有这些数据同步到应用程序服务器。图片(例如50kb中的50个)我遇到了一个OOM(不记忆)问题。从本质上讲,我试图使用常规的JsonArray方法上传所有数据,但是很快我发现自己正在击中OOM。当我试图访问jsonarray时,堆变得完整(哪个值有很多值,为什么不呢?>

Brian的输入建议我将所有数据写入一个文件。它,然后将此文件流到服务器。

以下是代码段,该代码段从App Database获取用户数据,SD卡中的相应图片,通过所有记录循环,使用Jackson JSON库创建JSONOBJECTS的JSONARRAY(您需要在Libs Folder中包括在内,您可以使用此代码并将它们存储到文件中。然后将文件流传输到服务器(不包括此片段)。希望这可以帮助某人!


            // Sync the values in DB to the server
            Log.d("SyncData", "Opening db to read files");
            SQLiteDatabase db = context.openOrCreateDatabase("data_monitor", Context.MODE_PRIVATE, null);
            db.execSQL("CREATE TABLE IF NOT EXISTS user_data(device_id VARCHAR,name VARCHAR,age VARCHAR,picture_time VARCHAR);");
            Cursor c = db.rawQuery("SELECT * FROM user_data", null);
            int count = c.getCount();
            if (count > 0) {
                File file = new File(Environment.getExternalStorageDirectory().getPath(), "Pictures/UserFile/UserFile");
                JsonFactory jsonfactory = new JsonFactory();
                JsonGenerator jsonGenerator = null;
                try {
                    jsonGenerator = jsonfactory.createJsonGenerator(file, JsonEncoding.UTF8);
                    jsonGenerator.writeStartObject();       
                    jsonGenerator.writeArrayFieldStart("user_data"); //Name for the JSONArray
                } catch (IOException e3) {
                    e3.printStackTrace();
                }
                c.moveToFirst();
                // Looping through each record in the cursor
                for (int i = 0; i < count; i++) {               
                    try {
                        jsonGenerator.writeStartObject();  //Start of inner object '{'
                        jsonGenerator.writeStringField("device_id", c.getString(c.getColumnIndex("device_id")));
                        jsonGenerator.writeStringField("name", c.getString(c.getColumnIndex("name")));
                        jsonGenerator.writeStringField("age", c.getString(c.getColumnIndex("age")));
                        jsonGenerator.writeStringField("picture_time", c.getString(c.getColumnIndex("picture_time")));

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    // creating a fourth column for the input of corresponding image from the sd card
                    Log.d("SyncData", "Name of image - " + c.getString(c.getColumnIndex("picture_time")));
                        image = c.getString(c.getColumnIndex("picture_time")).replaceAll("[^\d]", ""); //Removing everything except digits
                        Log.d("SyncData", "imagename - " + image);
                        File f = new File(Environment.getExternalStorageDirectory().getPath(), "Pictures/UserPic/" + image + ".jpg");
                        Log.d("SyncData", "------------size of " + image + ".jpg" + "= " + f.length());
                        String image_str;
                        if (!f.exists() || f.length() == 0) {
                            Log.d("SyncData", "Image has either size of 0 or does not exist");
                            try {
                                jsonGenerator.writeStringField("picture", "Error Loading Image");
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {
                            try {
                                // Reusing bitmaps to avoid Out Of Memory
                                Log.d("SyncData", "Image exists,encoding underway...");
                                if (bitmap_reuse == 0) {    //ps : bitmap reuse was initialized to 0 at the start of the code,not included in this snippet
                                    // Create bitmap to be re-used, based on the size of one of the bitmaps
                                    mBitmapOptions = new BitmapFactory.Options();
                                    mBitmapOptions.inJustDecodeBounds = true;
                                    BitmapFactory.decodeFile(f.getPath(), mBitmapOptions);
                                    mCurrentBitmap = Bitmap.createBitmap(mBitmapOptions.outWidth, mBitmapOptions.outHeight, Bitmap.Config.ARGB_8888);
                                    mBitmapOptions.inJustDecodeBounds = false;
                                    mBitmapOptions.inBitmap = mCurrentBitmap;
                                    mBitmapOptions.inSampleSize = 1;
                                    BitmapFactory.decodeFile(f.getPath(), mBitmapOptions);
                                    bitmap_reuse = 1;
                                }
                                BitmapFactory.Options bitmapOptions = null;
                                // Re-use the bitmap by using BitmapOptions.inBitmap
                                bitmapOptions = mBitmapOptions;
                                bitmapOptions.inBitmap = mCurrentBitmap;
                                mCurrentBitmap = BitmapFactory.decodeFile(f.getPath(), mBitmapOptions);
                                if (mCurrentBitmap != null) {
                                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
                                    try {
                                        mCurrentBitmap.compress(Bitmap.CompressFormat.JPEG, 35, stream);
                                        Log.d("SyncData", "------------size of " + "bitmap_compress" + "= " + mCurrentBitmap.getByteCount());
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                    byte[] byte_arr = stream.toByteArray();
                                    Log.d("SyncData", "------------size of " + "image_str" + "= " + byte_arr.length);
                                    stream.close();
                                    stream = null;
                                    image_str = Base64.encodeToString(byte_arr, Base64.DEFAULT);
                                    jsonGenerator.writeStringField("picture", image_str);
                                }
                            } catch (Exception e1) {
                                e1.printStackTrace();
                            }
                        }
                    try {
                        jsonGenerator.writeEndObject();  //End of inner object '}'
                    } catch (JsonGenerationException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    c.moveToNext(); // Moving the cursor to the next record
                }
                try {
                    jsonGenerator.writeEndArray();      //close the array ']'
                    //jsonGenerator.writeStringField("file_size", "0");   // If need be, place another object here.
                    jsonGenerator.writeEndObject();     
                    jsonGenerator.flush();
                    jsonGenerator.close();
                } catch (JsonGenerationException e1) {
                    e1.printStackTrace();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                c.close();
                db.close();
            }       

最新更新