Android

Integrating ErrorProne and NullAway with an Android project

2017-09-15 Android, Gradle, Java, Static Code Analysis No comments

Recently, with the remote help of guys from Uber in California, I integrated NullAway and ErrorProne with the one of my open-source Android projects.

What is NullAway?

Basically, it’s a tool to help eliminate NullPointerExceptions (NPEs) in your Java code. It detects situations where NPE could occur at the compile time.

Let’s have a look at the following code:

static void log(Object x) {
    System.out.println(x.toString());
}
static void foo() {
    log(null);
}

NullAway will find out that we’re passing null and we’ll get appropriate error message:

warning: [NullAway] passing @Nullable parameter 'null' where @NonNull is required
    log(null);
        ^

It’s good to have checks like that because they eliminate possible bugs in advance and follows Clean Code principles.

A few words about ErrorProne

NullAway is built as a plugin to ErrorProne and can run on every single build of our code. Moreover, ErrorProne can perform other checks on our code, which can find out commonly people mistakes. E.g. it can detect a situation, where programmer forgot to add @Test annotation in the unit test method in a test suite and other things. It has built-in bug patterns, which are used during code analysis.

Integration with the Android project

I’ve integrated ErrorProne and NullAway with ReactiveNetwork Android library.

First, in the main build.gradle file, I’ve added the following lines:

ext.deps = [
            ...
            nullaway          : 'com.uber.nullaway:nullaway:0.1.2',
            errorprone        : 'com.google.errorprone:error_prone_core:2.1.1',
            ...
            ]

buildscript {
  repositories {
    jcenter()
    maven {
      url 'https://plugins.gradle.org/m2/'
    }
  }
  dependencies {
    ...
    classpath 'net.ltgt.gradle:gradle-errorprone-plugin:0.0.11'
    classpath 'net.ltgt.gradle:gradle-apt-plugin:0.11'
    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
  }
}

Next, in the library/build.gradle file, I’ve added appropriate plugins in the top:

apply plugin: 'net.ltgt.errorprone'
apply plugin: 'net.ltgt.apt'

Afterwards, I could add dependencies:

dependencies {
  ...

  annotationProcessor deps.nullaway
  errorprone deps.errorprone
}

The last thing to do, is the task responsible for running analysis during project compilation:

tasks.withType(JavaCompile) {
  if (!name.toLowerCase().contains("test")) {
    options.compilerArgs += ["-Xep:NullAway:ERROR", "-XepOpt:NullAway:AnnotatedPackages=com.github.pwittchen.reactivenetwork"]
  }
}

That’s it! Now, I could run analysis by typing:

./gradlew check

and fix the issues.

I think, a quite similar approach and configuration could be applied to a regular, pure Java project built with Gradle.

If you’re interested in the complete configurations, check it out in my project at: https://github.com/pwittchen/ReactiveNetwork.
You can also view Pull Request #226 made by @msridhar (kudos for him!).

Introducing ReactiveAirplaneMode

2017-08-15 Android, Open source, RxJava No comments

I’m continuing Rxfication of the Android. Recently I released brand new library called ReactiveAirplaneMode. As you may guess, it allows listening Airplane mode on Android device with RxJava observables. A usual I’ve hidden all implementation details, BroadcastReceivers and rest of the Android related stuff behind RxJava abstraction layer, so API is really simple. Just take a look on that:

ReactiveAirplaneMode.create()
    .observe(context)
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(isOn -> textView.setText(String.format("Airplane mode on: %s", isOn.toString())));

In the code above subscriber will be notified only when airplane mode changes.

If you want to read airplane mode and then listen to it, you can use the following method:

ReactiveAirplaneMode.create()
    .getAndObserve(context)
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(isOn -> textView.setText(String.format("Airplane mode on: %s", isOn.toString())));

If you want to check airplane mode only once, you can use get(context) method, which returns Single<Boolean> value:

ReactiveAirplaneMode.create()
    .get(context)
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(isOn -> textView.setText(String.format("Airplane mode on: %s", isOn.toString())));

If you want to check airplane mode only once without using Reactive Streams, just call isAirplaneModeOn(context) method:

boolean isOn = ReactiveAirplaneMode.create().isAirplaneModeOn(context);

You can add this library to your project via Gradle:

dependencies {
  compile 'com.github.pwittchen:reactiveairplanemode:0.0.1'
}

If you want to know more details, see sample app, documentation & tests, check repository with the source code at: https://github.com/pwittchen/ReactiveAirplaneMode.

Releasing ReactiveNetwork v. 0.11.0 with Walled Garden AKA Great Firewall support

2017-08-06 Android, Java, Open source No comments

In the latest release of ReactiveNetwork library, I focused on Walled Garden AKA Great Firewall support during checking Internet connectivity. There are countries with limited Internet access like China and in such cases, pinging commonly known host like www.google.com may have different results than in other countries because it may be blocked. We may get false positive results because users will generally have an access to the Internet, but they don’t have access only to several websites. To solve that problem, I created WalledGardenInternetObservingStrategy and made it default strategy for checking Internet connectivity inside the library. Of course, you can still use SocketInternetObservingStrategy if you want to.

Detailed release notes are as follows:

RxJava1.x

  • added WalledGardenInternetObservingStrategy – fixes #116
  • made WalledGardenInternetObservingStrategy a default strategy for checking Internet connectivity
  • added documentation for NetworkObservingStrategy – solves #197
  • added documentation for InternetObservingStrategy – solves #198
  • bumped Kotlin version to 1.1.3-2
  • bumped Gradle Android Tools version to 2.3.3
  • bumped Retrolambda to 3.7.0

RxJava2.x

  • added WalledGardenInternetObservingStrategy – fixes #116
  • made WalledGardenInternetObservingStrategy a default strategy for checking Internet connectivity
  • added documentation for NetworkObservingStrategy – solves #197
  • added documentation for InternetObservingStrategy – solves #198
  • fixed package name in AndroidManifest.xml file – solves #195
  • bumped RxJava2 version to 2.1.2
  • bumped Kotlin version to 1.1.3-2
  • bumped Gradle Android Tools version to 2.3.3
  • bumped Retrolambda to 3.7.0
  • increased code coverage with unit tests

Repository address: https://github.com/pwittchen/ReactiveNetwork.

Happy coding!

Releasing ReactiveNetwork v. 0.10.0

2017-07-20 Android, Open source, RxJava No comments

I’ve recently released ReactiveNetwork library v. 0.10.0 for RxJava1.x and RxJava2.x.
ReactiveNetwork is an Android library listening network connection state and Internet connectivity with RxJava Observables, which I’m developing for approximately 2 years now.

In this version, I’ve done a few bug fixes and added new features for RxJava2.x version.

Below, you can find the release notes:

Release for RxJava1.x

  • bumped RxJava1 version to 1.3.0
  • bumped test dependencies
  • created Code of Conduct
  • updated Kotlin version in sample apps
  • added retrolambda to the sample Java app – issue #163
  • fixed behavior of network observing in disconnected state – issue #159

Release for RxJava2.x

  • bumped RxJava2 version to 2.1.1
  • bumped test dependencies
  • created Code of Conduct
  • updated unit tests
  • updated Kotlin version in sample apps
  • added retrolambda to the sample Java app – issue #163
  • fixed behavior of network observing in disconnected state – issue #159
  • added the following methods to ReactiveNetwork class:
    • Single<Boolean> checkInternetConnectivity()
    • Single<Boolean> checkInternetConnectivity(InternetObservingStrategy strategy)
    • Single<Boolean> checkInternetConnectivity(String host, int port, int timeoutInMs)
    • Single<Boolean> checkInternetConnectivity(String host, int port,
      int timeoutInMs, ErrorHandler errorHandler)
    • Single<Boolean> checkInternetConnectivity(InternetObservingStrategy strategy,
      String host, int port, int timeoutInMs,
      ErrorHandler errorHandler)

You can add it to your project via Gradle:

RxJava1.x:

dependencies {
  compile 'com.github.pwittchen:reactivenetwork:0.10.0'
}

RxJava2.x:

dependencies {
  compile 'com.github.pwittchen:reactivenetwork-rx2:0.10.0'
}

Now, in RxJava2.x version, we have the possibility to check Internet connectivity once without any pooling with new Single type. It may be helpful in the specific use-cases when we’re focusing on smaller battery usage, a smaller amount of data being sent over the network and lower number of network connections.

I’m planning to publish more real life usage examples of this library in the future articles on this blog.

I have plans for a few updates in the next version. If you’re interested in this project or you’re using it, please stay tuned and keep an eye on it at GitHub.

Release of prefser v. 2.1.0 with RxJava2 support

2017-06-19 Android, Java, Open source, RxJava 2 comments

I’ve recently released new version of prefser library for Android. In case you don’t know, it’s a wrapper for Android SharedPreferences with object serialization and RxJava Observables. This version has the new artifact, which has codebase migrated to RxJava2.x. As usual, I kept backward compatibility with RxJava1.x.

You can find more details about the project at https://github.com/pwittchen/prefser.

If you want to use it in your mobile project, you need the following dependencies in the build.gradle file:

dependencies {
  compile 'com.github.pwittchen:prefser-rx2:2.1.0'
  compile 'io.reactivex:rxandroid:2.0.1'
}

Short release notes can be found at https://github.com/pwittchen/prefser/releases.

This update was requested by at least two developers on GitHub and it’s my second most popular project, so I hope you’ll find it useful if you’re in the process of migrating from RxJava1.x to RxJava2.x. I still have 4 remaining RxJava1.x libraries waiting for the upgrade. If you want to perform any updates via Pull Requests, you’re more than welcome.

Releasing Prefser v. 2.0.7

2017-05-28 Android, DSP2017, Java, Open source No comments

I’ve recently released new version of Prefser. It’s a wrapper for Android SharedPreferences with object serialization and RxJava Observables.
The new version number is 2.0.7.

In this release, I performed mostly internal work not related to the external library API. Nevertheless, it’s important for the library development in the future.

The following things were done:

  • updated dependencies
  • updated Gradle configuration
  • migrated unit tests to Robolectric
  • started executing unit tests on Travis CI
  • added integration with codecov.io and coverage report
  • extracted code related to accessors from the Prefser class (refactoring library internals)

Organizational work is done and now I’m ready for migration to RxJava2 in this project on a separate branch. I want to keep backward compatibility with RxJava1 as in my other projects. This update is planned for version 2.1.0.

Stay tuned!

ReactiveNetwork – release v. 0.9.0 with RxJava2.x support

2017-04-11 Android, DSP2017, Java, Open source, RxJava No comments

This time, I upgraded my another reactive Android open-source project called ReactiveNetwork to RxJava2.x. Many thanks goes to @tushar-acharya who performed initial migration to the newer version of RxJava. During migration, I’ve also created new package rx2 to avoid potential import conflicts during migration inside Android apps. Besides migration, I’ve updated sample apps, documentation & JavaDocs on Github pages. You can still use RxJava1.x version and it’s available on the branch with that name.

To use brand new ReactiveNetwork compatible with RxJava2.x, add the following dependency to your build.gradle file:

dependencies {
  compile 'com.github.pwittchen:reactivenetwork-rx2:0.9.0'
}

If you still want or need to use RxJava1.x, use the following dependency:

dependencies {
  compile 'com.github.pwittchen:reactivenetwork:0.9.0'
}

New updates and bug-fixes are on the way. Right now I have a few issues in the project backlog.

Feel free to contribute to this project and report new issues! Any constructive feedback will be appreciated.

ReactiveBeacons – release of v. 0.6.0 with support for RxJava2

2017-04-03 Android, Bluetooth Low Energy, DSP2017, Java, Open source, RxJava No comments

Thanks to @BugsBunnyBR I released new version of ReactiveBeacons library with the RxJava2.x support. It’s an Android library scanning BLE (Bluetooth Low Energy) beacons nearby with RxJava Observables. I also kept backward compatibility with RxJava1.x. Different versions of the libraries are located on the separate git branches. It’s a similar approach to original RxJava project. I have separate builds on Travis CI, separate artifacts and JavaDocs. Such approach generates more overhead, but in such case, RxJava1.x can be kept in a maintenance mode and RxJava2.x can be a subject of the future development.

What has been done in this version?

  • migrated library to RxJava2.x on RxJava2.x branch and released it as reactivebeacons-rx2 artifact
  • kept library compatible with RxJava1.x on a RxJava1.x branch and released it as reactivebeacons artifact
  • removed master branch
  • bumped library dependencies
  • added permission annotations
  • organized Gradle configuration
  • transformed instrumentation unit tests to pure java unit tests
  • started executing unit tests on Travis CI server
  • created separate JavaDoc for RxJava1.x and RxJava2.x

If you want to add RxJava2.x version to your Android project, add the following dependency to build.gradle file:

dependencies {
  compile 'com.github.pwittchen:reactivebeacons-rx2:0.6.0'
}

For RxJava1.x you can use old artifact id:

dependencies {
  compile 'com.github.pwittchen:reactivebeacons:0.6.0'
}

This library was one of the first experiments with my migrations to RxJava2.x. I have plans to migrate rest of my libraries soon.
Thanks to the awesome open-source community on GitHub, this process goes faster and I don’t have to do everything by myself.

Handling different Android versions with strategy pattern

2017-03-26 Android, DSP2017, Software Design Patterns No comments

When we’re developing Android apps, we have to remember that different users have different versions of the Android OS. Unfortunately, not all of them has the newest version of the system and some of them have older devices with older systems. Some of these devices may be even unsupported because e.g. Google supports their devices like Nexus and Pixel for only 2 years. When we want to reach as many users as possible and make the app available for almost everyone, we have to handle different Android versions. One of the solutions for that problem is strategy design pattern (it’s also called Policy in Domain-Driven Design).

I’m developing an Android open-source library called ReactiveNetwork, which is used for monitoring connectivity with the network in the system. Network monitoring strategies vary between different versions of Android and I wanted to choose an appropriate strategy for appropriate Android version. To do so, I’ve created NetworkObservingStrategy interface:

public interface NetworkObservingStrategy {
  Observable observeNetworkConnectivity(final Context context);
  void onError(final String message, final Exception exception);
}

This interface can have many implementations like LollipopNetworkObservingStrategy, PreLollipopNetworkObservingStrategy and MarshmallowNetworkObservingStrategy. Morever, more implementations can be added in the future.

After that, we can choose a valid strategy for the concrete version of the system:

public static Observable<Connectivity> observeNetworkConnectivity(final Context context) {
  final NetworkObservingStrategy strategy;

  if (Preconditions.isAtLeastAndroidMarshmallow()) {
    strategy = new MarshmallowNetworkObservingStrategy();
  } else if (Preconditions.isAtLeastAndroidLollipop()) {
    strategy = new LollipopNetworkObservingStrategy();
  } else {
    strategy = new PreLollipopNetworkObservingStrategy();
  }

  return strategy.observeNetworkConnectivity(context);
}

That’s it. Now, we have the separate code working for Android M, L and all devices with system version lower than L.
This approach can also be applied to other areas.

Android design inspirations

2017-03-19 Android, Design, DSP2017 No comments

When we are planning to create our next Android app, besides the codebase, it’s also good to plan its design, UI, and UX. Before doing that, we can take a look at some inspirations and work of other people to gather a few UI design patterns, inspirations, and ideas.
Good resource of such inspirations is Android Niceties website. As the authors write, this website is
a collection of screenshots encompassing some of the most beautiful looking Android apps.

You can also take a look at https://pl.pinterest.com/explore/android-ui/.

Do you know any other similar resources? Share them in comments :-).