Monday, April 30, 2012

Android email example


SendEmailActivity .java

public class SendEmailActivity extends Activity 
{
Button buttonSend;
EditText textTo;
EditText textSubject;
EditText textMessage;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

buttonSend = (Button) findViewById(R.id.buttonSend);
textTo = (EditText) findViewById(R.id.editTextTo);
textSubject = (EditText) findViewById(R.id.editTextSubject);
textMessage = (EditText) findViewById(R.id.editTextMessage);

buttonSend.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {

 String to = textTo.getText().toString();
 String subject = textSubject.getText().toString();
 String message = textMessage.getText().toString();

 Intent email = new Intent(Intent.ACTION_SEND);
 email.putExtra(Intent.EXTRA_EMAIL, new String[]{ to});
 //email.putExtra(Intent.EXTRA_CC, new String[]{ to});
 //email.putExtra(Intent.EXTRA_BCC, new String[]{to});
 email.putExtra(Intent.EXTRA_SUBJECT, subject);
 email.putExtra(Intent.EXTRA_TEXT, message);

 //need this to prompts email client only
 email.setType("message/rfc822");

 startActivity(Intent.createChooser(email, "Choose an Email client :"));

}
});
}
}

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linearLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textViewPhoneNo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="To : "
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <EditText
        android:id="@+id/editTextTo"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="textEmailAddress" >

        <requestFocus />
    </EditText>

    <TextView
        android:id="@+id/textViewSubject"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Subject : "
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <EditText
        android:id="@+id/editTextSubject"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
         >
    </EditText>

    <TextView
        android:id="@+id/textViewMessage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Message : "
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <EditText
        android:id="@+id/editTextMessage"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="top"
        android:inputType="textMultiLine"
        android:lines="5" />

    <Button
        android:id="@+id/buttonSend"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Send" />

</LinearLayout>

Android silent mode example

SlientMode.java

public class SilentMode extends Activity 
{
  public void onCreate(Bundle savedInstanceState) 
 {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final TextView txt = (TextView) findViewById(R.id.txt1);

Button silent = (Button) findViewById(R.id.silent);
Button normal = (Button) findViewById(R.id.normal);
Button vibra = (Button) findViewById(R.id.vibration);

final AudioManager mode = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
silent.setOnClickListener(new View.OnClickListener() 
   {
public void onClick(View v) 
    {
txt.setText("The Mobile in Silent Mode");
mode.setRingerMode(AudioManager.RINGER_MODE_SILENT);
Toast.makeText(getBaseContext(), "Silent Mode Activated",
Toast.LENGTH_SHORT).show();
}
});

normal.setOnClickListener(new View.OnClickListener() 
{
public void onClick(View v) 
  {
txt.setText("The Mobile in Normal Mode");
mode.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
Toast.makeText(getBaseContext(), "Normal Mode Activated",
Toast.LENGTH_SHORT).show();
}
});

vibra.setOnClickListener(new View.OnClickListener() 
  {
public void onClick(View v) 
   {
txt.setText("The Mobile in Normal Mode");
mode.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
Toast.makeText(getBaseContext(), "Vibration Mode Activated",
Toast.LENGTH_SHORT).show();
}
});
}
}

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/txt1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/silent"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Switch to Silent Mode" />

    <Button
        android:id="@+id/normal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Switch to Normal Mode" />
   
    <Button
        android:id="@+id/vibration"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Switch to Vibration" />

</LinearLayout>

Sunday, April 29, 2012

SQLite DB Example


There are 4 ways of storing data on the android platform:

  • 1.    Preferences
  • 2.    SQLite Database
  • 3.    Files
  • 4.    Network

A word about each of them here and then I will move on to an example that shows how to work with SQLite DB that comes along with the android platform.

Preferences – 
Basically used for storing user preferences for a single application or across applications for a mobile. This is typically name-value pairs accessible to the context.

Databases – 
Android supports creating of databases based on SQLite db. Each database is private to the applications that creates it 

Files –
Files can be directly stored on the mobile or on to an extended storage medium. By default other applications cannot access it.

Network – 
Data can be stored and retrieved from the network too depending on the availability.

If an application wants to store and retrieve data for its own use, without having to share the data across applications, it can access the SQLite DB directly. There is no need of a content provider. We have seen in anearlier post how to use content providers

In this example, we will do the following:
1.    Create a database (typically a one time activity)
2.    Create a table (typically a one time activity)
3.    Insert values into the table
4.    Retrieve the values from the table
5.    Display the retrieved values as a List view
6.    Delete all the records from the table before closing the connection to the database

Step 1: Create a database:

   sampleDB =  this.openOrCreateDatabase(SAMPLE_DB_NAMEMODE_PRIVATEnull);

This opens a database defined in the constant SAMPLE_DB_NAME, if it already exists. Else it creates a database and opens it. The second parameter is operating mode : MODE_PRIVATE meaning it is accessible to only this context. The other modes are and MODE_WORLD_WRITABLE. MODE_WORLD_READABLE

Step 2: Create a Table:

sampleDB.execSQL("CREATE TABLE IF NOT EXISTS " +
                        SAMPLE_TABLE_NAME +
                        " (LastName VARCHAR, FirstName VARCHAR," +
                        " Country VARCHAR, Age INT(3));");

Step 3: Insert values into the table:

sampleDB.execSQL("INSERT INTO " +
                        SAMPLE_TABLE_NAME +
                        " Values ('Makam','Sai Geetha','India',25);");

Step 4: Retrieve values 

Cursor c = sampleDB.rawQuery("SELECT FirstName, Age FROM " +
                        SAMPLE_TABLE_NAME +
                        " where Age > 10 LIMIT 5"null);
            
      if (c != null ) {
            if  (c.moveToFirst()) {
                  do {
String firstName = c.getString(c.getColumnIndex("FirstName"));
                  int age = c.getInt(c.getColumnIndex("Age"));
                  results.add("" + firstName + ",Age: " + age);
                  }while (c.moveToNext());
            } 
       }

Step 5: Display the values as a list 
            
       this.setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,results));

The statement displays it as a list as the class extends a ListActivity.

Step 6: Delete the values from the table in the finally part of the try block

finally {
            if (sampleDB != null
                  sampleDB.execSQL("DELETE FROM " + SAMPLE_TABLE_NAME);
                  sampleDB.close();
        }

It is as simple as this to work with the SQLite DB even in android. No different from a desktop application. However, there are various overloaded methods of query() provided by the SQLIteDatabase class which can be more optimally used instead of execSQL.

Simulate Location Change in Android Emulator


Start the Emulator
Start a command prompt
Start telnet
Then, type, o localhost 5554
This connects the telnet client to the android emulator (assuming emulator is running locally listening on port 5554. Else this connection fails)
Now type
geo fix 79.000000 13.000000 (or your latitude and longitude)
This sends the location change signal to the emulator.
NOTE: This is useful for applications built using Location APIs in Android and need to work with changes in location

Android Google Maps API key


Step 1: Locate debug.keystore on your system. It is usually in the USER_HOME\Local Settings\Application Data\.android folder on windows.

Step 2: Use the keytool utility to generate certificate fingerprint (MD5). keytool utility that comes with the default JDK installation.

C:\>keytool -list -alias androiddebugkey -keystore .android\debug.keystore -storepass android -keypass android

It will getnerate a certificate fingerprint (MD5) in this format:

Certificate fingerprint (MD5): XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX

Step 3: Go to the page for obtaining the Maps API Key. Put your Certificate fingerprint (MD5) And get your API key for android Google Map application. On this page, paste the certificate fingerprint in the appropriate form field, and click the “Generate API Key” button. This will return a Maps API key string. 

The key can be used in the Maps Application by pasting it in the MapView element in the XML layout file where appropriate.

Uninstall apk programmatically


First, make sure the emulator is running. Then follow below steps:

1. Go to the tools directory in command prompt – 
c:\>android\tools
2. Type 
adb shell
3. #
cd /data/app (this takes you to the folder where all apk files are installed)
4. 
#ls (It will display all the .apk installed in your emulator)
5. #
rm ***.apk (which you want to remove, all apk files)
6.#
exit (exits from the adb shell)

NOTE: to start the emulator, you can start it from eclipse by right clicking an android project and “run as” an “application” or by going to tools directory at command prompt and typing “emulator –avd <avd_name>”

Incoming calls on Emulator


On windows XP, open a command console.
Type “telnet”. The telnet client starts.
Then, type, o localhost 5554
This connects the telnet client to the android emulator (assuming emulator is running locally listening on port 5554. Else this connection fails)
Now type
gsm call 123456
The last parameter could be any number.
This simulates a call to the emulator.

To disable Chinese / Japanese auto-Characters – Android Emulator


Sometimes, when you are using the emulator, even if you type English characters, the emulator will be suggesting based on some Chinese /Japanese characters (I do not know the difference between the two). To disable this you need to go to Phone Settings in the emulator menus and remove the Japanese IME Settings. The path to that is in the main screen, click on the up-arrow (seen at the bottom) to see the menu. Select “settings”, navigate to “Language & Keyboard Settings”, and uncheck “Japanese IME”. You will be back to English suggestions / keyboard.

Android google map example


Maps-based and location-based services are compelling for mobile users. Hence let us explore the support for map services in the Android platform in this tutorial. In the next we will  build upon this and add location services too.

Map services are provided by an external library that includes the com.google.android.maps package. This library is not provided as part of the standard SDK. It is provided as a Google APIs add-on to the android SDK. For the convenience of developers, this add-on is provided as part of the SDK on the emulator.

Before I jump into the example, let me explain some fundamental concepts related to the Maps API.

NOTE: For using the Google Maps, you have to obtain a Maps API key. How to obtain the key is also described towards the end of this tutorial. This is Step 1. 

Maps API add-on provides a MapActivity class that extends the Activity class of Android. This helps is managing the lifecycle of a MapView object that we will be using later. Our main class in the application will be extending the MapActivity class. This class can be treated as the default activity class whenever we deal with the Maps API.

MapView – This is a class that extends the View and the ViewGroup classes of Android. It provides the basic functionality expected on a Map like responding to key presses or touch and allowing zooming etc. It also provides a controller object that helps us manipulate the Map view programmatically. We will see how, in the example later.

Now that we have understood the basics of the Maps API, let us jump into the example. 

Step 2: To begin with, when you create an android project in Eclipse, instead of choosing the target name as Android 1.5, you need to select the target as Google APIs. This ensures that the project has the map API external libraries along with android 1.5 SDK. 

Step 3: The Activity class you create this time should not extend the standard “android.app.Activity” class but should extend the MapActivity class about which I explained earlier.

Step 4: Apart from this, you need to add the following tag in the AndroidManifext.xml in order to use the external library:

<uses-library android:name="com.google.android.maps" />

Step 5: Now let us declare the map view in main.xml in layout folder. To do so, add this element in order to display the map using MapView.

<com.google.android.maps.MapView
android:id="@+id/myGMap"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:enabled="true"
      android:clickable="true"
      android:apiKey="0YaGLMeMFKXrhzHL-uSYZSnqXqbGwE6kxF4VwFQ"
    />

Here the apikey should be what was generated by you in an earlier step 1. 

 Step 6: In the activity class I set the geo point on the map and set the satellite view to false.

      myMapView = (MapView) findViewById(R.id.myGMap);
      geoPoint = new GeoPoint((int) (latitude * 1000000), (int) (longitude * 1000000));
      myMapView.setSatellite(false);

Step 7: Now you are almost ready to go. But we will try to do some programtic handling of the mapview. For that we need to get a handle to the MapController object. It is done this way:

      myMC = myMapView.getController();
      myMC.setCenter(geoPoint);
      myMC.setZoom(15);

I also set the zoom controls to be displayed with this code.

      myMapView.setBuiltInZoomControls(true);
      myMapView.displayZoomControls(true);

Step 8: Add the following permissions in the AndroidManifest.xml in order to access the maps over the internet:

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>

You could execute your program now to view the map with the fixed geopoint. 

Step 9: One last step – let us add some actions to the key presses for zooming in, zooming out, viewing the satellite view, normal map view

      public boolean onKeyDown(int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_I) {
                  myMapView.getController().setZoom(myMapView.getZoomLevel() + 1);
                  return true;
            } else if (keyCode == KeyEvent.KEYCODE_O) {
                  myMapView.getController().setZoom(myMapView.getZoomLevel() - 1);
                  return true;
            } else if (keyCode == KeyEvent.KEYCODE_S) {
                  myMapView.setSatellite(true);
                  return true;
            } else if (keyCode == KeyEvent.KEYCODE_M) {
                  myMapView.setSatellite(false);
                  return true;
            }
            return false;
      }

Now you can run the applications. The Google map will show up with a pointer to the geo location defined in the program. You can click on I, O, S and M for zooming in, zooming out, viewing the satellite map or the normal map respectively.

Interesting?

The complete code is downloadable here.


Obtaining a Maps API Key:

Step 1: Locate debug.keystore on your system. It is usually in the USER_HOME\Local Settings\Application Data\.android folder on windows.

Step 2: Use the keytool utility to generate certificate fingerprint (MD5). keytool utility that comes with the default JDK installation.

C:\>keytool -list -alias androiddebugkey -keys
tore .android\debug.keystore -storepass android -keypass android

It will getnerate a certificate fingerprint (MD5) in this format:

Certificate fingerprint (MD5): XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX

Step 3: Go to the page for obtaining the Maps API Key. Put your Certificate fingerprint (MD5) And get your API key for android Google Map application. On this page, paste the certificate fingerprint in the appropriate form field, and click the “Generate API Key” button. This will return a Maps API key string. 

This key needs to be used along with the MapView element declared in the XML layout file as mentioned in the tutorial above.