android_guides icon indicating copy to clipboard operation
android_guides copied to clipboard

Do create View passing Activity as Context cause memory leak?

Open iceteahh opened this issue 7 years ago • 6 comments

public class MainActivity extends Activity {
        private TextView textView;
        protected void onCreate(Bundle savedInstanceState) {
              textView = new TextView(this);
              textView.setText("some text");
              setContentView(textView);
        }
}

We have two objects: one instance of MainActivity and one instance of TextView and both of them have reference to each other. So basically it will cause the memory leak. Am I right?

iceteahh avatar Jan 12 '18 09:01 iceteahh

@iceteahh

Memory leaks happen when you hold on to an object long after its purpose have been served. But in the above mentioned case textView object will be released before the MainActivity destroyed. So this will not cause a Memory Leak. Correct me incase i am wrong.

sumit007 avatar Jan 12 '18 10:01 sumit007

@sumit007 In my case above MainActivity hold reference to TextView and same for TextView. So in order to release MainActivity GC need to release TextView first but to release TextView it has to release MainActivity. So we have a loop here. And they maybe will never be released.

iceteahh avatar Jan 12 '18 10:01 iceteahh

GC consider an object as "garbage" if it cant be reached from GC root. Your case is not memory leak, objects will be destroyed.

You could easily check that overriding object's finalize() method.

AShuba avatar Jan 12 '18 16:01 AShuba

@iceteahh I am agree with @AShuba, in your case if variable textView is static then it will cause a memory leak. Rule of thumb is static view will leak the activity, So never declare a static view.

sumit007 avatar Jan 18 '18 07:01 sumit007

... as static? )

AShuba avatar Jan 18 '18 18:01 AShuba

Updated the comment.

sumit007 avatar Jan 19 '18 04:01 sumit007