Refresh data in a custom Android Adapter

An Adapter is an object that provides data to certain components like a ListView object or a Spinner object. There are distinct classes that implement the Adapter class, such as ArrayAdapter, which loads an array of objects. We can create a custom adapter that extends the ArrayAdapter class to create custom items.
Let’s say that we want to display Event objects in a ListView. This is our custom adapter:

public class MyCustomAdapter extends ArrayAdapter<MyEvent> {
    private final Context context;
    private List<MyEvent> events;

    public MyCustomAdapter(Context context, int layoutResourceId, List<MyEvent> events) {
        super(context, layoutResourceId, data);
        this.context = context; = events;

    public View getView(int position, View convertView, ViewGroup parent) {
        // Custom view

In the constructor method, the adapter saves the list of objects that will be displayed in the view. If we want to refresh/change this data after creating the adapter, add a new method to the adapter:

public void refreshEvents(List<MyEvent> events) {;;

This refresh method clears all the data from the list and updates it with new data. Alternatively you can create different methods to add or remove items. In any case, the most important part is to invoke the notifyDataSetChanged method. The notifyDataSetChanged method notifies the attached observers that the underlying data has been changed and any View reflecting the data set should refresh itself.

Finally, from the activity or fragment that contains the list, invoke the previous method with the new data:


Consider the case in which the refresh method is not called from the UI thread. For example, if the data is updated after a server request:

getActivity().runOnUiThread(new Runnable() {
    public void run() {

Read More

Custom color in Action Bar + Drawer

A navigation drawer is a common structure for the top-level of our Android app. A drawer provides a safe start point of return with which users can easily understand the application structure.

Using Android Studio, we can create a project from the template of an activity with a navigation drawer:

Create navigation drawer activity

A navigation drawer can be opened by a button placed in the top action bar or by swipe gestures. The default action bar for the drawer contains the icon button that opens/closes it, which is known as the toggle button. The action bar, the title and the button have their own default colors.

Default Action Bar

To change the default action bar with our custom colors, we need to change the styles xml file of our app, which initially only contains the base app theme:

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">

Under the style of our custom app theme, we need to add an item for the action bar and an item for the drawer toggle icon (arrow):

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="android:actionBarStyle">@style/MyActionBar</item>
    <item name="drawerArrowStyle">@style/MyDrawerArrowToggle</item>

    <!-- Support library compatibility -->
    <item name="actionBarStyle">@style/MyActionBar</item>

We also need to add the new colors that we are going to use. These color tags are placed outside the style tag.

<color name="background">#ff82B548</color>
<color name="foreground">@android:color/white</color>

Let’s define each one of these items. Firstly, the custom color for the toggle button:

<style name="MyDrawerArrowToggle" parent="Widget.AppCompat.DrawerArrowToggle">
    <item name="color">@color/foreground</item>

Secondly, the custom background color of the action bar and also the title text style:

<style name="MyActionBar" parent="@style/Widget.AppCompat.ActionBar">
    <item name="android:titleTextStyle">@style/MyTitleTextStyle</item>
    <item name="android:background">@color/background</item>

    <!-- Support library compatibility -->
    <item name="titleTextStyle">@style/TitleTextStyle</item>
    <item name="background">@color/background</item>

Finally, the title text style is defined as follows:

<style name="MyTitleTextStyle" parent="@style/TextAppearance.AppCompat.Widget.ActionBar.Title">
    <item name="android:textColor">@color/foreground</item>

And here it is the result:

Custom Action Bar

Read More

Android Studio Essentials

Android Studio Essentials is my third book that has been recently published by Packt Publishing here. You can get it also from Amazon here. This book is an update of my previous book “Android Studio Application Development”.

Android Studio Essentials coverAndroid Studio Essentials back

Android Studio is an IDE that is based on the JetBrains IntelliJ IDEA. It gives developers a unique platform to develop and debug Android apps using various developer tools. It has a wide array of features such as live layout facility, Gradle build support, and template-based wizards, which makes it a preferred choice for developers.

Starting off with the basic installation and configuration of Android Studio, this book aids you in building a new project by helping you to create a custom launcher icon and guiding you to choose your activity. You then gain an insight on the additional tools provided in Android Studio, namely the Software Development Kit (SDK) Manager, Android Virtual Device (AVD) Manager, and Javadoc.

Finally, it helps you to familiarize yourself with the Help section in Android Studio that enables you to search for the help you might require in different scenarios.

Read More

Giveaway Winners: Free copy of new book on Android Studio

The giveaway that was published here has ended. The winners were generated automatically and they will be contacted to let them know about it.

Angel (entry #53)
Paul (entry #106)
Victor (entry #41)

I used an external tool, PromoSimple ( to register the entrants and their number of entries. The following screenshot shows the Manage Winners page in which you can generate a winner for each prize.

Manage winners

To generate a random number, you can use the external site of or the PromoSimple generator.

Generate winners randomly

Thanks to everyone who participated and shared it!

You can still buy it at several sites:

Testing and Securing Android Studio Applications cover

Read More

Win Free copy of new book on Android Studio

Readers would be pleased to know that I have teamed up with Packt Publishing  to organize a Giveaway of my book “Testing and Securing Android Studio Applications

Three lucky winners stand a chance to win e-copy of the book. Keep reading to find out how you can be one of the Lucky Ones.

Testing and Securing Android Studio Applications cover


  • Explore the foundations of security and learn how to apply these measures to create secure applications using Android Studio
  • Create effective test cases, unit tests, and functional tests to ensure your Android applications function correctly
  • Optimize the performance of your app by debugging and using high-quality code

How to Enter?

All you need to do is write your e-mail and name below. It’s that simple. Winners will be contacted by email, so be sure to use your real email address when you comment!

In the second step, you can get extra entries if:

  • You head on over to the book page (Testing and Securing Android Studio Applications) and look through the product description of the book and drop a line via the comments after sending your email, to let us know what interests you the most about this book.
  • You tweet about this giveaway.
  • You follow me on twitter.

Winners will get an e-copy of the Book.

Read More

Testing and Securing Android Studio Applications

Testing and Securing Android Studio Applications is my second book that has been recently published by Packt Publishing here. You can get it also from Amazon here.

Testing and Securing Android Studio Applications coverTesting and Securing Android Studio Applications cover

Today, mobile applications are increasingly being used to access the Web. Mobile developers play a key role in how consumers access the Web with millions of people depending on them to create secure and functional applications. This book, beginning with the fundamentals of Android security, will guide you through the process of creating a secure and debugged application. We will look at the Android Studio development environment and take you through the steps needed to protect your local data and secure your network communications.

Initially covering the threats, risks, and vulnerabilities in software and in the Android environment, this book will then dig deeper, exploring different types of authentication methods that can be adopted in your Android application. You will be introduced to techniques and classes to test your application, before finally learning about supporting tools that will help you to improve your application.

By the end of this book, your Android application will be debugged and secure and you will be able to apply what you’ve learned to further application projects.

Read More

Test project setup in Android Studio – Updated

Android Studio IDE is gradually improving. One of these improvements is the management of tests cases in the Android projects. In this old post: Test project setup in Android Studio, I explained how to prepare your Android project to run test cases.
In the last versions of Android Studio, v0.8 and above, this process has been simplified. When a new project is created, a test package is automatically added. Tests will be saved in this package under the folder: /src/androidTest/java/<your_package>. Notice that the classes under test and the test classes are in the same package.
The project structure now looks like:
Project structure
Add your test classes in the test folder. To execute them, click on the package using the right mouse button and select the Run ‘Tests in <your_package>’ command. You can also run only one test class if you directly select it instead of the whole package.
Run Tests

Read More

Seguridad y Privacidad en Carpetas Personales de Salud para Android e iOS

For my PhD I write scientific articles that are submitted to scientific journals or conferences. The objective is to get them accepted and published. Currently we have 3 papers accepted. One of them has recently been published, the only article written in Spanish. The journal is Iberian Journal of Information and Technologies.

The RISTI (Iberian Journal of Information Systems and Technologies) is a peer-reviewed scientific journal, published by Academy Publisher in association with AISTI (Iberian Association of Systems and Information Technology), which focuses the research and the innovative practical application in the field of information systems and technologies. It is a biannual journal that publishes original and innovative articles accepted in an evaluation process by, at least, three members of the Scientific Council.

The journal is published in electronic and print version. The electronic version is free access and here is the reference (APA style) and the link to my article:

Zapata, B., Niñirola, A., Fernández-Alemán, J., & Toval, A. (2014). Seguridad y Privacidad en Carpetas Personales de Salud para Android e iOS. Iberian Journal Of Information Systems And Technologies, 0(13), 35-50. doi:10.4304/risti.13.35-50

RISTI nº 13

The abstract of the article:

Durante los últimos años, el uso de dispositivos móviles como teléfonos inteligentes y tabletas ha suscitado gran interés entre los proveedores de servicios de salud en el mundo de la mSalud. Las Carpetas Personales de Salud (en inglés Personal Health Record o PHR) móviles proporcionan numerosas ventajas y aunque hay estudios que indican que los pacientes están dispuestos a utilizarlos, los índices de uso son aún bajos. La seguridad y la privacidad han sido identificadas como una importante barrera para lograr su amplia adopción. Haciendo uso de un método adaptado de la revisión sistemática de literatura se identificaron 24 PHRs móviles para Android e iOS. La seguridad y privacidad de estos PHRs móviles fueron evaluadas usando un cuestionario de 12 preguntas. Nuestra investigación muestra que los desarrolladores de PHRs móviles han de mejorar sustancialmente sus políticas de privacidad.


Read More

Test project setup in Android Studio

Android Studio supports testing for activities natively. Let’s see how you can set up your test environment:

  1. Open Android Studio and the Android project under test. You can create a blank project with a main activity and layout.
  2. Create the package where the tests will be saved. You can create the test package in the source folder: /src/main/java/<your_package>.tests.
  3. Create the running configuration for testing. Open the top menu Run and execute the Edit Configurations option. On the left side of the window, the list of running configurations is shown. You should at least have the running configuration for your Android Application. Click on the add button and select the Android Tests type:
    Android Tests Configuration
  4. Configure the package for testing. Select the recently created running configuration so you can edit it on the right side of the window. Do the following modifications:
    1. Write a name, for example My Tests.
    2. Select your app in the Module list.
    3. Check the All in package option to establish the whole package for testing.
    4. Select your test package in the Package input text.
    5. Check the Show chooser dialog option so later you can select the emulator or a real device connected via USB. If you prefer using always the USB device, change this option, as you like.
    6. Click on the OK button to save the changes and close the window.

    Test configuration

  5. Verify that the running configuration is available in the toolbar of Android Studio as is shown in the following screenshot.
    Configuration check

Read More

First look at Genymotion Android emulator

Genymotion is an Android emulator, according to them, the faster Android emulator. Genymotion creates a virtual image of Android and it is available for Windows, Linux and Mac OS X.

  1. Download and install Oracle VirtualBox. This is necessary only for MacOS systems, otherwise VirtualBox is bundled with the Genymotion installer.
  2. Download and install Genymotion. You need to register first.
  3. Launch Genymotion and click on the option to create a new virtual device. The following screen is shown.
  4. genymotion first screen

  5. Click on the “Connect” button and log in using your Genymotion account. The full list of available devices is loaded. You can unfold each device to explore its features and the detailed specification.
  6. genymotion device list

  7. Select one of the devices, click “Next” and follow the assistant. ,
  8. Open the configuration when the virtual device is created.
  9. Click on the “Settings” option and check if the Android ADB is correctly selected. We have to indicate the path in our system that contains the Android SDK.
  10. genymotion settings

  11. Run the virtual device, which will be loaded in less than a minute.
  12. genymotion device running

    On the right edge of the emulator, we can change the device characteristics: battery life, GPS, orientation or camera.

    genymotion gps

  13. Finally, just open a project in Android Studio or Eclipse and try to run it. You will note that the virtual device is listed in the available running devices.
  14. genymotion android studio

    We don’t need any plug-in or any configuration to run an Android project from Android Studio or Eclipse using the Genymotion emulator.

    genymotion app running

Read More