Posts Tagged ‘lt xml’

English: Logo of Русский: Логотип Apache Tomcat

Setting the JAVA_HOME , CATALINA_HOME Environment Variable on Windows

One can do using command prompt
1. set JAVA_HOME=C:\”top level directory of your java install”
2. set CATALINA_HOME=C:\”top level directory of your Tomcat install”
3. set PATH=%PATH%;%JAVA_HOME%\bin;%CATALINA_HOME%\bin

Or you can do the same

  1. Go to system properties.
  2. Go to environment variables and add a new variable with the name  JAVA_HOME and provide variable value as C:\”top level directory of your java install”.
  3. Go to environment variables and add a new variable with the name  CATALINA_HOME and provide variable value as C:\”top level directory of your Tomcat install”.
  4. In path variable add a new variable value as ;%CATALINA_HOME%\bin;

and write startup.bat on command Prompt and press enter tomcat will start up and for shutdown u just write shutdown.bat        once you start the tomcat you can access it like that http://localhost:8080     and access Application Manager using login and password …. if you dont know username and password you can  follow below instructions ….

User and password for Tomcat

By default, Tomcat does not enable admin or manager access. To enable it, you have to edit the “%TOMCAT_FOLDER%/conf/tomcat-users.xml” manually.

File : tomcat-users.xml (before update) , initially, Tomcat comments all users and roles like above.



<!--
  
  <role rolename="role1"/>
  
  
  
-->

File : tomcat-users.xml (after updated)

<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
<!--
  <role rolename="tomcat"/>
  <role rolename="role1"/>
  <user username="tomcat" password="tomcat" roles="tomcat"/>
  <user username="both" password="tomcat" roles="tomcat,role1"/>
  <user username="role1" password="tomcat" roles="role1"/>
-->
  <role rolename="manager"/>
  <role rolename="admin"/>
  <user username="admin" password="admin" roles="admin,manager"/>
</tomcat-users>

To enable admin access, just update the content like above. Saved it and restart Tomcat, now you can access Tomcat admin or manger pages with user = “admin” and password = “admin“.

Android invasion, Sydney, Australia

In this article I explain a possible cause of android.os.NetworkOnMainThreadException and how to avoid it.
From the Android site you can read:
NetworkOnMainThreadException
The exception that is thrown when an application attempts to perform a networking operation on its main thread.
This is only thrown for applications targeting the Honeycomb SDK or higher…

Here is a sample developed for Gingerbread, API level 9:

  1. create an Android project called HttpClient
  2. edit the file AndroidManifest.xml
    1 <?xml version="1.0" encoding="utf-8"?>
    2 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    3     package="eu.lucazanini.httpclient"
    4     android:versionCode="1"
    5     android:versionName="1.0" >
    6
    7     <uses-sdk android:minSdkVersion="9" />
    8     <uses-permission android:name="android.permission.INTERNET"/>
    9
    10     <application
    11         android:icon="@drawable/ic_launcher"
    12         android:label="@string/app_name" >
    13         <activity
    14             android:name=".HttpClientActivity"
    15             android:label="@string/app_name" >
    16             <intent-filter>
    17                 <action android:name="android.intent.action.MAIN" />
    18
    19                 <category android:name="android.intent.category.LAUNCHER" />
    20             </intent-filter>
    21         </activity>
    22     </application>
    23
    24 </manifest>

    where <uses-sdk android:minSdkVersion=”9″ /> means an API version earlier to Honeycomb (Gingerbread, API level 9), and <uses-permission android:name=”android.permission.INTERNET”/> authorizes the application to perform an internet connection

  3. edit the file HttpClientActivity.java
    1 package eu.lucazanini.httpclient;
    2
    3 import java.io.IOException;
    4
    5 import org.apache.http.HttpResponse;
    6 import org.apache.http.client.ClientProtocolException;
    7 import org.apache.http.client.methods.HttpGet;
    8 import org.apache.http.impl.client.DefaultHttpClient;
    9
    10 import android.app.Activity;
    11 import android.os.Bundle;
    12 import android.util.Log;
    13
    14 public class HttpClientActivity extends Activity {
    15
    16     @Override
    17     public void onCreate(Bundle savedInstanceState) {
    18         super.onCreate(savedInstanceState);
    19         setContentView(R.layout.main);
    20
    21         connect();
    22
    23     }
    24
    25     private void connect() {
    26         try {
    27             DefaultHttpClient client = new DefaultHttpClient();
    28             HttpGet request = new HttpGet("http://www.google.com");
    29             HttpResponse response = client.execute(request);
    30         } catch (ClientProtocolException e) {
    31             Log.d("HTTPCLIENT", e.getLocalizedMessage());
    32         } catch (IOException e) {
    33             Log.d("HTTPCLIENT", e.getLocalizedMessage());
    34         }
    35     }
    36
    37 }

This app is executed without errors.

If you specify an API level after Honeycomb, such as Ice Cream Sandwich, replacing the line <uses-sdk android:minSdkVersion=”9″ /> with <uses-sdk android:minSdkVersion=”14″ /> and you launch the application, you get the exception android.os.NetworkOnMainThreadException.

An easy way to avoid the exception is to insert the following code (which requires import android.os.StrictMode):

1 StrictMode.ThreadPolicy policy = new
2 StrictMode.ThreadPolicy.Builder()
3 .permitAll().build();
4 StrictMode.setThreadPolicy(policy);

before the row connect() in HttpClientActivity.java
But this method is recommended in development environments only, the recommended method is to use the class AsyncTask.

An example is the following in which the code of the class HttpClientActivity.java is replaced by:

1 package eu.lucazanini.httpclient;
2
3 import java.io.IOException;
4
5 import org.apache.http.HttpResponse;
6 import org.apache.http.client.ClientProtocolException;
7 import org.apache.http.client.methods.HttpGet;
8 import org.apache.http.impl.client.DefaultHttpClient;
9
10 import android.app.Activity;
11 import android.os.AsyncTask;
12 import android.os.Bundle;
13 //import android.os.StrictMode;
14 import android.util.Log;
15
16 public class HttpClientActivity extends Activity {
17     /** Called when the activity is first created. */
18     @Override
19     public void onCreate(Bundle savedInstanceState) {
20         super.onCreate(savedInstanceState);
21         setContentView(R.layout.main);
22
23 //      StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
24 //              .permitAll().build();
25 //      StrictMode.setThreadPolicy(policy);
26
27 //      connect();
28
29         new Connection().execute();
30
31     }
32
33     private class Connection extends AsyncTask {
34
35         @Override
36         protected Object doInBackground(Object... arg0) {
37             connect();
38             return null;
39         }
40
41     }
42
43     private void connect() {
44         try {
45             DefaultHttpClient client = new DefaultHttpClient();
46             HttpGet request = new HttpGet("http://www.google.com");
47             HttpResponse response = client.execute(request);
48         } catch (ClientProtocolException e) {
49             Log.d("HTTPCLIENT", e.getLocalizedMessage());
50         } catch (IOException e) {
51             Log.d("HTTPCLIENT", e.getLocalizedMessage());
52         }
53     }
54
55 }

You can override not only doInBackground but also other methods of the AsyncTask class like OnPreExecute(), OnPostExecute(Result), publishProgress(Progress. ..).

Spring Interceptors : It has the ability to pre-handle and post-handle the web requests.

Struts.xml:


<?xml version="1.0" encoding="UTF-8"?>

<!--DOCTYPE struts PUBLIC
 "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
 "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
 <include file="struts-default.xml" />
 <package name="default" extends="struts-default">
     <interceptors>
        <interceptor name="bean-scope"/>
        <interceptor name="params"
           />
        <interceptor name="userAuthentication"
           />

        <interceptor-stack name="authStach">
           <interceptor-ref name="bean-scope"/>
           <interceptor-ref name="userAuthentication"/>
           <interceptor-ref name="defaultStack"/>
        </interceptor-stack>
     </interceptors>

     <action name="myProfile"class="com.myproject.application.action.EntrepreneurAction"
                method="profile">
        <interceptor-ref name="authStach"/>
        <result name="success" type="tiles" >pages/myProfile.jsp</result>
     </action>
 </package>
</struts>


package com.myproject.application.interceptor;

import com.myproject.application.model.User;

public class AllRoleAuthenticationInterceptor extends UserAuthenticationInterceptor {

    private static final long serialVersionUID = -5932013298987566795L;
    @Override
    public boolean isAllowed(User user) {
      return true;
    }
}


package com.myproject.application.interceptor;

import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import com.cofundit.application.action.constants.ActionConstants;
import com.cofundit.application.model.User;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/**
* A base class for authenticating all the users.
* Needs to override the isAllowed method to control the access
*/
public class UserAuthenticationInterceptor extends AbstractInterceptor{

   private static final long serialVersionUID = 6487648946271825850L;
   @Override
   public String intercept(ActionInvocation invocation) throws Exception {
      Map<string, object=""> session = invocation.getInvocationContext().getSession();
      User user = (User) session.get(“user”);
      User adminUser=(User) session.get(”ADMIN_USER”);
      if ((user != null && isAllowed(user)) || (adminUser != null && isAllowed(adminUser))) {
         invocation.invoke();
      }
      HttpServletRequest request = ServletActionContext.getRequest();
      String requestedUrl = request.getRequestURL().toString();
      if (request.getQueryString() != null) {
         requestedUrl += "?" + request.getQueryString();
      }
      session.put(”last_requested_url”, requestedUrl);
      return "user_login";
   }

   public boolean isAllowed(User user){
     return false;
   }
}

It would be safe to say that nearly every mobile phone sold in the past decade has SMS messaging capabilities. In fact, SMS messaging is one great killer application for the mobile phone and it has created a steady revenue stream for mobile operators. Understanding how to use SMS messaging in your application can provide you with many ideas to create the next killer application.

 

In this article, we take a look at how you can programmatically send and receive SMS messages in your Android applications

 

English: SMS message received on a Motorola RA...

 

. The good news for Android developers is that you don’t need a real device to test out SMS messaging – the free Android emulator provides the capability to do so.

 

Sending SMS Messages

 

To get started, first launch Eclipse and create a new Android project. Name the project as shown in Figure 1.

 


Figure 1 Creating a new Android project using Eclipse

 

Android uses a permission-based policy where all the permissions needed by an application need to be specified in the AndroidManifest.xml file. By doing so, when the application is installed it will be clear to the user what specific access permissions are required by the application. For example, as sending SMS messages will potentially incur additional cost on the user’s end, indicating the SMS permissions in the AndroidManifest.xml file will let the user decide whether to allow the application to install or not.

 

In the AndroidManifest.xml file, add the two permissions – SEND_SMS and RECEIVE_SMS:

 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="net.learn2develop.SMSMessaging"
      android:versionCode="1"
      android:versionName="1.0.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".SMS"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
    <uses-permission android:name="android.permission.SEND_SMS">
    </uses-permission>
    <uses-permission android:name="android.permission.RECEIVE_SMS">
    </uses-permission>
</manifest>

 

In the main.xml file located in the res/layout folder, add the following code so that the user can enter a phone number as well as a message to send:

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <TextView  
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:text="Enter the phone number of recipient"
        />     
    <EditText 
        android:id="@+id/txtPhoneNo"  
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content"        
        />
    <TextView  
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content"         
        android:text="Message"
        />     
    <EditText 
        android:id="@+id/txtMessage"  
        android:layout_width="fill_parent" 
        android:layout_height="150px"
        android:gravity="top"         
        />          
    <Button 
        android:id="@+id/btnSendSMS"  
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content"
        android:text="Send SMS"
        />    
</LinearLayout>

 

The above code creates the UI shown in Figure 2.

 


Figure 2 Creating the UI for sending SMS messages

 

Next, in the SMS activity, we wire up the Button view so that when the user clicks on it, we will check to see that the phone number of the recipient and the message is entered before we send the message using the sendSMS() function, which we will define shortly:

 

package net.learn2develop.SMSMessaging;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.gsm.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class SMS extends Activity 
{
    Button btnSendSMS;
    EditText txtPhoneNo;
    EditText txtMessage;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);        

        btnSendSMS = (Button) findViewById(R.id.btnSendSMS);
        txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo);
        txtMessage = (EditText) findViewById(R.id.txtMessage);

        btnSendSMS.setOnClickListener(new View.OnClickListener() 
        {
            public void onClick(View v) 
            {                
                String phoneNo = txtPhoneNo.getText().toString();
                String message = txtMessage.getText().toString();                 
                if (phoneNo.length()>0 && message.length()>0)                
                    sendSMS(phoneNo, message);                
                else
                    Toast.makeText(getBaseContext(), 
                        "Please enter both phone number and message.", 
                        Toast.LENGTH_SHORT).show();
            }
        });        
    }    
}

 

The sendSMS() function is defined as follows:

 

public class SMS extends Activity 
{
    //...

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        //...
    }

    //---sends an SMS message to another device---
    private void sendSMS(String phoneNumber, String message)
    {        
        PendingIntent pi = PendingIntent.getActivity(this, 0,
            new Intent(this, SMS.class), 0);                
        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber, null, message, pi, null);        
    }    
}

 

To send an SMS message, you use the SmsManager class. Unlike other classes, you do not directly instantiate this class; instead you will call the getDefault() static method to obtain an SmsManager object. The sendTextMessage() method sends the SMS message with a PendingIntent. The PendingIntent object is used to identify a target to invoke at a later time. For example, after sending the message, you can use a PendingIntent object to display another activity. In this case, the PendingIntent object (pi) is simply pointing to the same activity (SMS.java), so when the SMS is sent, nothing will happen.

 

If you need to monitor the status of the SMS message sending process, you can actually use two PendingIntent objects together with two BroadcastReceiver objects, like this:

 

    //---sends an SMS message to another device---
    private void sendSMS(String phoneNumber, String message)
    {        
        String SENT = "SMS_SENT";
        String DELIVERED = "SMS_DELIVERED";

        PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
            new Intent(SENT), 0);

        PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
            new Intent(DELIVERED), 0);

        //---when the SMS has been sent---
        registerReceiver(new BroadcastReceiver(){
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode())
                {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), "SMS sent", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                        Toast.makeText(getBaseContext(), "Generic failure", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NO_SERVICE:
                        Toast.makeText(getBaseContext(), "No service", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NULL_PDU:
                        Toast.makeText(getBaseContext(), "Null PDU", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_RADIO_OFF:
                        Toast.makeText(getBaseContext(), "Radio off", 
                                Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        }, new IntentFilter(SENT));

        //---when the SMS has been delivered---
        registerReceiver(new BroadcastReceiver(){
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode())
                {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), "SMS delivered", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case Activity.RESULT_CANCELED:
                        Toast.makeText(getBaseContext(), "SMS not delivered", 
                                Toast.LENGTH_SHORT).show();
                        break;                        
                }
            }
        }, new IntentFilter(DELIVERED));        

        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);        
    }

 

The above code uses a PendingIntent object (sentPI) to monitor the sending process. When an SMS message is sent, the first BroadcastReceiver‘s onReceive event will fire. This is where you check the status of the sending process. The second PendingIntent object (deliveredPI) monitors the delivery process. The second BroadcastReceiver‘s onReceive event will fire when an SMS is successfully delivered.

 

You can now test the application by pressing F11 in Eclipse. To send an SMS message from one emulator instance to another, simply launch another instance of the Android emulator by going to the Tools folder of the SDK and running Emulator.exe.

 


Figure 3 Sending an SMS message

 

Figure 3 shows how you can send an SMS message from one emulator to another; simply use the target emulator’s port number (shown in the top left corner of the window) as its phone number. When an SMS is sent successfully, it will display a “SMS sent” message. When it is successfully delivered, it will display a “SMS delivered” message. Note that for testing using the emulator, when an SMS is successfully delivered, the “SMS delivered” message does not appear; this only works for real devices.

 

Figure 4 shows the SMS message received on the recipient emulator. The message first appeared in the notification bar (top of the screen). Dragging down the notification bar reveals the message received. To view the entire message, click on the message.

 


Figure 4 The SMS message received by the Android emulator

 

If you do not want to go through all the trouble of sending the SMS message yourself, you can use an Intent object to help you send an SMS message. The following code shows how you can invoke the built-in SMS application to help you send an SMS message:

 

        Intent sendIntent = new Intent(Intent.ACTION_VIEW);
        sendIntent.putExtra("sms_body", "Content of the SMS goes here..."); 
        sendIntent.setType("vnd.android-dir/mms-sms");
        startActivity(sendIntent);

 

Figure 5 shows the built-in SMS application invoked to send the SMS message.

 


Figure 5 Invoking the built-in SMS application

 

Receiving SMS Messages

 

Besides programmatically sending SMS messages, you can also intercept incoming SMS messages using a BroadcastReceiver object.

 

To see how to receive SMS messages from within your Android application, in the AndroidManifest.xml file add the <receiver> element so that incoming SMS messages can be intercepted by the SmsReceiver class:

 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="net.learn2develop.SMSMessaging"
      android:versionCode="1"
      android:versionName="1.0.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".SMS"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>        

        <receiver android:name=".SmsReceiver"> 
            <intent-filter> 
                <action android:name=
                    "android.provider.Telephony.SMS_RECEIVED" /> 
            </intent-filter> 
        </receiver>

    </application>
    <uses-permission android:name="android.permission.SEND_SMS">
    </uses-permission>
    <uses-permission android:name="android.permission.RECEIVE_SMS">
    </uses-permission>
</manifest>

 

Add a new class file to your project and name it as SmsReceiver.java (see Figure 6).

 


Figure 6Adding the SmsReceiver.java file to the project

 

In the SmsReceiver class, extend the BroadcastReceiver class and override the onReceive() method:

 

package net.learn2develop.SMSMessaging;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class SmsReceiver extends BroadcastReceiver
{
	@Override
	public void onReceive(Context context, Intent intent) 
       {	
	}
}

 

When SMS messages are received, the onCreate() method will be invoked. The SMS message is contained and attached to the Intent object (intent – the second parameter in the onReceive() method) via a Bundle object. The messages are stored in an Object array in the PDU format. To extract each message, you use the static createFromPdu() method from the SmsMessage class. The SMS message is then displayed using the Toast class:

 

package net.learn2develop.SMSMessaging;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.gsm.SmsMessage;
import android.widget.Toast;public class SmsReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent) 
    {
        //---get the SMS message passed in---
        Bundle bundle = intent.getExtras();        
        SmsMessage[] msgs = null;
        String str = "";            
        if (bundle != null)
        {
            //---retrieve the SMS message received---
            Object[] pdus = (Object[]) bundle.get("pdus");
            msgs = new SmsMessage[pdus.length];            
            for (int i=0; i<msgs.length; i++){
                msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);                
                str += "SMS from " + msgs[i].getOriginatingAddress();                     
                str += " :";
                str += msgs[i].getMessageBody().toString();
                str += "\n";        
            }
            //---display the new SMS message---
            Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
        }                         
    }
}

 

That’s it! To test the application, press F11 in Eclipse. Deploy the application to each Android emulator. Figure 7 shows Eclipse showing the emulators currently running. All you need to do is to select each emulator and deploy the application onto each one.

 


Figure 7 Selecting an emulator/device to deploy the application onto

 

Figure 8 shows that when you send an SMS message to another emulator instance (port number 5556), the message is received by the target emulator and displayed via the Toast class.

 


Figure 8 Sending and receiving SMS messages using the Android emulators

 

Summary

 

In this article, you have seen how you can send and receive SMS messages programmatically from within your Android application. The capability to send and receive SMS messages is very useful as you can build very compelling applications. As an example, you can build a location tracker application where you can send a secret-coded SMS message to a device and when the device receives the secret SMS message it will reply with another SMS message containing its current geographical location using its built-in GPS receiver. How cool is that?!

 

Click the link below to download project source code

 

Attachment Size
SMSMessaging.zip 35.43 KB

 

Poor little android.. Dwarfed by Apple Devices...

 

While working on an Android App, I had to integrate the Camera API. User can take a photo from App and process it. With Android the Photo that you click cannot be accessed until the media scanner runs and index it. It is possible to triggeer programatically the Media Scanner in Android. Check the below code snippet:

 

import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
...
...
sendBroadcast (
    new Intent(Intent.ACTION_MEDIA_MOUNTED,
        Uri.parse("file://" + Environment.getExternalStorageDirectory()))
);
...

 

Here we are using sendBroadcast method from Activity class to send a broadcast message to an Intent. For our need we have used ACTION_MEDIA_MOUNTED intent which will invoke the media scanner. Also note that we have passed the path (URI) of our external storage directory.

 

So in your app whenever you want to trigger Media scanner, simply invoke the above intent via broadcast message.

 

Following is a Demo App to achieve this.

 

Demo App

 

The App will be very simple. It will have a button “Trigger Media Scanner”. On its click we will invoke the above sendBroadcast() code to trigger media scanner.

 

Step 1: Create Basic Android Project in Eclipse

 

Create a Hello World Android project in Eclipse. Go to New > Project > Android Project. Give the project name as MediaScannerDemo and select Android Runtime 2.1 or sdk 7. I have given package name net.viralpatel.android.mediascanner.

 

Once you are done with above steps, you will have a basic hello world Android App.

 

Step 2: Change the Layout

 

For our demo, we need simple layout. Just one button Trigger Image Scanner which does the job.

 

Open layout/main.xml in your android project and replace its content with following:

 

File: res/layout/main.xml

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center">
    
    <Button
            android:id="@+id/buttonMediaScanner"
            android:layout_width="fill_parent"
            android:text="Trigger Media Scanner"
            android:textSize="25dp"
            android:layout_height="100dp"></Button>
</LinearLayout>

 

The UI is very simply. One LinearLayout to organize the button and one button. Note the id for button buttonMediaScanner which we will use in our Java code.

 

Step 3: Android Java Code to trigger Image Scanner Intent

 

Open MediaScannerDemoActivity class and add following code in OnCreate() method.

 

package net.viralpatel.android.mediascanner;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MediaScannerDemoActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button buttonMediaScanner = (Button) findViewById(R.id.buttonMediaScanner);
        
        //Add onClick event on Media scanner button
        buttonMediaScanner.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                
                //Broadcast the Media Scanner Intent to trigger it
                sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri
                        .parse("file://"
                                + Environment.getExternalStorageDirectory())));
                //Just a message
                Toast toast = Toast.makeText(getApplicationContext(),
                        "Media Scanner Triggered...", Toast.LENGTH_SHORT);
                toast.show();
            }
        });
    }
}

 

Thus in OnCreate() method, we have added an OnClickListener to button. In the listener class, we added logic to trigger media scanner and also a Toast message to show user that scanner has been triggered.

 

Screen shots of Android App

 

And that’s all! Just execute the app in Android emulator or real device and see following output.

 

android-media-scanner-trigger

 

On click of Trigger Media Scanner button, the media scanner is invoked which we can see in Title bar.
android media-scanner-app

 

Download Source Code

 

MediaScannerDemo.zip (45 KB)

 

English: Iceland, from the NASA Visible Earth ...

To start with let us see how to integrate Image Gallery with your App. Consider a requirement, you want your app user to select Image from the Gallery and use that image to do some stuff. For example, in Facebook app you can select Picture from your phone and upload directly to your profile.

Let us create an example with following requirement:

  1. First screen shows user with and Image view and a button to loan Picture.
  2. On click of “Load Picture” button, user will be redirected to Android’s Image Gallery where she can select one image.
  3. Once the image is selected, the image will be loaded in Image view on main screen.

So lets start.

Step 1: Create Basic Android Project in Eclipse

Create a Hello World Android project in Eclipse. Go to New > Project > Android Project. Give the project name as ImageGalleryDemo and select Android Runtime 2.1 or sdk 7.

Once you are done with above steps, you will have a basic hello world Android App.

Step 2: Change the Layout

For our demo, we need simple layout. One Image view to display user selected image and one button to trigger Image gallery.

Open layout/main.xml in your android project and replace its content with following:

File: res/layout/main.xml

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <ImageView
        android:id="@+id/imgView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"></ImageView>
    <Button
        android:id="@+id/buttonLoadPicture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0"
        android:text="Load Picture"
        android:layout_gravity="center"></Button>
</LinearLayout>

So our Android’s app UI is very simple, One LinearLayout to organize Image view and Button linearly. Note that the id of Image view is imgView and that of Button is buttonLoadPicture.

Step 3: Android Java Code to trigger Image Gallery Intent

We now need to write some Java code to actually handle the button click. On click of buttonLoadPicture button, we need to trigger the intent for Image Gallery.

Thus, on click of button we will trigger following code:

1
2
3
4
Intent i = new Intent(
Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);

Note how we passed an integer RESULT_LOAD_IMAGE to startActivityForResult() method. This is to handle the result back when an image is selected from Image Gallery.

So the above code will trigger Image Gallery. But how to retrieve back the image selected by user in our main activity?

Step 4: Getting back selected Image details in Main Activity

Once user will select an image, the method onActivityResult() of our main activity will be called. We need to handle the data in this method as follows:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
     super.onActivityResult(requestCode, resultCode, data);
     
     if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
         Uri selectedImage = data.getData();
         String[] filePathColumn = { MediaStore.Images.Media.DATA };
         Cursor cursor = getContentResolver().query(selectedImage,
                 filePathColumn, null, null, null);
         cursor.moveToFirst();
         int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
         String picturePath = cursor.getString(columnIndex);
         cursor.close();
                     
         // String picturePath contains the path of selected Image
     }

Note that method onActivityResult gets called once an Image is selected. In this method, we check if the activity that was triggered was indeed Image Gallery (It is common to trigger different intents from the same activity and expects result from each). For this we used RESULT_LOAD_IMAGE integer that we passed previously to startActivityForResult() method.

Final Code

Below is the final code of ImageGalleryDemoActivity class.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package net.viralpatel.android.imagegalleray;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class ImageGalleryDemoActivity extends Activity {
    
    
    private static int RESULT_LOAD_IMAGE = 1;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        Button buttonLoadImage = (Button) findViewById(R.id.buttonLoadPicture);
        buttonLoadImage.setOnClickListener(new View.OnClickListener() {
            
            @Override
            public void onClick(View arg0) {
                
                Intent i = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                
                startActivityForResult(i, RESULT_LOAD_IMAGE);
            }
        });
    }
    
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        
        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };
            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();
            
            ImageView imageView = (ImageView) findViewById(R.id.imgView);
            imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
        
        }
    
    
    }
}

Screen shots of Android app

First screen: Lets user to trigger Image Gallery
android-gallery-intent-example

User can select an image from Image Gallery
android-gallery-intent-select-image

Once user selects an image, the same will be displayed on our main activity
android-gallery-intent-example-demo

Download Source Code

ImageGalleryDemo.zip (46 KB)

JPOs printed clone legs

OK after my article about ISO 8583 let’s go deeper into programming using Java + JPOS library.

Quote from JPOS website:

jPOS is a Java® platform-based, mission-critical, ISO-8583 based financial transaction library/framework that can be customized and extended in order to implement financial interchanges.

So first thing to do is download JPOS from it website.

Then we setup our development environment by creating Java Project using your favorites IDE. Add to the project all jar in JPOS library.
Here’s my Eclipse  package explorer looks like.

package explorer

package explorer

 

Read More »

 

Android Robot. Français : le logo d'android 日本...

In this tutorial, you will learn how to use Eclipse to create an Android JUnit Test Project, create automated unit tests and run them under a variety of conditions.

Before You Begin

The authors are assuming the reader has some basic knowledge of Android and have all of the tools such as Eclipse and the Android SDK installed and working. The examples given here are engineered to show how the Android JUnit framework can be used to test Android applications. Specifically, this tutorial will show you how to test aspects of an Activity and identify program errors. These errors are determined, but not addressed, as part of this tutorial.

Note: The code for the SimpleCalc application is available on Google Code as well as from the above link.

Step 1: Review the SimpleCalc Application

First, let’s take a few moments to look over the SimpleCalc application. It’s a very simple application with just one screen. The screen has two simple functions: it allows the user to input two values, adds or multiplies these values together and displays the result as shown below.

Junit Testing The SimpleCalc application

Step 2: Review the SimpleCalc Screen Layout

The SimpleCalc application has just one screen, so we have only one layout resource file called /res/layout/main.xml.

Here is a listing of the main.xml layout resource:
  1. <?xml version=”1.0″ encoding=”utf-8″?>
  2. <LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android&#8221;
  3.     android:orientation=”vertical” android:layout_width=”fill_parent”
  4.     android:layout_height=”fill_parent”>
  5.     <TextView android:layout_width=”fill_parent”
  6.         android:layout_height=”wrap_content” android:text=”@string/hello”
  7.         android:gravity=”center_horizontal” android:textSize=”48px”
  8.         android:padding=”12px” />
  9.     <EditText android:layout_height=”wrap_content” android:id=”@+id/value1″
  10.         android:hint=”@string/hint1″ android:inputType=”numberDecimal”
  11.         android:layout_width=”fill_parent” android:textSize=”48px”></EditText>
  12.     <EditText android:layout_height=”wrap_content” android:id=”@+id/value2″
  13.         android:hint=”@string/hint2″ android:inputType=”numberDecimal”
  14.         android:layout_width=”fill_parent” android:textSize=”48px”></EditText>
  15.     <FrameLayout android:id=”@+id/FrameLayout01″
  16.         android:layout_width=”wrap_content” android:layout_height=”wrap_content”
  17.         android:padding=”12px” android:background=”#ff0000″>
  18.         <LinearLayout android:id=”@+id/LinearLayout02″
  19.             android:layout_width=”wrap_content” android:layout_height=”wrap_content”
  20.             android:orientation=”horizontal” android:background=”#000000″
  21.             android:padding=”4px”>
  22.             <TextView android:layout_width=”wrap_content”
  23.                 android:layout_height=”wrap_content” android:text=”@string/resultLabel”
  24.                 android:textSize=”48px” android:id=”@+id/resultLabel”></TextView>
  25.             <TextView android:layout_width=”wrap_content”
  26.                 android:layout_height=”wrap_content” android:id=”@+id/result”
  27.                 android:textSize=”48px” android:textStyle=”bold”
  28.                 android:layout_marginLeft=”16px”></TextView>
  29.         </LinearLayout>
  30.     </FrameLayout>
  31.     <LinearLayout android:id=”@+id/LinearLayout03″
  32.         android:layout_height=”wrap_content” android:layout_width=”fill_parent”>
  33.         <Button android:layout_height=”wrap_content” android:id=”@+id/addValues”
  34.             android:text=”@string/add” android:textSize=”32px”
  35.             android:layout_width=”wrap_content”></Button>
  36.         <Button android:layout_height=”wrap_content” android:id=”@+id/multiplyValues”
  37.             android:text=”@string/multiply” android:textSize=”32px”
  38.             android:layout_width=”wrap_content”></Button>
  39.     </LinearLayout>
  40. </LinearLayout>

This layout is fairly straightforward. The entire content of the screen is stored within a LinearLayout, allowing the controls to display one after another vertically. Within this parent layout, we have the following controls:

  • A TextView control displaying the header “Unit Testing Sample.”
  • Two EditText controls to collect user input in the form of two numbers.
  • A FrameLayout control which contains a horizontal LinearLayout with the result label TextView and resulting sum or product TextView. The FrameLayout displays a red border around these controls, highlighting the result.
  • Finally, another horizontal LinearLayout with two child controls: a Button control for addition and a Button control for multiplication.

This layout is designed to look right in the Android Layout Designer when the Nexus One option (which has a screen size of 800×480) is chosen in both portrait and landscape modes. You’ll soon see that this is not a bullet-proof way of designing layouts. As with the code you’ll see in the next step, it isn’t designed to work perfectly.

Step 3: Review the SimpleCalc Activity

The SimpleCalc application has just one screen, so we have only one Activity as well: MainActivity.java. The MainActivity.java class controls the behavior of the one screen, whose user interface is dictated by the main.xml layout.

Here is a listing of the MainActivity.java class:

  1. package com.mamlambo.article.simplecalc;
  2. import android.app.Activity;
  3. import android.os.Bundle;
  4. import android.util.Log;
  5. import android.view.View;
  6. import android.view.View.OnClickListener;
  7. import android.widget.Button;
  8. import android.widget.EditText;
  9. import android.widget.TextView;
  10. public class MainActivity extends Activity {
  11.    /** Called when the activity is first created. */
  12.    @Override
  13.    public void onCreate(Bundle savedInstanceState) {
  14.        final String LOG_TAG = “MainScreen”;
  15.        super.onCreate(savedInstanceState);
  16.        setContentView(R.layout.main);
  17.        final EditText value1 = (EditText) findViewById(R.id.value1);
  18.        final EditText value2 = (EditText) findViewById(R.id.value2);
  19.        final TextView result = (TextView) findViewById(R.id.result);
  20.        Button addButton = (Button) findViewById(R.id.addValues);
  21.        addButton.setOnClickListener(new OnClickListener() {
  22.            public void onClick(View v) {
  23.                try {
  24.                    int val1 = Integer.parseInt(value1.getText().toString());
  25.                    int val2 = Integer.parseInt(value2.getText().toString());
  26.                    Integer answer = val1 + val2;
  27.                    result.setText(answer.toString());
  28.                } catch (Exception e) {
  29.                    Log.e(LOG_TAG, “Failed to add numbers”, e);
  30.                }
  31.            }
  32.        });
  33.        Button multiplyButton = (Button) findViewById(R.id.multiplyValues);
  34.        multiplyButton.setOnClickListener(new OnClickListener() {
  35.            public void onClick(View v) {
  36.                try {
  37.                    int val1 = Integer.parseInt(value1.getText().toString());
  38.                    int val2 = Integer.parseInt(value2.getText().toString());
  39.                    Integer answer = val1 * val2;
  40.                    result.setText(answer.toString());
  41.                } catch (Exception e) {
  42.                    Log.e(LOG_TAG, “Failed to multiply numbers”, e);
  43.                }
  44.            }
  45.        });
  46.    }
  47. }
As you can see, the Java for this class is quite straightforward. It simply implements onClick() handlers for both the addition and multiplication Button controls.

When a Button is pressed, the Activity retrieves the values stored in the two EditText controls, calculates the result, and displays it in the TextView control called R.id.result.

Note: There are bugs in this code! These bugs have been designed specifically to illustrate unit testing.

Step 4: Creating an Android Test Project

You can add a test project to any Android project in two ways. You can add a test project while creating a new Android project with the Android Project Wizard or you can add a test project to an existing Android project. (The steps are basically the same.)

For this example, we have an existing project. To add a test project to the SimpleCalc project in Eclipse, take the following steps:

From the Project Explorer, choose the Android project you wish to add a test project to. Right-click on the project and choose Android Tools->New Test Project…

Junit Testing, Creating a Test Project

Step 5: Configuring the Android Test Project

Now you need to configure the test project settings, including the test project name, file location, Android project to test and build target (SDK version).

For this example, we can use the following settings:

  • Test project names generally end in “Test”, so let’s name this test project SimpleCalcTest
  • The project location can be wherever you normally store source files on your hard drive.
  • Choose the Android project to test: SimpleCalc
  • The appropriate build target will be selected automatically once you select the project to test. In this case, since the Android project is built for Android 2.1 + Google APIs (API Level 7), it makes sense to use the same build target for the test project.
  • It makes sense to name the test project accordingly: SimpleCalcTest, with the appropriate package name suffix simplecalc.test.
Configuring the project test

Hit Finish.

Step 6: Review the SimpleCalcTest Project

The SimpleCalcTest project is an Android project. You will notice that it has all the normal things you’d expect of an Android project, including a Manifest file and resources.

Junit Testing SimpleCalcTest Project Files

Step 7: Determine Unit Tests for the SimpleCalc Application

Now that you have a test project configured for the SimpleCalc application, it makes sense to determine some reasonable unit tests for the application.

Many software methodologies these days work compatibly with unit testing. Unit tests can greatly increase the stability and quality of your application and reduce testing costs. Unit tests come in many forms.

Unit tests can:

  • Improve testing coverage
  • Test application assumptions
  • Validate application functionality

Unit tests can be used to test core functionality, such as whether or not the SimpleCalc math is being performed correctly. They can also be used to verify if the user interface is displaying correctly. Now let’s look at some specific test cases.

Step 8: Create Your First Test Case

To create your first test case, right-click on the simplecalc.test package and choose New->JUnit Test Case.

Configuring test case settings.

Step 9: Configure Your First Test Case

Now you need to configure the test case settings.

For this example, we can use the following settings:

  • Both JUnit 3 and 4 are supported. We’ll use the default JUnit 3 here.
  • The source folder should be the location of the SimpleCalcTest project files.
  • The package should be the package name of the SimpleCalcTest project.
  • In this case, we will name the test case MathValidation.
  • For the SuperClass, choose “android.test.ActivityInstrumentationTestCase2.” This is the test case you use for testing activities.
  • Check the boxes to add method stubs for setUp() and constructor.
junit Testing, Configuring test case settings.

Hit Finish. (You can safely ignore the warning saying, “Superclass does not exist.”)

Step 10: Review the MathValidation Test Case

The MathValidation.java test case source file is then created.

The lifecycle of a test case is basically this: construction, setUp(), tests run, tearDown(), and destruction. The setUp() method is used to do any general initialization used by all of specific tests. Each test to be run in the test case is implemented as its own method, where the method name begins with “test”. The tearDown() method is then used to uninitialize any resources acquired by the setUp() method.

  1. package com.mamlambo.article.simplecalc.test;
  2. import android.test.ActivityInstrumentationTestCase2;
  3. public class MathValidation extends
  4.        ActivityInstrumentationTestCase2<MainActivity> {
  5.    public MathValidation(String name) {
  6.        super(name);
  7.    }
  8.    protected void setUp() throws Exception {
  9.        super.setUp();
  10.    }
  11. }

Now it’s time to implement the MathValidation Test Case

Step 11: Modify the MathValidation Class Constructor

First, modify the MathValidation class constructor. This constructor ties configures the internals of the Android test superclass we’re using.

  1. public MathValidation() {
  2.        super(“com.mamlambo.article.simplecalc”, MainActivity.class);
  3. }

Step 12: Implement the MathValidation setUp() method

Now you need to gather the data required for validating the SimpleCalc math calculations. Begin by implementing the setUp() method. You can retrieve the Activity being tested using the getActivity() method as follows:

  1. MainActivity mainActivity = getActivity();

Next, you need to retrieve an instance of the TextView control called R.id.result. This is the control that will hold the resulting sum or product from the math calculations used by the application.

The full updated code listing (MathValidation.java) with these modifications is shown below:

  1. package com.mamlambo.article.simplecalc.test;
  2. import android.test.ActivityInstrumentationTestCase2;
  3. import android.widget.TextView;
  4. import com.mamlambo.article.simplecalc.MainActivity;
  5. import com.mamlambo.article.simplecalc.R;
  6. public class MathValidation extends ActivityInstrumentationTestCase2<MainActivity> {
  7.    private TextView result;
  8.    public MathValidation() {
  9.        super (“com.mamlambo.article.simplecalc”, MainActivity.class);
  10.    }
  11.    @Override
  12.    protected void setUp() throws Exception {
  13.        super.setUp();
  14.        MainActivity mainActivity = getActivity();
  15.        result = (TextView) mainActivity.findViewById(R.id.result);
  16.    }
  17. }

Step 13: Consider Tests for the SimpleCalc Application

Now that everything is set up, what tests do you want to perform? Let’s begin by checking the math used by the SimpleCalc application. Specifically, let’s check that the numbers are retrieved correctly, as well as added and multiplied correctly. Did we set the right types for our number values? Are we retrieving and performing mathematical calculations using the correct types?

To answer these questions, we must add some testing code to the MathValidation class. Each specific test will have it’s own method beginning with “test” – the “test” method name prefix is case sensitive! This naming scheme is how JUnit determines what methods to run.

Step 14: Implement a Method to Test SimpleCalc’s Addition

Let’s begin by testing the addition calculation of SimpleCalc. To do this, add a method called testAddValues() to the MathValidation class.

This test will enter two numbers (24 and 74) into the screen and press Enter, which acts as a click on the first Button control which is in focus. Then it will retrieve the sum displayed by the application in the result TextView control and test to see if the result is the expected one (98).

To supply the EditText controls with two numbers to sum, use the sendKeys() method. This method mimics how keys are sent to Android applications. If you use the setText() method of the EditText control to set the text in each control, then you are bypassing the validation of the numeric entry that user’s would encounter. This method of providing key strokes assumes that the focus starts on the first control and that using the Enter key goes to the next one (you’ll see that the enter key is sent at the end of each number). If neither of those assumptions is true, the test will also fail. This is not a bad thing, but it might be failing for the wrong reasons (e.g. focus or layout issues, rather than math issues).

Finally, you use the assertTrue() method to compare the actual result displayed on the screen to the expected result. ). We compare against a string, since the result is displayed as a string. This way, we can also make sure we don’t duplicate any math or type errors in the application logic within the test framework.
Here is the full listing of the testAddValues() method:

  1. private static final String NUMBER_24 = “2 4 ENTER “;
  2. private static final String NUMBER_74 = “7 4 ENTER “;
  3. private static final String ADD_RESULT = “98”;
  4. public void testAddValues() {
  5.    sendKeys(NUMBER_24);
  6.    // now on value2 entry
  7.    sendKeys(NUMBER_74);
  8.    // now on Add button
  9.    sendKeys(“ENTER”);
  10.    // get result
  11.    String mathResult = result.getText().toString();
  12.    assertTrue(“Add result should be 98”, mathResult.equals(ADD_RESULT));
  13. }

Congratulations! You’ve created your first test!

Step 15: Enhancing the Tests for Addition

Now let’s add a few more tests to make sure all different types of numbers can be added, resulting in the display of the proper sum.

Because the activity is launched for each test, you do not need to clear the values or anything like that between tests. You also do not need to change the focus within the form, since it begins at value1. Therefore, you can simplify tests by concatenating key presses together in a single sendKeys() method call, like such:

  1. sendKeys(NUMBER_24 + NUMBER_74 + “ENTER”);

For example, here is the code for the testAddDecimalValues() method, which tests the addition of a decimal value 5.5 with the number 74, which should result in 79.5:

  1. public void testAddDecimalValues() {
  2.        sendKeys(NUMBER_5_DOT_5 + NUMBER_74 + “ENTER”);
  3.        String mathResult = result.getText().toString();
  4.        assertTrue(“Add result should be ” + ADD_DECIMAL_RESULT + ” but was “
  5.                + mathResult, mathResult.equals(ADD_DECIMAL_RESULT));
  6.  }

Similarly, you can perform a test of adding a negative number -22 to the number 74, which should result in a sum of 52. This test is implemented in the testSubtractValues() method, as follows:

  1. public void testAddDecimalValues() {
  2.        sendKeys(NUMBER_5_DOT_5 + NUMBER_74 + “ENTER”);
  3.        String mathResult = result.getText().toString();
  4.        assertTrue(“Add result should be ” + ADD_DECIMAL_RESULT + ” but was “
  5.                + mathResult, mathResult.equals(ADD_DECIMAL_RESULT));
  6.    }

Step 16: Implement a Method to Test SimpleCalc’s Multiplication

It should be quite straightforward to implement a similar test for SimpleCalc’s multiplication called testMuliplyValues().

The only tricky part is that the Multiply Button control is not in focus when we’re done entering the numbers (instead, the Add Button is).
You might think to just call the requestFocus() method on the multiply button. Unfortunately, this won’t work because requestFocus() has to be run on the UI thread in Android. Running methods on the UI Thread can be done as part of a test case, but it’s done asynchronously so you can’t guarantee when it will be complete.

Instead, we’ll again use the sendKeys() method. Since we defined the Multiply Button to always display to the right of the Add Button, we can just send the “DPAD_RIGHT” key followed by “ENTER” to click the Multiply Button.

  1. public void testMultiplyValues() {
  2.    sendKeys(NUMBER_24+NUMBER_74+ ” DPAD_RIGHT ENTER”);
  3.    String mathResult = result.getText().toString();
  4.    assertTrue(“Multiply result should be ” + MULTIPLY_RESULT + ” but was “
  5.            + mathResult, mathResult.equals(MULTIPLY_RESULT));
  6. }

As an exercise, you might try adding more multiplication tests with various sizes of numbers. Try to engineer a test that might fail with the existing code. Can you guess if each test will be successful or not? (Hint: Look at the type of the variable that the string is being converted to.)

Step 17: Running Unit Tests with the Android Emulator or Device

Unit test frameworks such as the one you’re building are Android applications like any other. They must be installed on the emulator or device you wish to test, along with the application to be tested (in this case, SimpleCalc).

To run the unit tests you have created so far from Eclipse, choose the Debug drop down, then Debug As, then Android JUnit Test. Make sure the file you just created is the active file (shown in the window) as that is the test case that will be launched.

junit testing, Debugging JUnit Test

Step 18: Examining the Test Results

The tests may take some time to complete, especially if the emulator was not already running. When the tests have completed, you should see results similar to those shown here:

Junit Testing Examining the Test Results

You’ll notice that all four of the tests you’ve just created run. Two of them are successful, while two of them have failed. Do you know why they’ve failed? (Fixing these calculation bugs is left as a learning exercise for the reader.)

Besides successful tests and failed tests, errors are also shown. A failure is when a tested for assertion fails. An error, on the other hand, is a thrown exception. Errors can either be untested for edge cases or simply mistakes in the testing code. If you have errors, check your testing code carefully to make sure it is working correctly.

Step 19: Create a Test Case for Screen Display Testing

Unit tests need not be limited to validating core functionality such as the addition and multiplication of values. Tests can also validate whether or not a screen layout is displayed properly.

For example, you might want to validate that all of the layout controls display properly on all target screens. The SimpleCalc’s screen was designed in the layout designer in Eclipse for an 800×480 screen in either landscape or portrait mode, but will it work on other screen sizes and devices? Were we then too specific in our design? Automated testing can tell us the answer to this question very quickly.

To create another test case, right-click on the SimpleCalc.Test package and choose New->JUnit Test Case. Call this new test LayoutTests. Configure this test case much as you did the MathValidation class in Step 8.

Junit testing, Create a Test Case for Screen Display Testing.

Hit Finish.

Step 20: Review and Update the LayoutTests Test Case

The LayoutTests.java test case source file is then created. Modify the class to look like the code listing below, modifying the constructor, retrieving the Button controls and the layout as a whole:

  1. package com.mamlambo.article.simplecalc.test;
  2. import android.test.ActivityInstrumentationTestCase2;
  3. import android.view.View;
  4. import android.widget.Button;
  5. import com.mamlambo.article.simplecalc.MainActivity;
  6. import com.mamlambo.article.simplecalc.R;
  7. public class LayoutTests extends ActivityInstrumentationTestCase2<MainActivity> {
  8.    private Button addValues;
  9.    private Button multiplyValues;
  10.    private View mainLayout;
  11.    public LayoutTests() {
  12.        super(“com.mamlambo.article.simplecalc”, MainActivity.class);
  13.    }
  14.    protected void setUp() throws Exception {
  15.        super.setUp();
  16.        MainActivity mainActivity = getActivity();
  17.        addValues = (Button) mainActivity.findViewById(R.id.addValues);
  18.        multiplyValues = (Button) mainActivity
  19.                .findViewById(R.id.multiplyValues);
  20.        mainLayout = (View) mainActivity.findViewById(R.id.mainLayout);
  21.    }
  22. }
Now let’s implement some specific tests for LayoutTests.

Step 20: Consider Layout Tests for the SimpleCalc Application
Now that everything is set up, what tests do you want to perform? One common bug in application design is for controls not to display properly in all screen sizes and orientations. Therefore, it makes sense to try to build a test case to verify the location of certain controls. You can then add other checks to make sure other View controls display and behave appropriately.

Step 21: Implement a Method to Test Button Display

Let’s begin by testing that the Add Button control of the SimpleCalc screen is visible. To do this, add a method called testAddButtonOnScreen() to the LayoutTests class.

This test checks to see if the Add Button control is displayed within the visible rectangle representing the overall screen size.

To implement the testAddButtonOnScreen() method, you must first determine the screen size. There are a number of ways to do this. One simple way is to retrieve the View that represents the entire screen layout and use the getWidth() and getHeight() methods. Doing this also takes in to account any screen real estate being used by other items, such as the title bar or information bar that are often at the top of an Android screen.

Determining whether or not the Add Button control is drawn within those bounds is as simple as comparing the layout bounds to the bounds of the drawing rectangle for the Add Button control.

Here is the full listing of the testAddButtonOnScreen() method:

  1. public void testAddButtonOnScreen() {
  2.    int fullWidth = mainLayout.getWidth();
  3.    int fullHeight = mainLayout.getHeight();
  4.    int[] mainLayoutLocation = new int[2];
  5.    mainLayout.getLocationOnScreen(mainLayoutLocation);
  6.    int[] viewLocation = new int[2];
  7.    addValues.getLocationOnScreen(viewLocation);
  8.    Rect outRect = new Rect();
  9.    addValues.getDrawingRect(outRect);
  10.    assertTrue(“Add button off the right of the screen”, fullWidth
  11.            + mainLayoutLocation[0] > outRect.width() + viewLocation[0]);
  12.    assertTrue(“Add button off the bottom of the screen”, fullHeight
  13.            + mainLayoutLocation[1] > outRect.height() + viewLocation[1]);
  14. }

At this point, you can see how you could also test the display of the Multiply Button, or the Result text, or any other control on the SimpleCalc screen.

Step 22: Running the LayoutTests Test Case

In order for layout testing to provide useful results, we can’t just run the test once. Instead, the tests must be run on multiple emulator configurations and screen orientations. This is different from the logic tests of above where a messy layout or a layout that doesn’t match the design pattern doesn’t necessarily impede functionality.

For example, if you create emulator configurations (using AVDs) for the following configurations, the LayoutTests test case will yield the following results:

  1. 480×800, portrait mode (will pass)
  2. 800×480, landscape mode (will fail)
  3. 320×480, portrait mode (will fail)
  4. 480×320, landscape (will fail)
  5. 480×854, portrait mode (will pass)
  6. 854×480, landscape mode (will fail)

 Can you figure out why it fails in all landscape modes, but draws fine in the creator for the landscape mode (#2 above)?

Can you figure out why it fails in all landscape modes, but draws fine in the creator for the landscape mode (#2 above)?

Hint: What’s shown on the screen when the application actually runs (see the figure below)?

JUnit Testing Sample

Step 23: Where to Go From Here

Now that you have some tests in place—some of which pass and some of which fail—you can imagine how unit testing can improve the quality of your application.

The more thorough you are with your unit testing coverage, the better. You’ve seen how unit testing can uncover bugs in code and layout designs. The next step would be to identify the failure points and fix those bugs. Once you’ve fixed the bugs, you should re-run the unit tests to ensure that they pass in all test cases.

Conclusion

In this tutorial, you learned how to create unit tests using the Android JUnit framework for your Android projects. You also learned how to create different kinds of unit tests to test a variety of application features, including underlying program functions as well as display characteristics.

Image representing Android as depicted in Crun...

Description:
This example shows you how to download a pdf file from server and display its contents.

Algorithm:

1.) Create a new project by File-> New -> Android Project name it PDFFromServerExample.
2.) Write following code into your manifest file:

<?xml version=”1.0″ encoding=”utf-8″?>
<manifest xmlns:android=”http://schemas.android.com/apk/res/android&#8221;
android:versionCode=”1″
android:versionName=”1.0″ package=”com.pdftest”>
<uses-sdk android:minSdkVersion=”7″ />
<uses-permission android:name=”android.permission.INTERNET”></uses-permission>
<uses-permission android:name=”android.permission.WRITE_EXTERNAL_STORAGE”></uses-permission>
<application android:icon=”@drawable/icon” android:label=”@string/app_name” android:debuggable=”true”>
<activity android:name=”.PDFFromServerActivity”
android:label=”@string/app_name”>
<intent-filter>
<action android:name=”android.intent.action.MAIN” />
<category android:name=”android.intent.category.LAUNCHER” />
</intent-filter>
</activity>    </application>
</manifest>

3.) Create Downloader.java file into your package and write following code:

package com.pdftest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class Downloader {        public static void DownloadFile(String fileURL, File directory) {
try {

FileOutputStream f = new FileOutputStream(directory);
URL u = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod(“GET”);
c.setDoOutput(true);
c.connect();

InputStream in = c.getInputStream();

byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
f.close();
} catch (Exception e) {
e.printStackTrace();
}

}
}

4.) Run for output.

Steps:

1.) Create a project named PDFFromServerExample and set the information as stated in the image.

Build Target: Android 2.2
Application Name: PDFFromServerExample
Package Name: com.pdftest
Activity Name: PDFFromServerExample
Min SDK Version: 8

2.) Open PDFFromServerActivity.java file and write following code there:

package com.pdftest;import java.io.File;
import java.io.IOException;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;

public class PDFFromServerActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String extStorageDirectory = Environment.getExternalStorageDirectory()
.toString();
File folder = new File(extStorageDirectory, “pdf”);
folder.mkdir();
File file = new File(folder, “Read.pdf”);
try {
file.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
Downloader.DownloadFile(“http://www.nmu.ac.in/ejournals/aspx/courselist.pdf&#8221;, file);

showPdf();
}
public void showPdf()
{
File file = new File(Environment.getExternalStorageDirectory()+”/pdf/Read.pdf”);
PackageManager packageManager = getPackageManager();
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType(“application/pdf”);
List list = packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
intent.setDataAndType(uri, “application/pdf”);
startActivity(intent);
}
}

3.) Compile and build the project.

Output