Shortlink

Dive into Android development – VI

Let’s develop a simple Android application to perform dial-up and SMS operations. Let’s have two buttons “Call” and “SMS” as shown below. Clicking these buttons will perform the appropriate actions.

The resource layout file for the two buttons is given below.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/relativeLayout1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="0.13" >

    <Button
        android:id="@+id/callBtn"
        android:layout_width="80dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="120dp"
        android:layout_marginTop="50dp"
        android:text="Call" >
    </Button>

    <Button
        android:id="@+id/smsBtn"
        android:layout_width="80dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="120dp"
        android:layout_marginTop="120dp"
        android:text="SMS" >
    </Button>

</RelativeLayout>

Performing dial up and SMS operations involve use of Intents in Android. Intent is a simple class that encapsulates an action and data. For example Dial, Sms, Capture image are all actions that you want to perform. Wrap this information and associated data in a Intent object and launch an activity using it. Intent sends a message to the underlying Android system which triggers the necessary activity. So to dial a number you can use Intent.ACTION_DIAL as shown below.

Intent callIntent = new Intent(Intent.ACTION_DIAL,Uri.parse("tel:12345678"));
startActivity(callIntent);

The phone number and the action are wrapped in an Intent object and launched using startActivity method. This will automatically take you to the dialer screen.
To send a message you can use Intent.ACTION_VIEW with some additional information as shown below.

Intent smsIntent = new Intent(Intent.ACTION_VIEW);
smsIntent.setType("vnd.android-dir/mms-sms");
smsIntent.putExtra("sms_body", "Hi!!!");
smsIntent.putExtra("address", "12345678");
startActivity(smsIntent);

You can set the intent type to the MIME TYPE “vnd.android-dir/mms-sms”, and also provide the addresses and the message body.

The complete code of the activity class is shown below.

public class DiveIntoAndroid6Activity extends Activity {
	private Button callBtn,smsBtn;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		callBtn = (Button)findViewById(R.id.callBtn);
		smsBtn = (Button)findViewById(R.id.smsBtn);

		callBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent callIntent = new Intent(Intent.ACTION_DIAL,Uri.parse("tel:12345678"));
				startActivity(callIntent);
			}
		});
		smsBtn.setOnClickListener(new OnClickListener(){
			public void onClick(View v){
				Intent smsIntent = new Intent(Intent.ACTION_VIEW);
				smsIntent.setType("vnd.android-dir/mms-sms");
				smsIntent.putExtra("sms_body", "Hi!!!");
				smsIntent.putExtra("address", "12345678");
				startActivity(smsIntent);
			}
		});
	}
}
Shortlink

Multiple data sources in Grails 2.0

One of my favourite features in Grails 2.0 is the support for configuring multiple data sources. I remember playing with the spring resources to configure multiple data sources in one of my client assignments. Grails 2.0 brings in a built-in support for this.
You can go the DataSource.groovy and configure many datasources like below

environments {
    development {
        dataSource {//DEFAULT data source
            
        }
	dataSource_users { //Convention is dataSource_name
            
        }
	dataSource_sales {
            
        }
    }
    production {
        dataSource {
        
	}
	dataSource_users {
            
        }
	dataSource_sales {
            
        }
    }
}

You have 3 datasources configured, the ‘DEFAULT’, ‘users’, ‘sales’ in for development and production environments.
If you have two domain classes ‘Role‘ and ‘Product‘ mapped to table in ‘users’ and ‘sales’ data sources respectively, you can write it as

class Role{
    static mapping = {
          datasource 'users'
    }
}
class Product{
	static mapping = {
		datasource 'sales'
	}
}

If the datasource is not specified in the domain classes it will use the ‘DEFAULT’ datasource.
You need to be careful while using the service classes, because service classes provide transactional support to the default dataSource. You can change it by using static datasource = ‘name of the datasource’ in the service class.

Shortlink

Function Statements and Expressions in JavaScript

JavaScript is not really taken very seriously as a programming language, when it has to be. This statement comes to my mind whenever I read the book JavaScript, Good Parts.

In JavaScript you can define a function as a statement or as an expression.ie.,

   function eat(){ document.write("Eating"); }//Statement
   var eat = function(){ document.write("Eating"); }//Expression

The main difference between the two comes in the use of the function. A function declared as a statement can be used anywhere in the script ie., even before the declaration like

      eat();//prints Eating
      function eat(){ document.write("Eating"); }//Statement

The same code will throw an error if the function were declared as an expression.

      eat();//Uncaught TypeError: Property 'eat' of object [object DOMWindow] is not a function
      var eat = function(){ document.write("Eating"); }//Statement

So we’ll have to either stick to using functions as statements or expressions in the code. Need to be careful when we use both.

Shortlink

Gradle your Java app

Working with ANT has always been a slightly boring experience for me because of it’s rigid XML syntax. Setting up classpath, tasks like clean, compile, run tests etc., every time is a tedious process.
Ever since I started working with Groovy I started looking at a build tool known as Gradle. Gradle is a Groovy script that can be used to automate the build activities of your project. Let’s see how to build a simple Java project using Gradle.

You can download Gradle and add the bin folder to the path. I have a simple project ‘GradleEx1″ with the following project structure.

The src folder will have a class Hello with the following code.

package com.durasoft;
public class Hello{
	public String sayHello(String name){
		return "Hello " + name;	
	}
}

The tests folder will have a test case HelloTest with the following code.

package com.durasoft;

import org.junit.* ;
import static org.junit.Assert.* ;

public class HelloTest{

	private Hello helloObj = new Hello();
	
	@Test
	public void testSayHello(){
		assertEquals(helloObj.sayHello("Sam"),"Hello Sam");
	}
}

Let’s create a build script build.gradle in the GradleEx1 folder. This gradle file will have a groovy script where you will specify the tasks compile, run tests and package them in a jar file. While doing that you will also add reference to JUnit library.

The build.gradle file is shown below.

apply plugin:'java'

version = "1.0"

repositories {
  mavenCentral()
}
 
dependencies {
  testCompile group: 'junit', name: 'junit', version: '4.8+'
}

sourceSets {
	main {
		java {
			srcDir "src"
		}
	}
	test {
		java {
			srcDir "tests"
		}
	}
}

Is that all??? Yes. All I have done is specify the source folders and the dependencies from maven repository. So what about the compile, run tests, jar etc? The single line apply plugin:’java’ does the trick. It gives you built-in tasks like compileJava, test, jar etc., associated with any ANT build. Here’s where the ‘convention over configuration’ paradigm of Groovy/Grails comes into picture.

So how do we run this? Go to command prompt and run gradle test from GradleEx1 folder.

You can also run gradle jar to create GradleEx1-1.0.jar file. Have a look at the build folder generated in GradleEx1 folder.
Gradle is pretty simple and straightforward and makes use of the DSL capability of Groovy. It’s definitely a welcome change in configuring builds.

Shortlink

Classes in JavaScript

JavaScript is a functional Object-Oriented language. The language’s first class citizens are functions. Functions can be assigned as literals to variables as shown below.

var workOut = function(calories){
    document.write("Burning " + calories + " calories);
}
workOut(100);

Functions can also be invoked with a new keyword. This feature in JavaScript paves way for writing some traditional Object-Oriented code.
Say you want to create a class with variables and methods in JavaScript, instantiate it just like you do in C#/Java. Let’s create a class Person with name and age attributes and eat method.

  function Person(theName,theAge){
     this.name = theName; //public variable
     this.age = theAge;
     this.eat = function(){
        document.write(this.name + " is eating");
     }
  }

If you want to now create an object of Person and invoke it’s eat method you can use the new keyword similar to other OO languages.

   var p1 = new Person("Sam",23);
   p1.eat();

So what’s going on behind the screens?. We will discuss more about them later.