Tuesday, January 27, 2015

Gesture detection and scrollview issue

In one of my latest application when I implemented ViewFlipper with gesture listener, I come across a strange issue. All child of ViewFlipper are scrollViews. I implemented simple gesture listener like when swipe to left or right will take to the next scrollView. But the issue was swipe functionality is not working in scrollView. If the ViewFlipper child are any other layout like Linearlayout, swipe functionality is working fine. As usual, I debugged and found that, we have to override the dispatchTouchEvent(MotionEvent e) of activity class.

The dispatchTouchEvent() will look like this,
public boolean dispatchTouchEvent(MotionEvent ev) {
super.dispatchTouchEvent(ev);
return gestureDetector.onTouchEvent(ev);
}
Where gestureDetector is an instance of android.view.GestureDetector class.

Reference:
http://stackoverflow.com/questions/8330187/gesture-detection-and-scrollview-issue

Thursday, January 22, 2015

How to avoid MEMORY LEAKS in Android

Memory leaks means resources which are not available for garbage collection. GC will free resources which are not referenced. Sometimes a single reference can prevent a large set of objects from being garbage collected. For example, some static variables which are referenced in an activity may not be for GC, because as long as the reference exists, the Activity will be kept in memory, leaking all of its views.

Code snippet from Romain Guy is as,

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);
}
Here, the static drawable sBackground will leak.

The solution here is when the activity gets destroyed, release the drawable in destroy and unbind all callbacks


Here, our onDestroy() will look like this,


protected void onDestroy() { 
super.onDestroy();
sBackground.setCallbacks(null);
sBackground = null;
}

So that the drawable sBackground will be available for GC and can prevent memory leak when activity gets destroyed.

Another common cause for memory leak is non-static inner classes in an Activity. This commonly comes when creating fragments in an Activity. Either create static inner classes or create stand alone classes.

Reference:
http://android-developers.blogspot.in/2009/01/avoiding-memory-leaks.html
http://stackoverflow.com/questions/6567647/avoid-memory-leaks-on-android

Androidians