Do create View passing Activity as Context cause memory leak?
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
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
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.
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.
@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.
... as static? )
Updated the comment.