понедельник, 13 июня 2011 г.

Lazy pattern for Android

Many time I needed to do some actions "lazy" in code. Especially writing code for Android requires us to save resources of devices. There is not in problem in other languages like C#, ruby, etc. But in Java I did not find anything that could have helped me. So that here is my implementation of this pattern :)

First of all we have to declare action which should be done "lazy":

public interface ILazyAction<T> {
    T get();
}
And then create class which will evaluate our "lazy" action:
public class Lazy<T> {
    private T obj;
    private final ILazyAction<T> lazyAction;

    public Lazy(ILazyAction<T> lazyAction) {
        this.lazyAction = lazyAction;
    }

    public T getValue() {
        if (obj == null) {
            obj = lazyAction.get();
        }
        return obj;
    }
}
So that is all :) Now you can write something like
Lazy<Drawable> flag = new Lazy<Drawable>(new ILazyAction<Drawable>() {
   public Drawable get() {
        return context.getResources().getDrawable(R.drawable.flag);
     }
});
and then everywhere you can access to flag variable

flag.getValue()
So it is simple, is not it? :)
Yes, but actually there is one issue. The issue is called concurrency. The code is not thread safe because we do not expect that more than one thread can call initialization of the object.
It is easy to solve this problem:

public class Lazy<T> {
    private T obj;
    private final ILazyAction<T> lazyAction;
    private final Object lock = new Object();

    public Lazy(ILazyAction<T> lazyAction) {
        this.lazyAction = lazyAction;
    }

    public T getValue() {
        if (obj == null) {
            synchronized (lock) {
                if (obj == null) {
                    obj = lazyAction.get();
                }
            }
        }
        return obj;
    }
}
And now it is ready to work :)

App Shelf is released

We are happy to announce our new android application App Shelf. The tool allows you to organize your applications quickly and easily.
Yes everyone can say that there are a lot of such applications in Google Market but our application does its work automatically depending on the categories in Google Android Market. And of course it also allows you to change the organization according to your wishes.
The interface of application is very simple and consists of  two tabs. The first one allows to change your groups, the second one allows to change applications on your device.

In order to have quick access to the groups there is desktop shortcut which can be created from the appropriate menu (desktop context menu -> Shortcuts).
So do not hesitate to install App Shelf on your device ;). And do not forget to write a feedback here or on leetex.dev@gmail.com.

Link to Market: App Shelf
QR-code: