Reputation: 318
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
Upvotes: 0
Views: 3607
Reputation: 1006964
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:
onRetainNonConfigurationInstance()
ViewModel
from the Android Architecture ComponentsIf 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.).
Upvotes: 1
Reputation: 4507
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");
}
Upvotes: 1