Development, Flutter

Paddinger: Flutter Padding widgets generator

Paddinger is a new package to help you deal with Flutter paddings and here you’ll discover how!


Have you ever been tired of writing Padding and EdgeInsets boilerplate everytime you need to add padding to a widget? I was, so I started looking for something to simplify this task. Furthermore, the necessary code to create declarative UIs can become very long and difficult to read, so, if there is a way to reduce it even by a few lines it’s something always worth to be considered.

I found out I was not the only one who was tired of this Padding boilerplate because, searching for a solution, I found someone else struggling with the same problem. One of the solution I found was Padder, which is available on Github and on It’s a cool set of widgets which can help you dealing with paddings.

Unfortunately, it was not what I was looking for, but having found valid proofs that there was a problem affecting someone else other than me, I decided to build what I needed on my own, and so Paddinger was born.

What is Paddinger?

Paddinger is a code generator for Flutter: it builds Padding widgets for you based on the values you have in your design system. An example is worth a thousand words, so here it is. Assuming you have

const double PADDING_NORMAL = 8;

with Paddinger you will obtain a set of widgets like


just by annotating with @paddinger the constants you want the widgets to be generated for, like

const double PADDING_NORMAL = 8;

Then, you can use the generated widgets like every other one. Assuming you want to give a padding of 8 to a Text, instead of writing

  padding: const EdgeInsets.all(PADDING_NORMAL),
  child: Text(

you can just write

  child: Text(

which imho is far easier to remember, to write, to read and IDE code completion will come to rescue!

How to use Paddinger in your project?

  • First of all, add Paddinger as a dependency:
  paddinger_annotations: [latestVersionHere]

  paddinger: [latestVersionHere]
  • Create a file where you will add all your PADDING_ constants, the file could be named paddings.dart.
  • Add your favourite material or cupertino import like:
// ignore: unused_import
import 'package:flutter/material.dart';
  • Add the part directive:
part 'paddings.g.dart';

Now run the code generation with flutter pub run build_runner build --delete-conflicting-outputs and your widgets will be generated and ready to be used!

You can have a look at the example in the Github repository or on

Happy Fluttering!

Android, Development, Kotlin, Test

Clear all Android SharedPreferences

It may happen you would need to clear your all of your SharedPreferences without knowing in advance their keys.


This can happen when you are writing tests: you don’t want your production code to publicly expose your SharedPreferences keys neither you need a clear() method, so you didn’t implement it. You may also need to clear third party SharedPreferences to which you don’t have direct access.

Without changing your production code there is something you can do:

  • access the app SharedPreferences folder
  • get the SharedPreferences editor for each file
  • clear the SharedPreferences

You can use the following code, called in a @BeforeEach annotated method, to be sure each of your tests will run in a clean environment.

private fun clearAllSharedPreferences(context: Context) {
    val sharedPreferencesPath = File(context.filesDir.parentFile!!.absolutePath + File.separator + "shared_prefs")
    sharedPreferencesPath.listFiles()?.forEach { file ->
        context.getSharedPreferences(file.nameWithoutExtension, Context.MODE_PRIVATE).edit { clear() }


  • Be sure to include androidx.core:core-ktx in your project to have that edit() method
  • If you are running your tests using Espresso you can access the app Context using InstrumentationRegistry.getInstrumentation().targetContext

Happy coding!

Android, Development, Java, Kotlin

How to debug an Annotation Processor in Android Studio

Writing an Annotation Processor in Java/Kotlin is a very interesting task and debugging comes very handy, but unfortunately it seems not so easy to start a debug session.

rubber ducks

The following information are valid for Android Studio 3.6.3 and Kotlin 1.3.71. Gradle is the build tool used for the project.

First thing to do is setup a new Run/Debug Configuration in Android Studio:

  • Choose Run from the main menu
  • Choose Edit Configurations
  • Now click on the + symbol in the top left corner to add a new Configuration
  • Choose Remote from the list
  • Give it a friendly name (e.g. AnnotationProcessorDebugger)

Setup your breakpoints wherever you need them and then run this command from the terminal:

./gradlew --no-daemon -Dorg.gradle.debug=true :APP_MODULE_NAME:clean :APP_MODULE_NAME:compileDebugJavaWithJavac

Replace APP_MODULE_NAME with the name of the module having annotations which you want to debug. You will see the process will start and suddenly stop on > Starting Daemon waiting for you to do something.

Now, click on the Debug icon in the Toolbar (having selected the previously created AnnotationProcessorDebugger configuration) and the debugger will hit your breakpoints!

Additional info:

The clean task seems to be necessary.

Unfortunately, sometimes these steps are not enough, or simply don’t work, the debugger won’t hit your breakpoints. I see somebody else solved the issue after adding the following line to their file.

Development, Java, Spring

Using Spring Data to persist a Set of Enums in a Many-To-Many relationship

Usually, when we write a Many-To-Many relationship it is between 2 entities. Sometimes, it could happen that we have an entity which has a field which is a set of enum. In this case, we need to approach the problem differently and Spring comes to help.

Let’s see an example where we have two classes: Person and Skill (e.g. swimming, running, etc).

Many-To-Many between entities example

The following code shows what the situation is when Person and Skill are both entities.

public class Person {
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;
  private String name;
  @ManyToMany(fetch = FetchType.LAZY)
  @JoinTable(name = "person_skill", joinColumns = {
            @JoinColumn(name = "person_id")}, inverseJoinColumns = {
            @JoinColumn(name = "skill_id")})
  private Set<Skill> skillSet;

public class Skill {
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;
  private String name;

To use this mapping, you would have 3 tables. You can create them with the following SQL code.

CREATE TABLE `person` (
  `name` VARCHAR(45) NOT NULL,
  PRIMARY KEY (`id`));

CREATE TABLE `skill` (
  `name` VARCHAR(45) NOT NULL,
  PRIMARY KEY (`id`));

CREATE TABLE `person_skill` (
  `person_id` BIGINT(20) NOT NULL,
  `skill_id` BIGINT(20) NOT NULL,
  PRIMARY KEY (`person_id`, `skill_id`),
  INDEX `skill_fk_idx` (`skill_id` ASC),
  CONSTRAINT `person_fk`
    FOREIGN KEY (`person_id`)
    REFERENCES `person` (`id`)
  CONSTRAINT `skill_fk`
    FOREIGN KEY (`skill_id`)
    REFERENCES `skill` (`id`)

Many-To-Many between entity and enum example

The following code shows what the situation is when Person is an entity and Skill is an enum.

public class Person { 
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id; 
  private String name; 
  @ElementCollection(targetClass = Skill.class)
  @CollectionTable(name = "person_skill",
            joinColumns = @JoinColumn(name = "person_id"))
  @Column(name = "skill_name")
  private Set<Skill> skillSet;

public enum Skill {

To use this mapping, you would have only 2 tables, because Skill is not an entity and would not have its own table. You can create them with the following SQL code.

CREATE TABLE `person` (
  `name` VARCHAR(45) NOT NULL,
  PRIMARY KEY (`id`));

CREATE TABLE `person_skill` (
  `person_id` BIGINT(20) NOT NULL,
  `skill_name` VARCHAR(45) NOT NULL,
  PRIMARY KEY (`person_id`, `skill_name`),
  CONSTRAINT `person_fk`
    FOREIGN KEY (`person_id`)
    REFERENCES `person` (`id`)

As you can see here, you don’t have the table skill because Skill is not an entity but only an enum; you only have to create the table which represents the relationship between Person and Skill. Furthermore, since we added the annotation @Enumerated(EnumType.STRING) Spring Data will save the name of the entity in the database (look, we put a VARCHAR column). If you prefer, you could use EnumType.ORDINAL and Spring Data will save the ordinal value of the entity (1,2,3,etc..), so change the column to accept a numeric value.

That’s it!

Android, Development

Android Contextual Action Bar

In this post you will learn how to implement a Contextual Action Bar (CAB) which will be useful to do actions on multiple items you have selected in a RecyclerView.

The Contextual Action Mode represents a contextual mode of the user interface and focuses user interaction toward performing contextual actions. In the case of a RecyclerView which shows a list of item, Contextual Action Mode is triggered after a long press on one of this items: this causes the Contextual Action Bar to appear at the top of the screen so then the user can interact with its actions.

Let’s follow these steps!

Initial setup

First of all, create a RecyclerView and its adapter in the usual way you do it. Here in this example I will use a RecyclerView which shows Authentication items (it is a class I made for a project, it doesn’t matter for the purpose of the example, use whatever you want, and change the names accordingly).

Theme changes

Open your styles.xml file and add the following lines:

<!--  It should be true otherwise action mode will not overlay toolbar -->
       <item name="windowActionModeOverlay">true</item>
       <!--  For Custom Action Mode Background Color/Drawable -->
       <item name="actionModeBackground">@color/colorAccent</item>

Comments should be self-explanatory.

Menu file

We need a menu file which contains the available actions for that RecyclerView. Let’s create a file into the res/menu directory like the following:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android=""

        app:showAsAction="always" />


We added a delete action that will be shown on the CAB.

Adapter changes

Our adapter we created in the first step needs to be able to keep trace of the elements we select. To do this, let’s modify our adapter and create a new field

private final SparseBooleanArray selectedItemsIds;

and initialize it in our constructor

selectedItemsIds = new SparseBooleanArray();

Now, let’s create an Interface which will be useful for all the Adapters which need the CAB, and make our Adapter implements it. Please note this is a generic interface, so adapt it to the model you are displaying in your adapter.

public interface ActionModeAdapterCallbacks<T> {

    void toggleSelection(int position);

    void clearSelections();

    int getSelectedCount();

    List<T> getSelectedItems();

This is what the implementation should look like:

public void toggleSelection(final int position) {
    if (selectedItemsIds.get(position)) {
    } else {
        selectedItemsIds.put(position, true);

public void clearSelections() {

public int getSelectedCount() {
    return selectedItemsIds.size();

public List<Authentication> getSelectedItems() {
    final List<Authentication> selectedItemList = new LinkedList<>();
    for (int i = 0; i < selectedItemsIds.size(); i++) {
    return selectedItemList;

Now, we also need the Adapter to change the view state when an item gets selected to show the user a visual feedback. To do this we can use a StateListDrawable and in the onBindViewHolder() method add this line.


Create a new xml file inside the res/drawable directory:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="">
    <item android:drawable="@color/colorPrimaryDark" android:state_activated="true" />
    <item android:drawable="@android:color/transparent" />

and assign it to the root view element of the layout file which represents your adapter’s row item:


Doing so, each time an item is selected or deselected, the adapter will change its color accordingly.

Fragment/Activity changes

Now, we need to make our Fragment/Activity class aware that we can trigger the Contextual Action Mode. To do so, let’s create an interface and call it ActionModeViewCallbacks.

public interface ActionModeViewCallbacks {

    void onListItemSelect(final int position);

    void onDestroyActionMode();


This interface has 2 methods:

  • onListItemSelect(final int position): to be used after a long click on an item to trigger the Action Mode (or after a single click on an item, if Action Mode was already triggered, to select this new item, too);
  • onDestroyActionMode(): reset actionMode variable to null;

Now, let’s create another interface which extends from this one:

public interface ListAuthenticationActionModeViewCallbacks extends ActionModeViewCallbacks {

    void onDeleteActionClicked();


This new interface has another method, onDeleteActionClicked(), which is where the presenter gets called (check MVP if you are not aware what MVP and a Presenter are) and asked to delete the items the user has selected (if you have more than a single action, you need to create more methods, each for any action you have).

This interface must be implemented by the Fragment/Activity which wants to use the Contextual Action Mode. The implementation looks like this:

    public void onListItemSelect(final int position) {

        final boolean hasCheckedItems = listAuthenticationAdapter.getSelectedCount() > 0;

        if (hasCheckedItems && actionMode == null) {
            // there are some selected items, start the actionMode
            actionMode = ((AppCompatActivity) getActivity()).startSupportActionMode(new ListAuthenticationToolbarActionModeCallback(this, this, listAuthenticationAdapter));
        } else if (!hasCheckedItems && actionMode != null) {
            // there no selected items, finish the actionMode

       if (actionMode != null) {
            //set action mode title on item selection
            actionMode.setTitle(getString(R.string.cab_selected, listAuthenticationAdapter.getSelectedCount()));

    public void onDestroyActionMode() 
        actionMode = null;

public void onDeleteActionClicked() {

where R.string.cab_selected is

<string name="cab_selected">%1$d selected</string>

In doing startSupportActionMode() we need to pass a ActionMode.Callback item that I haven’t explained yet. Let’s create another class which implements that interface.

public class ListAuthenticationToolbarActionModeCallback implements ActionMode.Callback {

    private final ActionModeViewCallbacks actionModeViewCallbacks;
    private final ListAuthenticationAdapter listAuthenticationAdapter;

    public ListAuthenticationToolbarActionModeCallback(final ActionModeViewCallbacks actionModeViewCallbacks, final ListAuthenticationAdapter listAuthenticationAdapter) {
        this.actionModeViewCallbacks = actionModeViewCallbacks;
        this.listAuthenticationAdapter = listAuthenticationAdapter;

    public boolean onCreateActionMode(final ActionMode mode, final Menu menu) {
        mode.getMenuInflater().inflate(, menu);
        return true;

    public boolean onPrepareActionMode(final ActionMode mode, final Menu menu) {
        return true;

    public boolean onActionItemClicked(final ActionMode mode, final MenuItem item) {
        switch (item.getItemId()) {
                return true;
        return false;

    public void onDestroyActionMode(final ActionMode mode) {

Please have a look on the official documentation here to understand how ActionMode.Callback works.


See the following screenshots:

  • first one shows the initial situation before Action Mode is triggered;
  • second one shows the situation after Action Mode was triggered by long press an item;
  • third one shows the final situation after the item “Auth 2” was deleted.

contextual action bar first contextual action bar selected contextual action bar after delete


Your Contextual Action Mode should work now! I suggest you to create different menu files, Fragment/ActivityToolbarActionModeCallback and Fragment/ActivityActionModeViewCallbacks to keep everything separated.

Please note: if you rotate the device, Contextual Action Mode is lost, you need to save its state and restore it. Another post will follow, hopefully soon!

Development, Java

Java concurrency: a few examples

Sometimes we write very high level code, sometimes we don’t. I want to put here a link to a simple project which shows how to deal with concurrency in Java with a few examples.

The project is available on Github here

Goal of the project is to retrieve the details and the balance of a player and show them at the same time: until you have collected both of them you have to wait before showing the user the information.

There are two different packages: in the first, Futures and Callables are being used, in the other, Threads/Runnables and a CountDownLatch are.

Futures and Callables are the best option when you need to run a task which has a return value. I also made it in a different way using Threads/Runnables, a CountDownLatch and some listeners but these classes are usually used when you have tasks which won’t return any value.

Use the two Main classes to run the examples. Have fun!

Android, Development

Android NoteApp with Dagger and Retrofit

Today I show a simple Android project I wrote which shows the use of Dagger, Retrofit and some other stuff.

The full source code of the project is available for you here

The project’s main purposes are the following:

  • Show Dagger2 dependency injection;
  • Show MVP architecture (made through Dagger2)
  • Show the repository pattern used to cache server data
  • Show the creation and use of a CustomView

Furthermore, I have used ButterKnife to remove the boilerplate code needed to bind classes/views, and GreenDao to automatically create the SQLite repository/model classes.

This project is based on the Google Android Architecture samples which are available here


ApplicationContextException using SpringBoot with Gradle and IntelliJ IDEA

In my spare time I decided to have a better look to SpringBoot and in doing so I decided to leave back Maven and Eclipse and to move to Gradle and IntelliJ, which I already use to develop Android applications.

During the first phase of my development I encountered a strange issue: it seems that IntelliJ IDEA will add wrong dependencies to your SpringBoot project which will cause it to crash at runtime.

This was the exception thrown and the full stack trace:

org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
	at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh( ~[spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
	at ~[spring-context-4.2.5.RELEASE.jar:4.2.5.RELEASE]
	at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh( ~[spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
	at org.springframework.boot.SpringApplication.refresh( [spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
	at org.springframework.boot.SpringApplication.createAndRefreshContext( [spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
	at [spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
	at [spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
	at [spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
	at com.sampleapp.SampleAppApplication.main( [main/:na]
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_72]
	at sun.reflect.NativeMethodAccessorImpl.invoke( ~[na:1.8.0_72]
	at sun.reflect.DelegatingMethodAccessorImpl.invoke( ~[na:1.8.0_72]
	at java.lang.reflect.Method.invoke( ~[na:1.8.0_72]
	at com.intellij.rt.execution.application.AppMain.main( [idea_rt.jar:na]
Caused by: org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
	at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.getEmbeddedServletContainerFactory( ~[spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
	at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.createEmbeddedServletContainer( ~[spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
	at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh( ~[spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
	... 13 common frames omitted

This stacktrace is related to SpringBoot v1.3.3 but I experienced the same issue even with SpringBoot v1.4.0.

In the end I found that IntelliJ was putting this line in the build.gradle file:


After removing that line, the project ran without issues.
So if you are experiencing an ApplicationContextException and you couldn’t find its cause, try to have a look at your build.gradle file.