Search code examples
javaandroidjsongsonsavestate

OutOfMemory exception when converting object to Json through Gson


i am getting

java.lang.OutOfMemoryError

for some users (not always) when I convert a list of object to JSON using Gson. please tell me how to fix that.

@Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if(myList != null && !myList.isEmpty()) {
            //exception at this line
            String myJson = new Gson().toJson(myList, myList.getClass());
            outState.putString(MY_LIST, myJson);
        }
        outState.putInt(NEXT_PAGE, getNextPage());
    }

myList is the list of my custom object and size of list is 400kb to 600kb


Solution

  • This will depend on the size of your list. Why don't you use streaming API https://sites.google.com/site/gson/streaming

    To be more specific something like

    public String writeListToJson(List myList) throws IOException {
        ByteArrayOutputStream byteStream =new ByteArrayOutputStream();
        OutputStreamWriter outputStreamWriter=new OutputStreamWriter(byteStream ,"UTF-8");
        JsonWriter writer = new JsonWriter(outputStreamWriter);
        writer.setIndent("  ");
        writer.beginArray();
        Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().setPrettyPrinting().create();
        for (Object o : myList) {
            gson.toJson(o, o.class, writer);
        }
        writer.endArray();
        writer.close();
        return byteStream.toString("UTF-8");
    }