title: Check and Avoid Memory Leaks in Application
body: <p>So, I am done with a project, now the main issue I am facing is the <strong>Memory Leakage</strong> in the application <em>(“leak” meaning you keep a reference to an activity, thus preventing the GC from collecting it)</em></p>
  
  <p>Some of the cases I found, where the memory leakage occurs are:</p>
  
  <h2>Context Leakage</h2>
  
  <p>It occurs because of long lived reference to the activity context.</p>
  
  <p>A very good example of it i found <a href="https://stackoverflow.com/q/6567647/1626878">here</a>,</p>
  
  <pre><code>private static Drawable sBackground;
  
  @Override
  protected void onCreate(Bundle state) {
    super.onCreate(state);
  
    TextView label = new TextView(this);
    label.setText("Leaks are bad");
  
    if (sBackground == null) {
      sBackground = getDrawable(R.drawable.large_bitmap);
    }
    label.setBackgroundDrawable(sBackground);
  
    setContentView(label);
  }
  </code></pre>
  
  <p>here the problem is with <code>private static Drawable sBackground;</code> The static Drawable is created with the Activity as the context, so in THAT case, there's a static reference to a Drawable that references the Activity, and that's why there's a leak. As long as that reference exists, the Activity will be kept in memory, leaking all of its views.</p>
  
  <h2>Screen orientation change</h2>
  
  <p>The second case that draws the attention is when the screen orientation changes. When the screen orientation changes the system will, by default, destroy the current activity and create a new one while preserving its state. In doing so, Android will reload the application’s UI from the resources. Now imagine you wrote an application with a large bitmap that you don’t want to load on every rotation.</p>
  
  <p>This will result in a lot of memory leakage as there could be large bitmaps to load.</p>
  
  <h2>context-activity</h2>
  
  <p>The third case, I found was the reference to the activity context. It also results in memory leakage.</p>
  
  <p>I wonder if there is any easy way to avoid such memory leakages from
  happening. or if there could be tool  to check and remove those
  memory leakages from the application.</p>