Android controlling EditText input

Description: coming soon..


  • imeOptions flagNoFullscreen
  • imeOptions actionDone
  • inputType textUri



        <EditText
            android:key="server_ip"
            android:title="server_ip"
            android:dialogTitle="@string/server_ip"
            android:contentDescription="Server IP"
            android:defaultValue="192.168.1.2"
            android:lines="1"
            android:imeOptions="flagNoFullscreen|actionDone"
            android:inputType="textUri"/>

Android: using AIDL

DEFINING AIDL OBJECTS


Let's say we want to define AIDL that we will use to communicate UI Fragment with AndroidService.

/** calls UI to Service **/
MyServiceAIDL.aidl

interface CommandServiceAIDL {
void setSomething(double value);
}



/** callbacks service to UI **/
MyListenerAIDL.aidl

interface MyListenerAIDL {
void onSomeEvent( boolean isOn);
}



ONCE YOU HAVE YOUR AIDL DEFINED



Let's say we have a UI Fragment

import android.content.ServiceConnection;

public class MyFragment extends Fragment implements ServiceConnection {
// ...
 @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
    // we have to BIND this UI to AIDL service
      getActivity().getApplicationContext().bindService(new Intent(CommandConst.ACTION_BIND_SERVICE), this, Context.BIND_AUTO_CREATE);
   }


// ...
@Override
   public void onDestroy() {
      super.onDestroy();
     // WE have to UNBIND this UI form AIDL service
      getActivity().getApplicationContext().unbindService(this);
   }



// class that has all my AIDL methods
private MyServiceAIDL myServiceAIDL;

@Override
   public void onServiceConnected(ComponentName name, IBinder service) {
   
      myServiceAIDL = MyServiceAIDL.Stub.asInterface(service);
      try {
         // register this fragment as a client of the AIDL service
         myServiceAIDL.register(TAG, myServiceAIDL Callback);
         myServiceAIDL.setSomething(123.5);
      }
      catch (RemoteException e) {
         Log.e(TAG, e.getMessage(), e);
      }
   }


private void doSomething(double value) {
         try {
            myServiceAIDL.setSomething(value);
         }
         catch (RemoteException e) {
            e.printStackTrace();
         }
      }


 // CALLBACKS

 private final MyListenerAIDL.Stub commandServiceCallback = new SimpleCommandServiceListener() {

     @Override
      public void onSomeEvent(final boolean isOn) throws RemoteException {
         handler.post(new Runnable() {
            @Override
            public void run() {
               if (someSwitch.isChecked() != isOn) {
                  someSwitch.setChecked(isOn);
               }
            }
         });
      }
}

Android app deploying and monetizing

In this tutorial we will discuss what you need to do to deploy your app to the Google Play Market and how to make money $$$.

Android Studio: migrating to 1.0

Exciting moment -- Android Studio is not a baby anymore!
However, the rite of passage did not come without the growing pains.

Mac OS X: cpp tools

In this tutorial I will summarize how to install all tools needed to compile C++ code.

Install Apple's Command Line Tools:

$ xcode-select --install

xcode-select: error: command line tools are already installed, use "Software Update" to install updates




SMS bid app



README.md

*************************************************
APP OVERVIEW
*************************************************

Use cases:
1) User creates offline list of items that will be used in an auction, example:
- sofa, pale blue, heavily used #sofa001
- mountain bike, barely used (I am developer not a sportsman) #bike002
- HTC ONE, Android phone, still working, AT&T #phone003
2) User distributes the list of bid items to FFF (family, friends and fools) by mailing, posting, etc.
3) User enters the bid items into the app
4) User enters the bid deadline per item into the app
6) User enters a minimum bid price per item into the app
7) FFF send SMS messages with bid in format:

bid #bike002 $30

8) The app tally up the highest bid and replies to FFF

- Minimum bid for item #bike002 is $30
- These is a higher bid for #bike002 in amount of $31

9) User can monitor the winning bids in the app

#sofa001
No bids

#bike002 minimum bid $30
- $31 from 6508151234
- $30 from 6508151432

10) there are many additional features you can add to this application


AndroidStudio: install *.md plugin

It is a common practice to provide a README text file in the root of the project.
The file usually specify:
- project overview
- project dependencies
- how to build the project
- copyrights

It is became the standard to write this file in a MarkDown format README.md

Once you create a new *.md text file the AndroidStudio tells you that it does not recognize the format and to download the plugin.

Android: checking IP of your devie





$ adb shell netcfg
lo       UP                                   127.0.0.1/8   0x00000049 00:00:00:00:00:00
can0     UP                                     0.0.0.0/0   0x000000c1 00:00:00:00:00:00
can1     UP                                     0.0.0.0/0   0x000000c1 00:00:00:00:00:00
can2     UP                                     0.0.0.0/0   0x000000c1 00:00:00:00:00:00
can3     UP                                     0.0.0.0/0   0x000000c1 00:00:00:00:00:00
tunl0    DOWN                                   0.0.0.0/0   0x00000080 00:00:00:00:00:00
sit0     DOWN                                   0.0.0.0/0   0x00000080 00:00:00:00:00:00
ip6tnl0  DOWN                                   0.0.0.0/0   0x00000080 00:00:00:00:00:00

eth0     UP                                 192.168.1.4/24  0x00001043 00:04:a3:92:d4:0b

If you like this post, please give me your 2 cents ($0.02 litterally) to show token of appreciation and encourage me to write more:

Donate Bitcoins

Android: start app on reboot

In this tutorial we will learn how to start an app (Activity or Service) on Android reboot.

Android: detect your own phone number

In this tutorial you will learn how to detect your own phone number programmatically

Android: send SMS programmatically

This tutorial is a continuation of previous post:
http://ukitech.blogspot.com/2014/11/android-calling-activity-from.html

We will learn how to SENT a SMS programmatically.

Android: calling Activity from BroadcastReceiver

This tutorial is a continuation of the previous post:
http://ukitech.blogspot.com/2014/11/android-sms-app.html

We will learn how to connect Activity (UI) and BroadcastReceiver which does not know the Activity (and hence the UI) using Application class.

Android Studio: GIT: .gitignore

Managing which files should be ignored by GIT (code repository) it an important skill. It is done by .gitignore file in which each line represents a directory, a pattern, or a file to be ignored.

Android: SMS app: receiving

In this tutorial we will learn how to handle incoming messages, how to parse them to find a pattern, and how to send an SMS.

android-maven-plugin-4.0

As you are migrating your projects from old to new Android structure you may encounter:

Mac OS X Yosemite: Java and Android developer

If you did not upgrade yet, you will probably do so within days, here are my observations so far.


12a. Android: JSON OpenWeatherMap

In this tutorial we will implement basic weather OpenWeatherMap API using JSON (JavaScript Object Notation).

Android: Camera

In this tutorial we will learn how to capture an image using Android Camera and how to pass this image from a Fragment back to Activity

Android: MediaPlayer

In this tutorial we will learn how to play MP3 file saved in the application. We will create an app that plays a soothing sound of the forest (or waves, or rain) that plays in the loop. We will also learn how to control the playback.


Android: ADB install apk

In this tutorial you will learn frequently used Terminal commands (from your computer) to manage APKs on your Android device.

Cron Job to keep server time up to date

This tutorial shows you how to set up a CRON (repetitive) JOB on Ubuntu Linux server to update the correct time.

IntelliJ IDEA: code snippet auto-complete

In this tutorial I will show how to create auto-complete snippets using IntelliJ IDEA. This is a very convenient for such things as copyright information that I need to include in clients' files.

BookShelf app: adding book cover

In this tutorial we will add a field to our model and the database.

ListView: customizing item view

In this tutorial we will make custom ITEM of the ListView


ListView: press state selector

In this tutorial we will add visual indication to ListView pressed state.

Gradle: Working with multi app projects in Android Studio

In this tutorial I wanted to share how is my project organized to work with multiple apps and libraries.

Maven: updating version on Mac

In this tutorial we will discuss upgrading Maven on Mac OS X.

Maven: installing Android SDK

In order to compile Android project using Maven you have to instal Android SDK to your Maven repository.


$ git clone https://github.com/mosabua/maven-android-sdk-deployer.git
Cloning into 'maven-android-sdk-deployer'...
remote: Counting objects: 3198, done.
remote: Compressing objects: 100% (7/7), done.
remote: Total 3198 (delta 3), reused 6 (delta 3)
Receiving objects: 100% (3198/3198), 435.92 KiB | 0 bytes/s, done.
Resolving deltas: 100% (1585/1585), done.
Checking connectivity... done.

$ cd maven-android-sdk-deployer/

Android NFC

In this tutorial we will create a simple NFC app as a new project from scratch.

Android: reinstalling several APKs from single folder

In this tutorial we will install multiple APKs from your local computer to Android device using ADB connection.

echo "                    ██╗"
echo "██╗   ██╗ ██╗   ██╗ ╚═╝"
echo "██║   ██║ ██╚═██╗═╝ ██╗"
echo "██║   ██║ ████══╝   ██║"
echo "██║   ██║ ██║╚██╗   ██║"
echo "████████║ ██║  ╚██╗ ██║"
echo "╚═══════╝  ╚╝   ╚═╝ ╚═╝"
echo

# Install new APKs
for apk in $(ls *.apk)
do
    echo "Installing $apk"
    echo
    adb install -r "$apk"
done

Groovy on Android

Android developers are already using Groovy in many places AROUND Android, for example in Gradle build scripts. Now the dream of using Groovy as primary language for Android is a little closer to realization! See what is cooking.

Installing Maven

After few years of not needing it, I came back to Maven, reason being that I cannot use Gradle for reasons beyond my control and Ant does not describe complex projects structures required.

Bash: GIT repetitive tasks

I have too many GIT repos to remember that I need to keep updated, to do that I have a script that updates what I need.

Mac Daemons that hunt us

Sometimes you get annoyed by garbage other companies are trying to stuff on your computer. Motorola is one of these companies. When I connect my test DROID device the annoying popups are opened. 

This is not a conclusive solution, but a start of the longer article on the unwanted Mac Daemons that suck up your patience and CPU power.

Removing Launch services


$ launchctl list | grep moto
- 0 com.motorola.motohelperUpdater
32594 - com.motorola.motohelper
- 0 com.motorola.MDMUpdaterPlist
$ launchctl remove com.motorola.motohelper

$ launchctl remove com.motorola.motohelperUpdater


Removing unwanted Application



cd /Library/Application\ Support/
$ ls | grep Moto
MotoCast

Motorola Mobility
uki@ Application Support $ sudo rm -r MotoCast
Password:

uki@ Application Support $ sudo rm -r Motorola\ Mobility/



List of legitimate Services:


  • PTPCamera - part of the Image Capture software that MacOS uses

Got Droid? - My Android (test) devices

While cleaning my office I decided to make an inventory of my Android devices.

Please note that it is NOT worth testing on anything less than API 8 Android 2.2 Froyo as it is less than 0.7% of the market share,  so it is OK to use support library v7 in all apps you are running. 
I keep my Google ION for "sentimental reasons only.


OSOS versionVersion NameAPI LEVEL% usedMakeModelCPU nameCPU MhzCPU numberflash ROMRAMCamera MpBTRadioscreen heightscreen widthscreen density dpiScreen diagonal inches
Android1.6Donut40HTCGoogle ION / Magic528132quad band unlocked3.2
Android2.2.3Froyo80.7MotorolaDROIDArm Cortex A860015128544802403.7
Android/CM2.3.3Gingerbread MR11011.4BNNookColor10246001617
Android2.3.3Gingerbread MR11011.4HTCVision / Desire Z A7272ARMv7 Scorpion80011.5Gb51252.18004802403.7
Android2.3.4Gingerbread MR11011.4MotorolaDROID2 A955OMAP 3630100018Gb51252.18544803.7
Android4.2.2Jelly Bean1720.7SamsungGT-P7510 Tab 10.1128075216010.1
Android4.1.11720.7HTCOne X11967203204.9
Android4.4.2KitKat1924.5SamsungSM-P990 Galaxy Tab 12.12560160032012.1
Android/CM4.4.4KitKat1924.5OnePlusOne A0001Snapdragon 8014192010804805.5













Android name to version to API level table


  • API 1 (no code name) 1.0  
  • API 1 (no code name) 1.1  
  • API 3 Cupcake 1.5, NDK 1
  • API 4 Donut 1.6, NDK 2
  • API 5 Eclair 2.0  
  • API 6 Eclair 2.0.1  
  • API 7 Eclair 2.1, NDK 3 - support-v7 ActionBar
  • API 8 Froyo 2.2.x  , NDK 4
  • API 9 Gingerbread 2.3 - 2.3.2  , NDK 5 - added some NFC
  • API 10 Gingerbread 2.3.3 - 2.3.7   - added full NFC
  • API 11 Honeycomb 3.0  
  • API 12 Honeycomb 3.1  , NDK 6
  • API 13 Honeycomb 3.2.x  
  • API 14 Ice Cream Sandwich 4.0.1 - 4.0.2, NDK 7 - added NFC: Android Beam
  • API 15 Ice Cream Sandwich 4.0.3 - 4.0.4 , NDK 8
  • API 16 Jelly Bean 4.1.x  
  • API 17 Jelly Bean 4.2.x  
  • API 18 Jelly Bean 4.3.x  
  • API 19 KitKat 4.4 - 4.4.4  
  • API 20 Android Wear devices
  • API 21 Lollipop 5.0 API level 21


My devices spreadsheet



8b. ListViewSwipeActivity

In this tutorial you will learn how to use ListViewSwipeActivity.


6a. Java: Generic Type Interface

In this tutorial we will learn how to create an Interface that serves any type of object using Java Generic Types introduced in Java 1.5.

9b. Gradle: AndroidStudio with submodules (library projects)

In this tutorial we will overview integration basics of Android Studio and Gradle build tools.

Android: ListViewSwipeActivity ListView with swipe detection

In this tutorial we will explore writing and using ListView that extends support-v7 ActionBarActivity and detects side-to-side swipes and touch events.

8a. Android: populating ListView from the Databse

In this tutorial we will expand on the previous example showing basic SQLite CRUD methods. We will populate a list with results from the database.


7b. SQLite CRUD - BookShelf app

In this tutorial you will learn basic SQLite CRUD  functions (Create, Read, Update, Delete) for database operations. Actually, we will use Save, Fetch, Update and Delete method names.

7a. Android: Shared Preferences: saving and fetching persistent data

In this tutorial you will learn how to save and retrieve user preferences.

IntelliJ IDEA 13: error preventing Android project compilation

4:00:12 AM Throwable: Cannot generate protobuf files as the path to protoc has not been set. Please set in Settins > Compiler
4:00:12 AM Compilation completed with 0 errors and 0 warnings in 0 sec


Not resolved

5e. Android: opening a Web page

In this Tutorial you will learn how to open a Web page in Android.

Android: opening other screen (Activity) from Menu

In this tutorial you will learn how to open a new screen (Activity) using an Intent and Menu items.

5d. AndroidStudio: convert to lower/upper case

This tutorial shows you how to change the code lower/upper case of code in Android Studio.

5c. Android: Fragments

When part of your screen has to change layout based on the application logic it is a good practice to use Fragments. For example, user changes convertor type from "length" to "colors" which has very different UI layout, some of the the screen (Activity) will remain the same, but the conversion input will be a different Fragment.


Eclipse: export and import preferences

When you work in multiple Eclipse workspaces recreating your preferences is time consuming, to avoid this you can quickly export your set-up and next time you create a workspace import it.

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: