Wednesday, September 24, 2014

VirtualBox Ubuntu: setup for development

I need a Linux box for work development (Mac Unix does not suffice) so I downloaded VirtualBox and Ubuntu. To start developing I needed a bunch of installed.

VItrualBox Ubuntu on Mac: up/down/delete keys act weird typing letters

When I try to navigate in vi editor the characters are being typed instead.

Tuesday, September 23, 2014

Eclipse: hiding files in Package Explorer

It is very important to have your Eclipse IDE as optimized as possible. It is essential for me to see all "hidden" files and directories such as .gitmodules, .project, .classpath, but I do not want to see .DS_store as it is useless to me.

GIT: remove last (few) commits

You should commit often, however sometimes I do a NEW commit instead making an amend to previous, that is especially important when working with tools like Gerit (online code review) when you can have only 1 commit, sometimes for a very long time.
This recipe works only if you did NOT PUSH.

GIT: update ALL REPOS in current directory

If you have a ZILLION GIT repositories in your current workspace you may benefit from a Bash shell command that does operations on all of them at one swoop.

Monday, September 22, 2014

Eclipse: converting Android to plain Java project

When you are switching between Android and plain Java projects (or libraries) occasionally you may end up with a Java project that is complaining: AndroidManifest.xml is missing!
This tutorial shows the steps to fix that.

Sunday, September 21, 2014

5b. Android: formatting numbers based on LOCALE

This example shows you how to format a number based on user's language and region setting (LOCALE)

Android Studio: Reveal in Finder

Very often you need to open the file or a directory in Finder (or Terminal), to do so you right-click on the file or directory and selected Reveal In Finder.

5a. Android Studio: create new Java CONSTANTS class

Sometimes is worth to extract a bunch of code to a separate class to keep the original short and sweet (readable and maintainable).

Eclipse: starting from bash command line

I start Eclipse from Bash command line (in to make sure it reads all Bash Enviroment settings.

function eclipse () {
nohup bash -ic /Eclipse_Luna_4_4/ &
echo "disown PID -- prevent eclipse from closing when you close Terminal"

Saturday, September 20, 2014

4i. Android: 9patch

If you want to provide a reach UI you will be using images, it is not possible to create image for every device size, therefore they will be stretching. Android 9patch is a way to control what can stretch in the image to preserve quality of that image.

Examples of using 9patch:

Finding draw9patch tool 

In the browser search for square icon

  • top - stretch horizontally
  • left - stretch vertically
  • right - content area
  • bottom - content area

Actual look of the 9patch:

Copy your 9patch  pop_up_background_82x82.9.png to drawable folder:


            android:background="@drawable/pop_up_background" />

4h. Android: Activity lifecycle methods

There are few concepts that you will have to get familiar with:

  • activity stack - LIFO (last in, first out )
  • active activity - running activity that is visible and interactive
  • paused activity - running activity that is visible, but obstructed
  • stopped activity - completely obstructed
  • inactivate activity - app has been killed by Android, or the user 

* Activity starts but it is not visible yet, open necessary connections
protected void onCreate(Bundle savedInstanceState) {
// your code
* Activity starts but it is not visible yet, open necessary connections
protected void onStart() {
// your code
* activity was completely hidden by another Activity, or another app, but not killed
* check if you need refresh time-sensitive content (facebook wall update)
protected void onRestart() {
// your code
* Activity is now visible to the user, resume updating the views
protected void onResume() {
// your code

/** Activity is obstructed, stop updating the views */
protected void onPause() {
// your code
* Activity was obstructed, release resources, or it may get killed
protected void onStop() {
// your code
* Activity is being killed by Android, close network and database connections
protected void onDestroy() {
// your code

There is a description available on from Google's Android Developers site:

It takes time and effort to create tutorials, please support my efforts with a couple-dollar donation, any amount will be greatly appreciated and highly motivating!

Android: language locale

Android allows us to write applications that are specific to languages and regions.

  • create locale specific layouts if language has different layout than default (i.e. Chinese)
  • create local specific res/values/strings.xml for each language you want to support
  • create local specific res/values/dimens.xml if language requires some minor length adjustments (e.g. German)

Don't forget to provide translations for regional varieties of the language!

    <string name="app_name">Converter Mate!</string>
    <string name="select_conversion">Select Conversion  Mate!:</string>
    <string name="enter_value">Enter Value  Mate!</string>
    <string name="action_settings">Settings  Mate!</string>
    <string name="resulting_value">Resulting Value Mate!:</string>

Android: switch case conditional

At some point, each application will have to perform some logic based on different cases.

  • extract your CONSTANTS
  • extract your logic into a separate method so it can be called from several places
  • use switch case instead of if else
  • use try catch statement when data types may vary

   private final static double CONVERSION_METERS_TO_YARDS = 1.093613298;
   private final static double CONVERSION_KILOMETERS_TO_MILES = 0.621371192;

   private void calculateResult() {
      Double valueEntered = 0.0;
      try {
         valueEntered = Double.valueOf(valueEnteredEditText.getText().toString());
         showToast("afterTextChanged " + valueEntered);
      catch (NumberFormatException e) {

      switch (selectedConversion) {
      case 0:
         resultingValueTextView.setText("" + valueEntered * CONVERSION_METERS_TO_YARDS);
      case 1:
         resultingValueTextView.setText("" + valueEntered * CONVERSION_KILOMETERS_TO_MILES);

Android: LinearLayout

I like to work with combination of LinearLayout, especially when creating forms.

<LinearLayout xmlns:android=""
            android:layout_weight="40" />
            android:layout_weight="60" />
            android:layout_weight="40" />
            android:layout_weight="60" />
            android:layout_weight="40" />
            android:layout_weight="60" />

Android: handling input fo TextEdit and updating TextView

Some of the simplest, but very useful apps, can contain forms that that you have to read and fill out. You can do most of that work with TextEdit (input) and TextView (output).

Step 1) Define your layout, name your widgets very well.

Step 2) Define class members for each of the fields that will be used multiple times

public class MainActivity extends ActionBarActivity {
   //during the life-span of the app we will access these fields many times
   private EditText valueEnteredEditText;
   private TextView resultingValueTextView;

Step 3) Find the right layout items by ID and inflate them.

   protected void onCreate(Bundle savedInstanceState) {

      valueEnteredEditText = (EditText) findViewById(;
      resultingValueTextView = (TextView) findViewById(;


Step 4) Add a listener that will react to a value entered

   private void addListenerToValueEnteredEditText() {

      valueEnteredEditText.addTextChangedListener(new TextWatcher() {
         public void onTextChanged(CharSequence s, int start, int before, int count) {
            showToast("onTextChanged ");
         public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            showToast("beforeTextChanged ");
         public void afterTextChanged(Editable s) {

Friday, September 19, 2014

Android Studio: switching between Project and Structure views

If you have a lot of methods in a given class you may want to see the Structure view.

Step 1) Select "monitor" icon in the bottom-left corner
Step 2) Select "Structure" view
Step 3) Open view settings "gear" icon
Step 4) Sort Alphabetically
Step 5) Autoscroll to Source - if you select any method on the left, the right source will show
Step 6) Autoscroll from Source - if you select in the source, the method on the left will be selected

Android: adding a Spinner (drop-down or pick-list widget)

You start by adding Spinner UI to your res/layout/activity_xyz.xml
Make sure to give it a meaningful ID, especially if you have multiple Spinner items.

            android:id="@+id/conversionSelectorSpinner" />

If your spinner will have a pre-defined list of items that will need to be translated to another language then you probably should use string-array in res/values/strings.xml

    <string-array name="conversionTypeArray">
        <item>meters to yards</item>
        <item>kilometers to miles</item>

In your Activity class you have to add your Spinner in onCreate() method.

   protected void onCreate(Bundle savedInstanceState) {
      //set up the conversion choices using a Spinner
      Spinner conversionSelectorSpinner = (Spinner) findViewById(;
      // create adapter from the res/values/strings.xml/string-array
      // simple_spinner_item is a TextView
      ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.conversionTypeArray, android.R.layout.simple_spinner_item);
     // simple_spinner_dropdown_item is basically a single line TextView that serves as header of a Spinner
       // set array adapter to populate the spinner

Now if you build  the APK we will have a Spinner, but we will have to make it work for us.

We will need a variable that will hold our selection, we will make it a class member to be used in various methods.

public class MainActivity extends ActionBarActivity {
   private int selectedConversion = 0;

We will need a programmatic access to the string-array we defined, we will add that line inside our onCreate() method.

 final String conversionTypeArray[] = getResources().getStringArray(R.array.conversionTypeArray);

Finally, we will have to add a event listener to our Spinner.

      // add listener that will react when an item was selected
      conversionSelectorSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
         public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
            // assign selected item to the class member to be used later
            selectedConversion = position;
            // if you change conversion type, it is natural that the result will be different
            // we would not have debug toasts in production version, for edu purposes only
            showToast("onItemSelected in position: " + position + " id: " + id + " selected name: " + conversionTypeArray[position]);
         public void onNothingSelected(AdapterView<?> parentView) {
            // onNothingSelected is a Callback method to be invoked when the selection disappears from this view.
            // The selection can disappear for instance when touch is activated or when the adapter becomes empty.

Android apps now can run on every OS in a Chrome browser

Android apps can now run on every OS in a Chrome browser, or at least this can be shown to be possible. Tested on OS X, Windows and Ubuntu.

"ARChon runtime lets you run unlimited number of Android APKs created with chromeos-apk on Chrome OS and across any desktop platform that supports Chrome."


On personal note, the author of the hack, Mr. vladikoff001, is our developer hero of the mega proportions. Congratulations.

Yes, this is still a buggy hack, but it definitely opens doors for bigger and better future for this Android developer.

Android Studio: Eclipse shortcuts and formatter

If you are switching between Eclipse (at work) and Android Studio (home, teaching) then you will run into a problem of remembering the keyboard shortcuts and formatting the code consistently.

In Android Studio you have an option to add "Eclipse Code Formatter" and specify the xml formatter you exported from Eclipse (for your whole team).

You also have an option of using keymaps (keyboard shortcuts) from Mac Eclipse.

GIT: submodules

In this tutorial you will see examples of how to work with modules in GTI. It is a good practice for multiple projects to re-use common libraries of code, for example model library, APIs, utility classes, etc.

Eclipse: show hidden files

It is common that you need to edit hidden .* files, for example if you work with GIT you may want to edit .gitignore file.

In Eclipse > Package Explorer > select drop-down arrow "View Menu" > Filters ...

Then unselect ".* resources" and the .gitignore .gitmodules, etc. should be showing. 

Tuesday, September 16, 2014

Eclipse not reading ANT env variables

Sometimes you have ANT build.xml that works perfectly from command line but does not execute in Eclipse:

Execute failed: Cannot run program "${env.THRIFT_TOOL}": error=2, No such file or directory

When you inspect your build.xml you should have (true for any executable):

<property environment="env"/><property name="thrift.compiler" value="${env.THRIFT_TOOL}"/>

If you inspect your env variable setting, on OSX ~/.profile you should have:

# Thrift tool  - updated: Sept 16, 2014
export THRIFT_TOOL=/usr/local/bin/thrift

Yet Eclipse is not running Ant correctly!

Starting Eclipse from COMMAND LINE fixes the issue:

$ bash -ic /Applications/../ 

Thrift: building from source

I was required to build Thrift from sources (to adjust it to generate Parcelable Android model classes)

uki@ thrift $ .git clone
uki@ thrift $ cd thrift
uki@ thrift $ .git checkout 0.9.1
uki@ thrift $ ./
uki@ thrift $ ./
uki@ thrift $ ./configure
uki@ thrift $ sudo make
uki@ thrift $ sudo make install

I get an error on my Mac:

./src/thrift/cxxfunctional.h:93:18: error: no member named 'bind' in namespace 'std'; did you mean 'find'?

Attempted solution 1:

I found a post on
change file:
line 51 to #include "thrifty.hh"

src/thriftl.ll:51:10: fatal error: 'thrifty.hh' file not found
#include "thrifty.hh"

Attempted solution 2:

As I was reading up I found that the version of my C++ might be wrong:

"libc++, the default C++ standard library in 10.9, doesn't include the experimental TR1 headers - just their standardized C++11 versions"

Checking the existing version of C++ on Mac:

 $ gcc --version
Configured with: --prefix=/Applications/ --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 5.1 (clang-503.0.40) (based on LLVM 3.4svn)

Installed newest C++ from brew

$ brew install gcc49

in my ~/.profile I added these 2 lines:

# C++ HOME - updated: Sept 16, 2014
export CPP_HOME=/usr/local/Cellar/gcc/4.9.1/bin/
export PATH=${PATH}:${CPP_HOME}
alias g++="/usr/local/Cellar/gcc/4.9.1/bin/cpp-4.9"
alias gcc="/usr/local/Cellar/gcc/4.9.1/bin/cpp-4.9"

now in the Terminal I can verify this:

uki@ thrift $ gcc --version
cpp-4.9 (Homebrew gcc 4.9.1) 4.9.1

The exercise is not complete yet, so I was not able to verify if this is a fix.

Monday, September 15, 2014

Eclipse: Thrift plugin

If you are editing Thrift files you will need this plugin.

GIT: installation on Mac

General GIT installation page:


Mac Specific:

Install Brew - Mac package installer

This "brew" tool will be useful for many other things...

$ ruby -e "$(curl -fsSL"

Check existing version of git

$ git --version
git version (Apple Git-48)

We can see that I had not the newest GIT (1.8.5), but I want to latest and greatest...

Install the latest and greatest git version

$ brew install git
/usr/local/Cellar/git/1.9.0: 1322 files, 30M

At this point the new GIT is installed, however the old GIT is still being used..

$ git --version
git version (Apple Git-48)

Checking the NEW GIT at different location...

uki@ bin $ /usr/local/Cellar/git/1.9.0/bin/git --version
git version 1.9.0

Edit the PATH so he new GIT tool is found first

Open Applications > Utilities >
We will be editing .profile file located in your home folder (~), this file may not be showing in your Finder, so you might need to do it in vi editor.

edit ~/.profile
export GIT_TOOL=/usr/local/Cellar/git/1.9.0/
export PATH=${GIT_TOOL}/bin:${PATH}
$ git --version
git version 1.9.0

Sunday, September 14, 2014

Android Class - Table of Contents

Note: content of this page is being migrated to the right margin.

Session 1

GIT: cheat sheet

UNIX commands review

Session 2 - review

Android SDK: set-up in IDE

 Android Studio - creating Android Virtual Device AVD

Android Studio - changing the app name

Android Studio - creating new Module (app)

Android Studio - Failure [INSTALL_FAILED_OLDER_SDK]

Android Studio - Error:compileSdkVersion android-L requires compiling with JDK 7

Session 3

Android Tutorial - creating calc converter app

Saturday, September 13, 2014

Android Tutorial - creating GUI - converter app

Step 1: Open src > main > res > activity-main.xml

  • Use "Design" view to bring desired Views
  • Use "Text" view to edit XML

Read about Spinner:

Read about Toast:

Android: creating new module - calc converter app


In this short tutorial you will create a new Android Studio project.

Step 1. In Android Studio create a new Module

  • Android Application
  • Application Name: Unit Conventer
  • Module Name: unit_conventer
  • edu.clcillinois.cit299.calc
  • Min. required SDK: API 10
  • Target SDK:  API 19 (Kitkat)
  • Compile with: APK 19  (Kitkat)
  • Java: 1.6
  • Theme: Holo Light

Step 2. Search on Google images and/or create an icon for the app

search terms: calculator converter icon

Step 3: Chose the selected app icon

Step 4: Create "Blank Activity" with ActionBar

Step 5: Create "MainActivity" and "activity_main" layout

Step 6: Deploy the app to a device

If you get an error

see fix here: 

Android Studio - creating new app icon

You can set a new app icon at any time, but if you have the asset already created the best time is to set it when you create the new app (new Module).

Android Studio - Error:compileSdkVersion android-L requires compiling with JDK 7

Error:compileSdkVersion android-L requires compiling with JDK 7
Open SDK Settings

Problem Description:

The default java 1.6 on Mac is located at
You need Java 1.7 to compile android-L


Download the newest Java from Oracle site.
$ java -version

java version "1.8.0_20-ea"

Set location of Java JDK to newest Java you have installed


Android Studio - Failure [INSTALL_FAILED_OLDER_SDK]

Problem Description:

When trying to install a newly created app the error appears in Run window and the app fails to install.


Additional info:

This bug occurs when styles.xml contain:

<style name="AppTheme" parent="Theme.AppCompat.Light">


Open build.gradle

Change from:

android {
    compileSdkVersion 'android-L'
    buildToolsVersion "20.0.0"

Change to:

    compileSdkVersion 20
    buildToolsVersion "20.0.0"

Re-run the project and it will work OK.

Android Studio - creating new Module (app)

Android Studio Project e.g. CIT_299 can contain multiple Modules, or apps.

Create a new Module - App

  • Application name 
  • module name

Android Studio: changing the app name

The app name is normally saved in string name="app_name"

To change the app name you should navigate:


  • CIT_299 - is your project name
  • week03 - is your app folder
  • main/res - is how Android Studio places resources folder
  • values - is you DEFAULT LANGUAGE values folder

Make sure you change any other language you want to support e.g. values-es for Spanish

Next, you should rename the DIRECTORY and MODULE name:

Finally, make sure settings.gradle include the newly named module

include: ':converter', ':week2'

Friday, September 12, 2014

Android Studio: creating Android Virtual Device AVD

Why do we need AVD?

To be honest most of my Android testing happens on the real devices, however sometimes you need to test on a device with different screen size, different resolution (dpi) or limited memory or network bandwidth.

Example AVD Settings

One of my favorite emulator settings is the 10.1 inch tablet with mdpi resolution, it it relatively light weight and works pretty well.  

Starting AVD with the correct scale for your screen size.

It is essential that when you start the emulator of e.g. 10.1 inch tablet, it is actually 10.1 inch (diagonally) on your screen - you should measure it with a ruler. If the screen is too small you will design all the elements too big, if the emulator is too big, the UI will be too small on the real device.

Android SDK: set-up in IDE

It is a good practice to maintain a Stand Alone version of Android SDK (also called ADT for Eclipse) that is residing on your file system independently of your IDE (Eclipse, or Android Studio).

Getting Android SDK



Once you download the SDK (ADT) put it in a convenient location, I keep it on my Mac here:


The reason for this location is that it is being backed up with all Apps and moved to another Mac when upgrading. We aware that after you download all kinds of versions this folder will grow, mine is about 13 Gb most of that are system-images -- and I don't even have all previous versions of Android downloaded. You will need every version you are building for, so for example I am currently using API 17 and 19.

Setting SDK in Eclipse (Luna):

Setting Android SDK in Android Studio