简体   繁体   中英

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

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");
}

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

Do NOT put that in the saved instance state Bundle . OutOfMemoryError is only one of your worries. You will crash with a FAILED BINDER TRANSACTION much of the time, as there is a 1MB limit on all simultaneous IPC transactions going on in your app.

If you are trying to deal with configuration changes, use something else to hold onto this information:

  • Retained fragment
  • onRetainNonConfigurationInstance()
  • ViewModel from the Android Architecture Components
  • etc.

If you are trying to deal with process termination/app restart, put an identifier in the saved instance state Bundle that will allow you to reload this list from a persistent store (database, plain file, etc.).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM