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.

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.

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.

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 Terminal.app) to make sure it reads all Bash Enviroment settings.


function eclipse () {
nohup bash -ic /Eclipse_Luna_4_4/Eclipse.app/Contents/MacOS/eclipse &
echo "disown PID -- prevent eclipse from closing when you close Terminal"
}

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:

conventer/src/main/res/drawable-mdpi/pop_up_background.9.png


    <TextView
            android:id="@+id/resultingValue"
            android:text="..."
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="60"
            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) {
super.onStart();
// your code
}
/**
* Activity starts but it is not visible yet, open necessary connections
*/
protected void onStart() {
super.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() {
super.onRestart();
// your code
}
/**
* Activity is now visible to the user, resume updating the views
*/
protected void onResume() {
super.onResume();
// your code
}


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


There is a description available on from Google's Android Developers site:
http://developer.android.com/reference/android/app/Activity.html




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!

<resources>
    <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) {
         resultingValueTextView.setText("");
         return;
      }

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

Android: LinearLayout


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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context=".MainActivity">
    <LinearLayout
        android:id="@+id/spinnerLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/select_conversion"
            android:layout_weight="40" />
        <Spinner
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/conversionSelectorSpinner"
            android:layout_weight="60" />
    </LinearLayout>
    <LinearLayout
        android:layout_marginTop="20dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView
            android:text="@string/enter_value"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_weight="40" />
        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:inputType="number"
            android:ems="8"
            android:id="@+id/valueEntered"
            android:onClick="onClickEnterValue"
            android:text=""
            android:layout_gravity="center_vertical"
            android:layout_weight="60" />
    </LinearLayout>
    <LinearLayout
        android:layout_marginTop="30dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView
            android:text="@string/resulting_value"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="40" />
        <TextView
            android:id="@+id/resultingValue"
            android:text="..."
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="60" />
    </LinearLayout>
</LinearLayout>


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.

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);


      valueEnteredEditText = (EditText) findViewById(R.id.valueEntered);
      resultingValueTextView = (TextView) findViewById(R.id.resultingValue);


       addListenerToValueEnteredEditText();
       createConversionSelectorSpinner();
   }



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) {
            calculateResult();
         }
      });
   }



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.

        <Spinner
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            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>
    </string-array>


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

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
     
      //set up the conversion choices using a Spinner
      Spinner conversionSelectorSpinner = (Spinner) findViewById(R.id.conversionSelectorSpinner);
     
      // 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
      adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
     
       // set array adapter to populate the spinner
      conversionSelectorSpinner.setAdapter(adapter);



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() {
         @Override
         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
            calculateResult();
            // we would not have debug toasts in production version, for edu purposes only
            showToast("onItemSelected in position: " + position + " id: " + id + " selected name: " + conversionTypeArray[position]);
         }
         @Override
         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.
            showToast("onNothingSelected");
         }
      });










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."

VIDEO DEMO

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. 



Eclipse not reading ANT env variables

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

BUILD FAILED
Execute failed: java.io.IOException: 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
export PATH=${THRIFT_TOOL}:${PATH}


Yet Eclipse is not running Ant correctly!

Starting Eclipse from COMMAND LINE fixes the issue:

$ bash -ic /Applications/../Eclipse.app/Contents/MacOS/eclipse 

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 https://github.com/apache/thrift.git
uki@ thrift $ cd thrift
uki@ thrift $ .git checkout 0.9.1
uki@ thrift $ ./cleanup.sh
uki@ thrift $ ./bootstrap.sh
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 http://blog.evernote.com/
change file:
thrift/compiler/cpp/src/thriftl.ll
line 51 to #include "thrifty.hh"

src/thriftl.ll:51:10: fatal error: 'thrifty.hh' file not found
#include "thrifty.hh"
THIS SOLUTION CLEARLY DOES NOT WORK

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/Xcode.app/Contents/Developer/usr --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.


Eclipse: Thrift plugin

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

GIT: installation on Mac

General GIT installation page:

http://git-scm.com/book/en/v2/Getting-Started-Installing-Git

 

Mac Specific:

Install Brew - Mac package installer

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

$ ruby -e "$(curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)"

Check existing version of git

$ git --version
git version 1.8.5.2 (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 1.8.5.2 (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 > Terminal.app
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


Android Class - Table of Contents

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

Session 1

GIT: cheat sheet

http://ukitech.blogspot.com/2014/06/git-cheat-sheet.html

UNIX commands review


Session 2 - review

Android SDK: set-up in IDE

http://ukitech.blogspot.com/2014/09/android-sdk-set-up-in-ide.html

 Android Studio - creating Android Virtual Device AVD

http://ukitech.blogspot.com/2014/09/android-studio-creating-android-virtual.html

Android Studio - changing the app name

http://ukitech.blogspot.com/2014/09/android-studio-changing-app-name.html

Android Studio - creating new Module (app)

Android Studio - Failure [INSTALL_FAILED_OLDER_SDK]

http://ukitech.blogspot.com/2014/09/android-studio-failure.html

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

http://ukitech.blogspot.com/2014/09/android-studio-errorcompilesdkversion.html


Session 3

Android Tutorial - creating calc converter app


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

Objective

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

Failure [INSTALL_FAILED_OLDER_SDK]
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
/Library/Java/Home
You need Java 1.7 to compile android-L

Solution:

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


/Library/Java/JavaVirtualMachines/jdk1.8.0_20.jdk/Contents/Home

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.

Failure [INSTALL_FAILED_OLDER_SDK]

Additional info:


This bug occurs when styles.xml contain:

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

Fix:


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/week03/src/main/res/values/strings.xml

Where: 
  • 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'




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


Open:
http://developer.android.com/sdk/index.html


Download:
http://developer.android.com/sdk/index.html#download

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


/Applications/Android/SDK/android-sdk-macosx

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