Wednesday, January 30, 2013

Part 2:Useful Eclipse Templates for Android Development

Part 1:Useful Eclipse Templates for Android Development

Weak Reference for Views in Activity.

Inside onCreate of each Android Activity we used to setContentView with layout xml. Then to access each view from the activity we use:

View view = findViewById(;

to avoid calling  findViewById multiple time,  call this only in onCreate and keep this view as member variable inside activity.

View mView


mView = findViewById(;

Then, question is why we need to overload the onCreate method, we call findViewById only when needed and keep as member variable. So introduce following get method.

View getView(){
         mView = findViewById(;
     return mView;

But in some cases, to avoid memory leakage issues, we need to remove all view from content view and need to null all these references in activity. But rather find each reference and assign to null, if we make a weak reference then it should all clear as we remove view from activity. For Example:

private WeakReference mView;
public View getView() {
if(!(mView!=null && mView.get()!=null)){
mView = new WeakReference((View) findViewById(;
return mFrameAddStyleView.get();
Now, Let see how to write a Eclipse template to auto generate this:

Eclipse - > Windows -> Preferences -> Java -> Editor -> Templates -> New ...
Name:- wfind
private WeakReference<${type}> m${new_name};
public ${type} get${new_name}() {
if(!(m${new_name}!=null && m${new_name}.get()!=null)){
m${new_name} = new WeakReference<${type}>((${type}) findViewById(${cursor}));
return m${new_name}.get();

Now go to your activity class and type wfind and press Ctrl+Space you will get what you want.