Have you ever got a

1
OutOfMemoryError
while compiling an Android project, just like this?

1
2
3
4
5
6
7
8
9
10
11
:app:dexDebug
Unknown source file : Uncaught translation error: java.util.concurrent.ExecutionException: java.lang.OutOfMemoryError: Java heap space
Unknown source file : 1 error; aborting

:app:dexDebug FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:dexDebug'.
> com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command '/Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home/bin/java'' finished with non-zero exit value 1

The quick solution is: add

1
javaMaxHeapSize
to
1
dexOptions
in your build.gradle, adjusting the value on your needs.

1
2
3
4
5
6
7
8
9
android {
	...

    dexOptions {
        javaMaxHeapSize "2g"
    }

    ...
}

E’ da tempo che mi chiedo come mai non esista un Google Developer Group nel Veneto. Basta dare un’occhiata alla directory dei GDG a questo link per vedere che, in Italia, il Nord-Est è abbastanza scoperto. Così, invece di attendere che su quella mappa compaia un nuovo marker più vicino alle mie zone, ho deciso di prendere contatti con Google e attivarmi per creare un GDG nella zona di Venezia-Treviso-Padova.

Perché? Per costruire una community reale di sviluppatori, designer e esperti di social media marketing con il supporto di Google! Sarà la prima community di questo tipo nel Veneto.

Cos’è un GDG (Google Developer Group)? I GDG sono gruppi di sviluppatori (ma non solo) interessati nelle tecnologie Google come Android, Chrome, Drive, Google Cloud, Cast API, Maps API, YouTube API… (ma non solo). Un GDG può attuarsi in diversi modi, da un gruppo ristretto di persone che consultano gli ultimi video tecnici, a eventi più grandi come demo, talk tecnici e hackaton. Il focus di ogni evento è comunque su contenuti tecnici e di sviluppo.

Chi può partecipare? Sviluppatori, UI/UX designer, esperti di social media marketing. Il focus è sulle tecnologie made in Google, ma questo non è un limite: sono benvenute tutte le tecnologie!

Cosa non si vuole fare: l’ennesimo evento in cui una persona parla e molte persone si annoiano.

Cosa si vuole fare: creare un punto di ritrovo sia virtuale che fisico nel quale le persone scambiano idee, materiale, informazioni e instaurano nuovi rapporti di collaborazione. Il tutto in modo informale, magari di fronte ad uno spritz o un caffè!

Vuoi saperne di più, solo per curiosità o per contribuire attivamente? Contattami tramite l’apposita sezione in questo sito o su Twitter!

Splash screens are not so popular in Android development. But wait: now Google started to put splash screens in its apps??? Take a look at Google Drive app for example. Does it mean that now we have a new standard?

This is not the right post to talk about if splash screen in Android is good or bad. Let’s think only about code: implementing a splash screen is easy.

I’ve seen many splash screen implementations, but some of them have one common bug. If I close the app (aka: press back button) when the splah screen is visibile, after a while the main screen of the app appears. WTF??? I’ve closed you, why are you coming back again?

The trick is very simple. Let’s take a look at how a very simple SplashActivity could be:

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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
public class SplashActivity extends Activity {

    private static int SPLASH_TIME_OUT = 2000; // 2 seconds

    private Handler mHandler;

    private Runnable mRunnable = new Runnable() {

        @Override
        public void run() {
            startMainActivity();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_splash);

        mHandler = new Handler();
    }

    @Override
    protected void onResume() {
        super.onResume();

        mHandler.postDelayed(mRunnable, SPLASH_TIME_OUT);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();

        removeCallbacks();
    }

    @Override
    protected void onStop() {
        super.onStop();

        removeCallbacks();
    }

    private void removeCallbacks() {
        if (mHandler != null) {
            mHandler.removeCallbacks(mRunnable);
        }
    }

    private void startMainActivity() {
        startActivity(new Intent(this, MainActivity.class));

        finish();
    }
}

This is very straightforward. The key point here is the

1
removeCallbacks
method: this is where I’m assuring that MainActivity is not started if the user have pressed back button (explicitly closing the application) or if app has gone in background.

In your AndroidManifest.xml don’t forget to declare your activity with the following attributes:

<activity
    android:name=".SplashActivity"
    android:configChanges="orientation|keyboardHidden"
    android:label="@string/application_name"
    android:noHistory="true" >
    <intent-filter>
        <action android:name="android.intent.action.MAIN"/>
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

In Java it’s common to work with listeners. And if you work with RxJava, you will prefer to use an Observable instead of listeners. But what if you have to deal with a library and you cannot change the source code?

There’s a simple way to create an Observable around a listener.

Suppose we have an interface

1
ValueUpdateListener
and an object
1
ValueUpdater
that will call our listener:

public interface ValueUpdateListener {
    
    void onValueChanged(@NonNull String value);

}

public class ValueUpdater {
    
    // in some point of the class...
    
    public void registerListener(ValueUpdateListener listener) {
        //...
    };
    
    public void unregisterListener(ValueUpdateListener listener) {
        //...
    };
}

We can create an Observable like this:

public Observable<String> observableListenerWrapper() {

    return Observable.create(new Observable.OnSubscribe<String>() {

        @Override
        public void call(Subscriber<? super String> subscriber) {
            ValueUpdateListener listener = new ValueUpdateListener() {

                @Override
                public void onValueChanged(@NonNull String value) {
                    if (subscriber.isUnsubscribed()) {
                        registerListener.unregisterListener(this);
                    } else {
                        subscriber.onNext(value);
                    }
                }
            };

            registerListener.registerListener(listener);
        }
    });
}

Now you just have to subscribe:

observableListenerWrapper().subscribe(value -> {
    // do something with the new value
});

Note that the listener will be automatically unregistered if the method

1
onValueChanged
is called and the observable is unsubscribed.

The next library you will learn should definetly be ReactiveX.

What is ReactiveX?

From the website: ReactiveX is a combination of the best ideas from the Observer pattern, the Iterator pattern, and functional programming.

(But it’s a lot more.)

The key concept to start with ReactiveX is: think reactive programming as operating on a stream of data.

Can I use ReactiveX with my favourite language?

Actually you can find a ReactiveX implementation for the following languages:

  • Java: RxJava
  • JavaScript: RxJS
  • C#: Rx.NET
  • C#(Unity): UniRx
  • Scala: RxScala
  • Clojure: RxClojure
  • C++: RxCpp
  • Ruby: Rx.rb
  • Python: RxPY
  • Groovy: RxGroovy
  • JRuby: RxJRuby
  • Kotlin: RxKotlin
  • Swift: RxSwift

Ok, but wait: why should I use ReactiveX?

Because it will make your life easier! Let me give you a couple of examples, based on Java/Android development.

Example 1: Nested API calls

Suppose that we need to call a remote API to authenticate a user, than another one to get user’s data and again another API to get user’s contacts. Tipically we would have to write nested API calls like this:

User user = null;

serviceEndpoint.login(username, password, new Callback<AccessToken>() {

    @Override
    public void success(User user, Response response) {

    	// store accessToken somewhere

        serviceEndpoint.getUser(new Callback<User>() {
            @Override
            public void success(User userResponse, Response response) {

            	user = userResponse;

                serviceEndpoint.getUserContact(user.getId(), new Callback<Contact>() {
                    @Override
                    public Contact success(Contact contact, Response response) {
                    	user.setContact(contact);
                    }

                    @Override
                    public void failure(RetrofitError error) {
                    	// handle error here...
                    }
                });
            }

            @Override
            public void failure(RetrofitError error) {
                // handle error here...
            }
        });

    }

    @Override
    public void failure(RetrofitError error) {
        // handle error here...
    }
});

Ok, maybe these APIs are not well designed, but sometimes you have to deal with it! ;-)

If we use RxJava + Retrofit (Retrofit is already compatible with RxJava), the code above will become:

 	serviceEndpoint.login()
            .doOnNext(accessToken -> storeCredentials(accessToken))
            .flatMap(accessToken -> serviceEndpoint.getUser())
            .flatMap(user -> serviceEndpoint.getUserContact(user.getId()))

Cool, right? There are actually many ways to achieve the same result using RxJava, but they’re all better than using nested calls.

Example 2: Android - forget about AsyncTasks

For Android developers, it gets even better. RxJava (and it’s extension RxAndroid) can handle all the stuff about running long tasks in a background thread and present results on the main thread. Starting from the example above, if we want to login the user and display it’s name, we can write just some lines of code:

1
2
3
4
5
6
7
8
// this code il placed inside an Activity

AppObservable.bindActivity(this,
    serviceEndpoint.login()
                .doOnNext(accessToken -> storeCredentials(accessToken))
                .flatMap(accessToken -> serviceEndpoint.getUser())
                .flatMap(user -> serviceEndpoint.getUserContact(user.getId()))
    ).subscribe(user -> mUserNameTextView.setText(user.getName()));

Ok, I know, it seems hard to understand at first. But AppObservable.bindActivity will make the network call (line 4 to 7) in a background thread, while the result will be delivered in the main thread, so we can change the view (line 8). Plus, the method is automatically binded to the activity lifecycle, so the result will not be delivered if the activity is paused.

This is super!

Good, I think I will learn it! Where should I start?

You can find many articles about ReactiveX, but only a few of them are easy to understand for a newbie.

  • I can suggest you to start from this: The introduction to Reactive Programming you’ve been missing. I’ve found it very clear and comprehensive of many aspects of reactive programming.

  • Here is a good talk about RxJava by Ivan Morgillo at droidconDE 2015. It’s focused on Android programming only in the last part. The most of the talk covers aspects of reactive programming that can be applied to all languages.

Some other references?