The code provided is not necessarily the cause of OutOfMemoryError. The main reason for OutOfMemory is that the JVM GC cannot free up enough memory for your operation.
Assuming that setContentView is really a tough operation and reduces the size of the image resolution, it will solve it for a while, this problem will reappear in another place on the system at another time.
You can indicate the reasons why the GC cannot allocate enough space, usually this means that you have some outdated link in the code that you need to clear to help your GC.
I would suggest using a profiler for your application to keep track of how space is allocated and cleaned up in your application. You have a default default with Android.
source share