Android

Solve orientation layout glitch StaggeredGridview / Gridview in Android

30 May , 2014  

Just remember to remove this part

1
2
3
android:configChanges="keyboardHidden|screenSize|fontScale"
android:exported="true"
android:windowSoftInputMode="adjustResize|stateHidden"

From your activity in AndroidManifest.xml

Android

Solve navigationdrawer back arrow for detail fragment

30 May , 2014  

Here is the solution for navigationdrawer back arrow for detail fragment :

http://stackoverflow.com/questions/17258020/switching-between-android-navigation-drawer-image-and-up-caret-when-using-fragme

Android

SwipeRefreshLayout and StaggeredGridView Android

30 May , 2014  

Merging between SwipeRefreshLayout and StaggeredGridView is not easy. To make it works together, we need to do few things. Here is the way :

1. Set listener and topindex variable

1
2
3
4
5
6
private int topIndex = 0;

public class HomeFragment extends Fragment implements AbsListView.OnScrollListener,
        AbsListView.OnItemClickListener, OnRefreshListener {

}

Fyi, we need topIndex for detecting if gridview already on top position or not.

2. Set gridview and swiperefreshlayout together

1
2
3
4
5
6
7
8
9
10
11
12
13
mSwipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipe_container);
mSwipeRefreshLayout.setOnRefreshListener(this);
mSwipeRefreshLayout.setColorScheme(android.R.color.holo_blue_bright,
        android.R.color.holo_green_light,
        android.R.color.holo_orange_light,
        android.R.color.holo_red_light);

mGridView = (StaggeredGridView) rootView.findViewById(R.id.latest_photo_gridview);
mAdapter = new HomeAdapter(mContext, mPhotoList);

mGridView.setAdapter(mAdapter);
mGridView.setOnScrollListener(this);
mGridView.setOnItemClickListener(this);

3. Set onScroll to works together

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
@Override
public void onScroll(final AbsListView view, final int firstVisibleItem,
        final int visibleItemCount, final int totalItemCount) {

    // our handling
    if (!mHasRequestedMore) {
        int lastInScreen = firstVisibleItem + visibleItemCount;
        if (lastInScreen >= totalItemCount) {
            mHasRequestedMore = true;
            onLoadMoreItems();
        }
    }
       
    boolean enable = false;
   
    // Detect if already on top of Gridview
    View childView = mGridView.getChildAt(0);
    topIndex = (childView == null) ? 0 : childView.getTop();
   
    int index = mGridView.getFirstVisiblePosition();
   
    if (mGridView != null && mGridView.getChildCount() > 0 && topIndex > 0 && firstVisibleItem == 0) {
        // check if the first item of the list is visible
        boolean firstItemVisible = mGridView.getFirstVisiblePosition() == 0;
        mSwipeRefreshLayout.setEnabled(firstItemVisible);
    } else {
        mSwipeRefreshLayout.setEnabled(enable);
    }
}

4. Switch swipelayout on and off and put on OnResume and OnCreate

1
2
3
4
5
if(topIndex > 0) {
      mSwipeRefreshLayout.setEnabled(true);
} else {
      mSwipeRefreshLayout.setEnabled(false);
}

Android

Solve launching android on Device very slow

29 May , 2014  

Today, i found the culprit why launching / deploy app into devices takes about 5 – 10 seconds. Apparently it’s because external folder.

Here is the fixes :
1. Right click on your project
2. Select Build Path -> Configure Build Path
3. Go to Libraries tab
4. Remove source attachment

Remove source attachment Android

Problem solved! 😀

Django

Django request POST very slow

28 May , 2014  

When develop http://rahasiaku.com using Django and Android, i found that Django POST is very slow. After few debugging, i got the culprit :

1
2
3
4
5
6
7
8
MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
#     'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

Yes, it’s because clickjacking middleware. Disable it will solve Django slow response for request POST

,

Server

Solve VSFTPD error retrieving directory Ubuntu

16 May , 2014  

Suddenly i got this “error retrieving directory, connection timeout ..” when accessing ftp EC2 server. Then, the solution just change my FTP client from “passive mode” into “active mode”. Weird but works!

Python

Setup latest UWSGI + Django in Production Ubuntu 14.04

14 May , 2014  

It’s very hard to find article to help setup UWSGI and Django 1.7 in production. I use EC2 with Ubuntu 14.04. The only reason why I need to use uwsgi because Apache mod-wsgi can’t run together with gevent. It’s always throw LoopExit exception.

Here is solution. First, we need to install required softwares :

1. Install dependecies

1
sudo apt-get install uwsgi build-essential python-dev uwsgi-plugin-python nginx

2. Setup wsgi configuration
Here is my example, i create “/etc/uwsgi/apps-available/ecommerce-dev.ini” and symlink to “/etc/uwsgi/apps-enabled/ecommerce-dev.ini”. This is the content :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
[uwsgi]
;enable master process manager
master = true

;spawn 2 uWSGI worker processes
workers = 2

;unix socket (referenced in nginx configuration)
socket = /tmp/ecommerce-dev.sock

# set mode of created UNIX socket
chmod-socket = 666

# place timestamps into log
log-date = true

# user identifier of uWSGI processes
uid = www-data
# group identifier of uWSGI processes
gid = www-data

; number of worker processes
;processes = 2
;vacuum = true

; project-level logging to the logs/ folder
;logto = /var/yodi/ecommerce-dev/uwsgi.log

; django >= 1.4 project
chdir = /var/yodi/ecommerce-dev
wsgi-file=/var/yodi/ecommerce-dev/ecommerce/wsgi.py

;enable-threads = true

virtualenv = /home/ubuntu/.virtualenvs/production
vacuum = true
env = DJANGO_SETTINGS_MODULE=ecommerce.settings
pidfile = /tmp/ecommerce-dev.pid
;harakiri = 20 # respawn processes taking more than 20 seconds
;max-requests = 5000 # respawn processes after serving 5000 requests

3. Register WSGI services

1
sudo vim /etc/init/uwsgi.conf

And write this :

1
2
3
4
5
6
7
8
9
description "uWSGI"
start on runlevel [2345]
stop on runlevel [06]
respawn

env UWSGI=/usr/local/bin/uwsgi
env LOGTO=/var/log/uwsgi-emperor.log

exec $UWSGI --master --emperor /etc/uwsgi/apps-enabled --die-on-term --uid www-data --gid www-data --logto $LOGTO

4. Running services

1
sudo service uwsgi start

5. Setup NGINX to listen UWSGI socket

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
server {
    listen 82;
    server_name dev.custoom.com;
    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;
    root /var/yodi/ecommerce-dev;

    client_body_timeout  460;
    client_header_timeout 460;
    send_timeout 460;
    client_max_body_size 10m;
    keepalive_timeout 300;

    index  index.php index.html index.htm;

    # Check if a file exists at /var/www/domain/ for the incoming request.
    # If it doesn't proxy to Apache/Django.
    try_files $uri @django;
    location / {
        uwsgi_pass unix:/tmp/ecommerce-dev.sock;
        include uwsgi_params;
    }
}

6. Running NGINX

1
sudo service nginx restart

Success! 😀

,

Javascript

The right way to use setTimeout in inifite loop Javascript

10 May , 2014  

When we using setTimeout, actually it will assigned into some parameters with ID of task. To avoid memory leaks, we should comes with this strategy. First, declare global variable.

1
var timeOutClose;

Let say we have infinite loop function contains :

1
2
3
4
// Run timer to close box
timeOutClose = setTimeout(function() {
    $(".md-close").trigger("click");
}, animationClose * 1000);

Then we make sure to clear timeOutClose variable by put this before execution :

1
2
3
4
5
6
7
8
9
// Clear timeout                   
if (timeOutClose) {
   clearTimeout(timeOutClose);
}

// Run timer to close box
timeOutClose = setTimeout(function() {
    $(".md-close").trigger("click");
}, animationClose * 1000);

Javascript

Beware with jquery animate in infinite loop Javascript caused memory leaks

10 May , 2014  

After do Check memory leak javascript in Chrome, i found that animate and delay in Javascript quite consume memory. And it’s end up with memory leaks.

Here are my code :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
for (var i = 0; i < split; i++) {
    ...

    $("tr.cmp_tr").css({
        'display' : 'none'
    });

    for (var k = 0; k < split; k++) {
        TimeOutObj = setTimeout(function() {
            $("tr#cmp" + k).css('opacity', 1).animate({
                opacity : 1
            }, 1000);
        }, 100 * i);
    }

    var k = 0;
    TimeOutObjSecond = setTimeout(function() {
        k += 1;
    }, 100 * i);
}

Then i change this line :

1
2
3
4
5
for (var k = 0; k < split; k++) {
    TimeOutObj = setTimeout(function() {
        $("tr#cmp" + k).show();
    }, 100 * i);
}

Voila! Now memory still in 2.9MB 😀

Uncategorized

Find Memory Leak in Javascript Looping

10 May , 2014  

Always carefull when building html pages that contains looping function using Javascript. I have bad experience when building looping html that running for 24/7. Memory leaks force browser crashed and not working.

Luckily, Chrome is powerfull browser that let us to analyze memory.

Capture

Every 10 minutes, memory increased 1MB which is disaster.

How to solve it ?

1. Be careful when create new objects in loop function
2. Do garbage collection and clear variables, example :

1
2
var x = <something you do here>;
del x;

Android

Solve burger icon not showed in actionbar

1 May , 2014  

Usually, we have burger icon in top left of actionbar. When it’s disappear, it probably because several issue. First thing, make sure Fragment have :

1
2
((ActionBarActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
((ActionBarActivity)getActivity()).getSupportActionBar().setTitle(menu_title);

,