Site Information ...

Android parse XML file example using SAX Parser

Here we are going to see about how to parse a XML using SAX Parser. SAX parser is fast and has less memory footprint. First we need to create an instance of SAXParserFactory and then use a custom XML handler extending DefaultHandler that will map our XML file into a java bean.



Sample XML data used in this example

<Items>
    <ItemData>
        <ItemNumber>ABC</ItemNumber>
        <Description>ABC Item Description</Description>
        <Price>9.95</Price>
        <Weight>10.00</Weight>
    </ItemData>
    <ItemData>
        <ItemNumber>XYZ</ItemNumber>
        <Description>XYZ Item Description</Description>
        <Price>19.95</Price>
        <Weight>22.22</Weight>
    </ItemData>
</Items>

Source code for ItemMaster.java

package com.as400samplecode;

public class ItemMaster {
   
    String itemNumber = null;
    String description = null;
    String price = null;
    double weight = 0;
   
    public String getItemNumber() {
        return itemNumber;
    }
    public void setItemNumber(String itemNumber) {
        this.itemNumber = itemNumber;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
    public String getPrice() {
        return price;
    }
    public void setPrice(String price) {
        this.price = price;
    }
    public double getWeight() {
        return weight;
    }
    public void setWeight(double weight) {
        this.weight = weight;
    }
   
}

Source code for ItemXMLHandler.java

package com.as400samplecode;

import java.util.ArrayList;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class ItemXMLHandler extends DefaultHandler {

    Boolean currentElement = false;
    String currentValue = "";
    ItemMaster item = null;
    private ArrayList<ItemMaster> itemsList = new ArrayList<ItemMaster>();

    public ArrayList<ItemMaster> getItemsList() {
        return itemsList;
    }

    // Called when tag starts 
    @Override
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {

        currentElement = true;
        currentValue = "";
        if (localName.equals("ItemData")) {
            item = new ItemMaster();
        } 

    }

    // Called when tag closing 
    @Override
    public void endElement(String uri, String localName, String qName)
    throws SAXException {

        currentElement = false;

        /** set value */
        if (localName.equalsIgnoreCase("ItemNumber"))
            item.setItemNumber(currentValue);
        else if (localName.equalsIgnoreCase("Description"))
            item.setDescription(currentValue);
        else if (localName.equalsIgnoreCase("Price"))
            item.setPrice(currentValue);
        else if (localName.equalsIgnoreCase("Weight"))
            item.setWeight(Double.parseDouble(currentValue));
        else if (localName.equalsIgnoreCase("ItemData"))
            itemsList.add(item);
    }

    // Called to get tag characters 
    @Override
    public void characters(char[] ch, int start, int length)
    throws SAXException {

        if (currentElement) {
            currentValue = currentValue +  new String(ch, start, length);
        }

    }

}

Source code for AndroidParseXMLActivity.java

package com.as400samplecode;

import java.io.StringReader;
import java.util.ArrayList;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class AndroidParseXMLActivity extends Activity {

    private EditText xmlInput;
    private TextView xmlOutput;

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

        xmlInput = (EditText) findViewById(R.id.xmlInput);
        xmlOutput = (TextView) findViewById(R.id.xmlOutput);

        Button parseMyXML = (Button) findViewById(R.id.parse);
        parseMyXML.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                parseXML();
            }
        });
    }

    private void parseXML() {

        String parsedData = "";
       
        try {

            Log.w("AndroidParseXMLActivity", "Start");
            /** Handling XML */
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp = spf.newSAXParser();
            XMLReader xr = sp.getXMLReader();

            ItemXMLHandler myXMLHandler = new ItemXMLHandler();
            xr.setContentHandler(myXMLHandler);
            InputSource inStream = new InputSource();
            Log.w("AndroidParseXMLActivity", "Parse1");

            inStream.setCharacterStream(new StringReader(xmlInput.getText().toString()));
            Log.w("AndroidParseXMLActivity", "Parse2");

            xr.parse(inStream);
            Log.w("AndroidParseXMLActivity", "Parse3");

            ArrayList<ItemMaster> itemsList = myXMLHandler.getItemsList();
            for(int i=0;i<itemsList.size();i++){
                ItemMaster item = itemsList.get(i);
                parsedData = parsedData + "----->\n";
                parsedData = parsedData + "Item Number: " + item.getItemNumber() + "\n";
                parsedData = parsedData + "Description: " + item.getDescription() + "\n";
                parsedData = parsedData + "Price: " + item.getPrice() + "\n";
                parsedData = parsedData + "Weight: "+ item.getWeight() + "\n";
               
            }
            Log.w("AndroidParseXMLActivity", "Done");
        }
        catch (Exception e) {
            Log.w("AndroidParseXMLActivity",e );
        }
       
        xmlOutput.setText(parsedData);
       
    }

}

Source code for 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">
    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:text="@string/hello"
        android:textStyle="bold" android:textSize="25sp"
        android:paddingBottom="15dp" />
    <EditText android:layout_height="wrap_content"
        android:layout_width="match_parent" android:id="@+id/xmlInput"
        android:lines="10">
        <requestFocus />
    </EditText>
    <Button android:layout_height="wrap_content"
        android:layout_width="wrap_content" android:id="@+id/parse"
        android:text="Parse Now" />
    <TextView android:layout_height="wrap_content"
        android:layout_width="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge"
        android:id="@+id/textView1" android:text="Parsed XML Data"
        android:paddingBottom="15dp" android:textStyle="bold" />
    <ScrollView android:layout_height="wrap_content"
        android:layout_width="match_parent" android:id="@+id/scrollView1">
        <LinearLayout android:id="@+id/linearLayout1"
            android:layout_width="match_parent" android:layout_height="match_parent">
            <TextView android:layout_height="wrap_content"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:id="@+id/xmlOutput" android:layout_width="match_parent" />
        </LinearLayout>
    </ScrollView>
</LinearLayout>

Recommended Reading

Read Excel and Write DB2 data using Apache POI HSSF implementation

HSSF is the POI Project's pure Java implementation of the Excel '97(-2007) file format. HSSF provides ways to read spreadsheets create, modify, read and write XLS spreadsheets. They provide:
  • low level structures for those with special needs
  • an eventmodel api for efficient read-only access
  • a full usermodel api for creating, reading and modifying XLS files

The following jars are needed to execute the sample code


The following sample code reads any excel file and will convert it into a Db2 database table with the help of a properties file. You can modify the program to convert excel data into Mysql, Oracle, SQL Server or any other relational database using the proper database JDBC drivers.

Sample Db2 table named MYTABLE

                R TABLER                            
                  EMPLOYEE       5S 1               
                  NAME          30A                 
                  SALARY        11P 2               
                  ZSTAMP          Z                 
                K EMPLOYEE                          

Sample EXCEL file


Read Excel and Write DB2 data using Apache POI

Sample Properties file

#Properties File for EXCEL to Db2 generation

localSystem=localhost
userId={user_id}    
password={password}
excelPath=data/
fileName=MYTABLE
fields=EMPLOYEE,NAME,SALARY 

Source code for ReadExcelWriteDb2.java

package com.as400samplecode;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.Properties;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class ReadExcelWriteDb2 {

    static Properties props;

    public static void main(String[] args) {

        String excelFilename = null;
        String propsFilename = null;

        ReadExcelWriteDb2 readExcelWriteDb2 = new ReadExcelWriteDb2();
        if (args.length < 1)
        {
            System.err.println("Usage: java "+readExcelWriteDb2.getClass().getName()+
            " Excel_Filename  Properties_Filename");
            System.exit(1);
        }

        excelFilename = args[0].trim();
        propsFilename = args[1].trim();
        readExcelWriteDb2.generateDb2(excelFilename, propsFilename);

    }

    public void  generateDb2(String excelFilename, String propsFilename){

        try {

            props = new Properties();
            props.load(new FileInputStream("properties/" + propsFilename));

            String DRIVER = "com.ibm.as400.access.AS400JDBCDriver";        
            String URL = "jdbc:as400://" + props.getProperty("localSystem").trim() + ";naming=system;errors=full";
            Connection conn = null; 
            String sql = null;
            PreparedStatement stmt = null;

            //Connect to iSeries                                         
            Class.forName(DRIVER);                                       
            conn = DriverManager.getConnection(URL,props.getProperty("userId").trim(),props.getProperty("password").trim());   

            sql = "SELECT " + props.getProperty("fields").trim() + " from " + props.getProperty("fileName").trim();
            stmt = conn.prepareStatement(sql);
            ResultSet rs = stmt.executeQuery();

            ResultSetMetaData metaData = rs.getMetaData();
            int colCount = metaData.getColumnCount();

            String q = "";
            for (int c = 0; c < colCount; c++) {
                if(q.equalsIgnoreCase("")){
                    q = "?";
                }
                else{
                    q = q + ",?";
                }
            }
            sql = "INSERT into " +
            props.getProperty("fileName").trim() + 
            " (" + props.getProperty("fields").trim() + ") VALUES(" + q + ")";
            stmt = conn.prepareStatement(sql);
            boolean insertData = true;
           
            FileInputStream fileInputStream = new FileInputStream(props.getProperty("excelPath").trim() + excelFilename.trim());

            HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
            HSSFSheet sheet = workbook.getSheetAt(0);

            int rows = sheet.getPhysicalNumberOfRows() + 5;
            System.out.println(workbook.getSheetName(0) + "\" has " + rows + " row(s).");
            for (int r = 0; r < rows; r++) {

                HSSFRow row = sheet.getRow(r);
                if (row == null) {
                    continue;
                }
                // Skip Header Row
                if (r == 0) {
                    continue;
                }


                int cells = row.getPhysicalNumberOfCells();
                System.out.println("\nROW " + row.getRowNum() + " has " + cells + " cell(s).");
                for (int c = 0; c < cells; c++) {
                    HSSFCell cell = row.getCell(c);
                    String value = null,printValue = null;

                    System.out.println("Column=" + cell.getColumnIndex() + " CELL Type=" + cell.getCellType());
                   
                    switch (cell.getCellType()) {

                    case HSSFCell.CELL_TYPE_FORMULA:
                        printValue = "FORMULA value=" + cell.getCellFormula();
                        value = cell.getCellFormula();
                        break;

                    case HSSFCell.CELL_TYPE_NUMERIC:
                        printValue = "NUMERIC value=" + cell.getNumericCellValue();
                        value = String.valueOf(cell.getNumericCellValue());
                        break;

                    case HSSFCell.CELL_TYPE_STRING:
                        printValue = "STRING value=" + cell.getStringCellValue();
                        value = cell.getStringCellValue();
                        break;
                       
                    case HSSFCell.CELL_TYPE_BLANK:
                        printValue = "STRING value=" + cell.getStringCellValue();
                        value = cell.getStringCellValue();
                        break;   

                    default:
                    }
                   
                    System.out.println("Column=" + cell.getColumnIndex() + " VALUE=" + printValue);
                   
                    // If no data was provided, do not insert
                    if(value.equalsIgnoreCase("") || value == null){
                        insertData = false;
                        break;
                    }
                   
                    switch (metaData.getColumnType(cell.getColumnIndex()+1)) {

                    case java.sql.Types.CHAR:
                        stmt.setString(cell.getColumnIndex()+1,value);
                        break;

                    case java.sql.Types.NUMERIC:
                        if(metaData.getScale(cell.getColumnIndex()+1) == 0){
                            stmt.setInt(cell.getColumnIndex()+1,Integer.parseInt(value));
                        }
                        else {
                            stmt.setDouble(cell.getColumnIndex()+1,Double.parseDouble(value));
                        }
                        break;

                    case java.sql.Types.DECIMAL:
                        if(metaData.getScale(cell.getColumnIndex()+1) == 0){
                            stmt.setInt(cell.getColumnIndex()+1,Integer.parseInt(value));
                        }
                        else {
                            stmt.setDouble(cell.getColumnIndex()+1,Double.parseDouble(value));
                        }
                        break;

                    default:
                    }
                }

                if(insertData){
                stmt.executeUpdate();
                }
            }

            rs.close();
            stmt.close();
            conn.close();


        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

Android emulator copy and paste from clipboard or notepad into EditText

If you try to just do a copy from the notepad and paste it in the EditText field then it doesn't work. You have to send the text as an sms message through telnet and then copy the text from the sms message.

To send a sms you have to first connect to the emulator using Telnet.

Syntax:    telnet localhost <port>
Example: telnet localhost 5554

Then send the message

Syntax:    sms send <senders phone number> <message>
Example: sms send 6667778888 This is the text you want to copy and paste

Tip: You can put any phone number

 
Android emulator copy and paste

Android emulator copy and paste

Android emulator copy and paste

Windows 7 how to enable Telnet Client

Today I was trying to use the Telnet from Command Prompt in Windows 7. It didn't work. First I thought I am making a Typo mistake. But after research found that it is disabled by default. Here are the steps to enable Telnet Client.
  1. Start
  2. Control Panel
  3. Programs And Features
  4. Turn Windows features on or off
  5. Check Telnet Client
  6. Hit OK

Windows 7 enable Telnet Client

Android google maps WebView example with Geocoding to get Latitude and Longitude

Geocoding is the process of transforming a street address or other description of a location into a (latitude, longitude) coordinate. The Geocoder class requires a backend service that is not included in the core android framework. The Geocoder query methods will return an empty list if there no backend service in the platform. Use the isPresent() method to determine whether a Geocoder implementation exists.

Android google maps WebView example
Before you start coding the Android application, you must setup a html page using Google Maps JavaScript API on a web server of your choice. Then you can reference the html page in your android application WebView. The example here uses an ArrayAdapter to list Countries. When you click on a given country, it uses that to Geocode its latitude and longitude. After that it centers the map to that location with the specifies zoom level. The user can then use the Maps control to zoom in and out, also can navigate using touch gestures.

Source for androidMap.html to be deployed on your Web Server

<!DOCTYPE html>
<html> 
<head> 
<title>Google Maps JavaScript API v3 Example: Overlay Removal</title>
<link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script> 
<script type="text/javascript"> 
  var map;
  var markersArray = [];

  function initialize() {
    var haightAshbury = new google.maps.LatLng(0,0);
    var mapOptions = {
      zoom: 5,
      center: haightAshbury,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("map_canvas"),
        mapOptions);

    google.maps.event.addListener(map, 'click', function(event) {
      addMarker(event.latLng);
    });
  }
  
  function centerAt(latitude, longitude){
        myLatlng = new google.maps.LatLng(latitude,longitude);
        map.panTo(myLatlng);
        addMarker(myLatlng);
  }       
  
  function addMarker(location) {
    clearOverlays(); 
    marker = new google.maps.Marker({
      position: location,
      map: map
    });
    markersArray.push(marker);
  }

 // Removes the overlays from the map, but keeps them in the array
  function clearOverlays() {
    if (markersArray) {
      for (i in markersArray) {
        markersArray[i].setMap(null);
      }
    }
  }

  // Shows any overlays currently in the array
  function showOverlays() {
    if (markersArray) {
      for (i in markersArray) {
        markersArray[i].setMap(map);
      }
    }
  }

  // Deletes all markers in the array by removing references to them
  function deleteOverlays() {
    if (markersArray) {
      for (i in markersArray) {
        markersArray[i].setMap(null);
      }
      markersArray.length = 0;
    }
  }
</script> 
</head> 
<body onload="initialize();"> 
<!--
  <div>
     <input onclick="clearOverlays();" type=button value="Clear Overlays"/>
    <input onclick="showOverlays();" type=button value="Show All Overlays"/>
    <input onclick="deleteOverlays();" type=button value="Delete Overlays"/> 
  </div> 
--> 
  <div id="map_canvas"></div> 
</body> 
</html> 

Source for GoogleMapsWebViewActivity.java

package com.as400samplecode;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;

public class GoogleMapsWebViewActivity extends Activity {

    private ListView mListView;
    private WebView mapView;
    private ArrayList<String> myAddressList = new ArrayList<String>();
    private String myAddress;
    private String centerURL;;

    static final String[] COUNTRIES = new String[] {
        "Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra",
        "Angola", "Anguilla", "Antarctica", "Antigua and Barbuda", "Argentina",
        "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan",
        "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium",
        "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia",
        "Bosnia and Herzegovina", "Botswana", "Bouvet Island", "Brazil", "British Indian Ocean Territory",
        "British Virgin Islands", "Brunei", "Bulgaria", "Burkina Faso", "Burundi",
        "Cote d'Ivoire", "Cambodia", "Cameroon", "Canada", "Cape Verde",
        "Cayman Islands", "Central African Republic", "Chad", "Chile", "China",
        "Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo",
        "Cook Islands", "Costa Rica", "Croatia", "Cuba", "Cyprus", "Czech Republic",
        "Democratic Republic of the Congo", "Denmark", "Djibouti", "Dominica", "Dominican Republic",
        "East Timor", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea",
        "Estonia", "Ethiopia", "Faeroe Islands", "Falkland Islands", "Fiji", "Finland",
        "Former Yugoslav Republic of Macedonia", "France", "French Guiana", "French Polynesia",
        "French Southern Territories", "Gabon", "Georgia", "Germany", "Ghana", "Gibraltar",
        "Greece", "Greenland", "Grenada", "Guadeloupe", "Guam", "Guatemala", "Guinea", "Guinea-Bissau",
        "Guyana", "Haiti", "Heard Island and McDonald Islands", "Honduras", "Hong Kong", "Hungary",
        "Iceland", "India", "Indonesia", "Iran", "Iraq", "Ireland", "Israel", "Italy", "Jamaica",
        "Japan", "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Kuwait", "Kyrgyzstan", "Laos",
        "Latvia", "Lebanon", "Lesotho", "Liberia", "Libya", "Liechtenstein", "Lithuania", "Luxembourg",
        "Macau", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands",
        "Martinique", "Mauritania", "Mauritius", "Mayotte", "Mexico", "Micronesia", "Moldova",
        "Monaco", "Mongolia", "Montserrat", "Morocco", "Mozambique", "Myanmar", "Namibia",
        "Nauru", "Nepal", "Netherlands", "Netherlands Antilles", "New Caledonia", "New Zealand",
        "Nicaragua", "Niger", "Nigeria", "Niue", "Norfolk Island", "North Korea", "Northern Marianas",
        "Norway", "Oman", "Pakistan", "Palau", "Panama", "Papua New Guinea", "Paraguay", "Peru",
        "Philippines", "Pitcairn Islands", "Poland", "Portugal", "Puerto Rico", "Qatar",
        "Reunion", "Romania", "Russia", "Rwanda", "Sqo Tome and Principe", "Saint Helena",
        "Saint Kitts and Nevis", "Saint Lucia", "Saint Pierre and Miquelon",
        "Saint Vincent and the Grenadines", "Samoa", "San Marino", "Saudi Arabia", "Senegal",
        "Seychelles", "Sierra Leone", "Singapore", "Slovakia", "Slovenia", "Solomon Islands",
        "Somalia", "South Africa", "South Georgia and the South Sandwich Islands", "South Korea",
        "Spain", "Sri Lanka", "Sudan", "Suriname", "Svalbard and Jan Mayen", "Swaziland", "Sweden",
        "Switzerland", "Syria", "Taiwan", "Tajikistan", "Tanzania", "Thailand", "The Bahamas",
        "The Gambia", "Togo", "Tokelau", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey",
        "Turkmenistan", "Turks and Caicos Islands", "Tuvalu", "Virgin Islands", "Uganda",
        "Ukraine", "United Arab Emirates", "United Kingdom",
        "United States", "United States Minor Outlying Islands", "Uruguay", "Uzbekistan",
        "Vanuatu", "Vatican City", "Venezuela", "Vietnam", "Wallis and Futuna", "Western Sahara",
        "Yemen", "Yugoslavia", "Zambia", "Zimbabwe"
    };
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mListView = (ListView) findViewById(R.id.listView1);
        mListView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, COUNTRIES));

        mListView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                // When clicked, show a toast with the TextView text
                Log.v("GoogleMapsWebViewActivity:", "Country: " + ((TextView) view).getText().toString());
                myAddressList.clear();
                String thisAddress = ((TextView) view).getText().toString();
                myAddressList.add(thisAddress);
                myAddress = thisAddress;
                //Set Map
                mapCustomerAddress();
            }
        });

        Button submit = (Button) findViewById(R.id.showMap);
        submit.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {

                Uri uri = Uri.parse("geo:0,0?q=" + myAddress);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);

            }
        });

    }

    private void mapCustomerAddress(){

        boolean internet =  isNetworkAvailable(GoogleMapsWebViewActivity.this);
        if(internet){
            Button mapButton = (Button) findViewById(R.id.showMap);
            mapButton.setEnabled(true);

            //getLocation();
            Log.v("GoogleMapsWebViewActivity:", "Address Size: " + myAddressList.size());
            Geocoder geoCoder = new Geocoder(GoogleMapsWebViewActivity.this, Locale.getDefault());   
            List<Address> addresses= null;
            try {
                for(int i=0;i<myAddressList.size();i++){
                    addresses = geoCoder.getFromLocationName(myAddressList.get(i), 5);
                    if(addresses.size() >0){
                        myAddress = myAddressList.get(i);
                        break;
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            setupWebView(addresses);
        }
        else {
            Button mapButton = (Button) findViewById(R.id.showMap);
            mapButton.setEnabled(false);

            mapView = (WebView) findViewById(R.id.mapView);
            String mapNotAvailable =     "<html><head></head><body>" +
            "<img src='map_not_available.png' width='100%'/>" +
            "<br/><b>You need internet connectivity for Maps!</b>" +
            "</body><html>";
            mapView.loadDataWithBaseURL("file:///android_asset/", mapNotAvailable, "text/html", "utf-8", null);

        }

    }

    /** Sets up the WebView object and loads the URL of the page **/
    private void setupWebView(List<Address> addresses){
        Log.v("GoogleMapsWebViewActivity:", "Address Size: " + addresses.size());
       
        if (addresses.size() > 0) {
            Log.v("GoogleMapsWebViewActivity:", "Address Lat: " + addresses.get(0).getLatitude());
            Log.v("GoogleMapsWebViewActivity:", "Address Long: " + addresses.get(0).getLongitude());

            centerURL = "javascript:centerAt(" + 
            addresses.get(0).getLatitude() + "," + 
            addresses.get(0).getLongitude()+ ")";
        }   

        mapView = (WebView) findViewById(R.id.mapView);
        mapView.getSettings().setJavaScriptEnabled(true);
        //Wait for the page to load then send the location information
        mapView.setWebViewClient(new WebViewClient(){ 
            @Override 
            public void onPageFinished(WebView view, String url) 
            {
                mapView.loadUrl(centerURL);
            }

        });
        String MAP_URL = "http://10.0.2.2:8080/CapitalWebServices/androidMap.html";
        mapView.loadUrl(MAP_URL); 
    }

    private boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    Log.v("INTERNET:",String.valueOf(i));
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        Log.v("INTERNET:", "connected!");
                        return true;
                    }
                }
            }
        }
        return false;
    }
}

Source for list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp"
    android:textSize="16sp" >
</TextView>

Source for 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">
    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:text="@string/hello"
        android:textSize="25sp" android:textStyle="bold" />
    <LinearLayout android:layout_width="match_parent"
        android:layout_height="wrap_content" 
  android:id="@+id/linearLayout1" android:orientation="horizontal">
        <LinearLayout android:layout_height="match_parent" android:id="@+id/linearLayout2"
            android:orientation="vertical" android:layout_weight="30" android:layout_width="0dp">
            <ListView android:id="@+id/listView1" android:layout_height="wrap_content"
                android:layout_width="match_parent" />
        </LinearLayout>
        <LinearLayout android:layout_height="match_parent" android:id="@+id/linearLayout3"
            android:orientation="vertical" android:layout_weight="70" android:layout_width="0dp">
            <Button android:text="View Larger Map and Get Directions" 
   android:id="@+id/showMap" android:layout_height="wrap_content" 
   android:layout_width="match_parent">
   </Button>
            <WebView android:id="@+id/mapView" android:layout_width="match_parent"
                android:layout_height="match_parent" />
        </LinearLayout>
    </LinearLayout>
</LinearLayout>

Source for AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.as400samplecode"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="13" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
       
    <application android:icon="@drawable/icon" android:label="@string/app_name"
    android:theme="@android:style/Theme.Holo.Light">
        <activity android:name=".GoogleMapsWebViewActivity"
                  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>

Android google maps example using MapActivity

How to embed google maps in your Android application? Google Maps comes bundled with the Android platform. The following code will show you how to use Google Maps in your Android applications. The sample program does the following...
  • Creates a Map View
  • Use the Geocoder to reverse geocode a given address
  • Get latitude and longitude of locations in Google Maps
  • Add markers to Google Maps
  • Set Zooom


Android google maps using MapActivity

Source for GoogleMapsActivity.java

package com.as400samplecode;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Point;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.view.MotionEvent;
import android.widget.Toast;

public class GoogleMapsActivity extends MapActivity {
    private MapController mapController;
    private MapView mapView;
    private GeoPoint p;

    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.main); // bind the layout to the activity

        // create a map view
        mapView = (MapView) findViewById(R.id.mapview);
        mapView.setBuiltInZoomControls(true);
               
        mapController = mapView.getController();
        Geocoder geoCoder = new Geocoder(this, Locale.getDefault());   
            try {
                List<Address> addresses = 
                    geoCoder.getFromLocationName("2111 North Blackstone Avenue, Fresno, CA 93703-2109", 5);
                if (addresses.size() > 0) {
                    p = new GeoPoint(
                            (int) (addresses.get(0).getLatitude() * 1E6), 
                            (int) (addresses.get(0).getLongitude() * 1E6));
                }   
            } catch (IOException e) {
                e.printStackTrace();
            }

        mapController.setZoom(14);
        mapController.animateTo(p);
       
        //---Add a location marker---
        MapOverlay mapOverlay = new MapOverlay();
        List<Overlay> listOfOverlays = mapView.getOverlays();
        listOfOverlays.clear();
        listOfOverlays.add(mapOverlay);       

        mapView.invalidate();
    }   

    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }
   
     class MapOverlay extends com.google.android.maps.Overlay
        {
            @Override
            public boolean draw(Canvas canvas, MapView mapView, 
            boolean shadow, long when) 
            {
                super.draw(canvas, mapView, shadow);                  
                 
                //---translate the GeoPoint to screen pixels---
                Point screenPts = new Point();
                mapView.getProjection().toPixels(p, screenPts);
     
                //---add the marker---
                Bitmap bmp = BitmapFactory.decodeResource(
                    getResources(), R.drawable.pushpin);           
                canvas.drawBitmap(bmp, screenPts.x, screenPts.y-50, null);        
                return true;
            }
     
            @Override
            public boolean onTouchEvent(MotionEvent event, MapView mapView) 
            {  
                //---when user lifts his finger---
                if (event.getAction() == 1) {               
                    GeoPoint p = mapView.getProjection().fromPixels(
                        (int) event.getX(),
                        (int) event.getY());
     
                    Geocoder geoCoder = new Geocoder(
                        getBaseContext(), Locale.getDefault());
                    try {
                        List<Address> addresses = geoCoder.getFromLocation(
                            p.getLatitudeE6()  / 1E6, 
                            p.getLongitudeE6() / 1E6, 1);
     
                        String add = "";
                        if (addresses.size() > 0) 
                        {
                            for (int i=0; i<addresses.get(0).getMaxAddressLineIndex(); 
                                 i++)
                               add += addresses.get(0).getAddressLine(i) + "\n";
                        }
     
                        Toast.makeText(getBaseContext(), add, Toast.LENGTH_SHORT).show();
                    }
                    catch (IOException e) {               
                        e.printStackTrace();
                    }  
                    return true;
                }
                else               
                    return false;
            }       
        }


}

Source for 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">
    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:text="@string/hello"
        android:textSize="25sp" android:textStyle="bold"
        android:paddingBottom="10dp" />
    <LinearLayout android:layout_height="wrap_content"
        android:id="@+id/linearLayout1" android:layout_width="match_parent"
        android:orientation="vertical">
        <RelativeLayout android:id="@+id/mainlayout"
            android:layout_height="wrap_content" android:layout_width="match_parent">
            <com.google.android.maps.MapView
                android:id="@+id/mapview" android:layout_width="fill_parent"
                android:layout_height="fill_parent" android:clickable="true"
                android:apiKey="???????????????????????????????????????" />
        </RelativeLayout>
    </LinearLayout>

</LinearLayout>

Source for AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.as400samplecode" android:versionCode="1"
    android:versionName="1.0">
    <uses-sdk android:minSdkVersion="13" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

    <application android:icon="@drawable/icon" android:label="@string/app_name"
        android:theme="@android:style/Theme.Holo.Light">

        <uses-library android:required="true" android:name="com.google.android.maps" />
       
        <activity android:name=".GoogleMapsActivity" 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>

Please Note: You need maps API key for the above example to run. Registering for a Maps API Key is simple, free, and has two parts:

  1. Registering the MD5 fingerprint of the certificate that you will use to sign your application. The Maps registration service then provides you a Maps API Key that is associated with your application's signer certificate.
  2. Adding a reference to the Maps API Key in each MapView, whether declared in XML or instantiated directly from code. You can use the same Maps API Key for any MapView in any Android application, provided that the application is signed with the certificate whose fingerprint you registered with the service.

Click here for Obtaining a Maps API Key



Android capture signature using Canvas and save in png format

Signature capture has a lot of uses in enterprise applications such as proof of delivery, inspection forms, sales order agreement, etc. Here is sample program that asks for the name of the person and its signature. The program uses a canvas view to get the signature and then save it as .png Image.

Android capture signature using Canvas
Android capture signature using Canvas
Please Note: Initially when I wrote the signature capture program it was saving data to the External Storage but then I changed that to the Internal Storage for security. In the example you will see references to External storage that I didn't remove when I posted this example so please ignore that. Comments from the readers made me realize that some people need help with storing data to Internal and External Storage, click below for sample code ...
Android Internal and External storage example

In case you want signature capture for a WEB app or a Hybrid app then no further, click below for sample code ...
Capture signature using HTML5 canvas - Use for iPad, iPhone, Android Tablets and Phones

Source for CaptureSignatureActivity.java

package com.as400samplecode;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class CaptureSignatureActivity extends Activity {

    public static final int SIGNATURE_ACTIVITY = 1;

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

        Button getSignature = (Button) findViewById(R.id.signature);
        getSignature.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Intent intent = new Intent(CaptureSignatureActivity.this, CaptureSignature.class); 
                startActivityForResult(intent,SIGNATURE_ACTIVITY);
            }
        });
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        switch(requestCode) {
        case SIGNATURE_ACTIVITY: 
            if (resultCode == RESULT_OK) {

                Bundle bundle = data.getExtras();
                String status  = bundle.getString("status");
                if(status.equalsIgnoreCase("done")){
                    Toast toast = Toast.makeText(this, "Signature capture successful!", Toast.LENGTH_SHORT);
                    toast.setGravity(Gravity.TOP, 105, 50);
                    toast.show();
                }
            }
            break;
        }

    }  

}

Source for CaptureSignature.java

package com.as400samplecode;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Calendar;

import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore.Images;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

public class CaptureSignature extends Activity { 

    LinearLayout mContent;
    signature mSignature;
    Button mClear, mGetSign, mCancel;
    public static String tempDir;
    public int count = 1;
    public String current = null;
    private Bitmap mBitmap;
    View mView;
    File mypath;

    private String uniqueId;
    private EditText yourName;

    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.signature);
       
        tempDir = Environment.getExternalStorageDirectory() + "/" + getResources().getString(R.string.external_dir) + "/";
        ContextWrapper cw = new ContextWrapper(getApplicationContext());
        File directory = cw.getDir(getResources().getString(R.string.external_dir), Context.MODE_PRIVATE);

        prepareDirectory();
        uniqueId = getTodaysDate() + "_" + getCurrentTime() + "_" + Math.random();
        current = uniqueId + ".png";
        mypath= new File(directory,current);


        mContent = (LinearLayout) findViewById(R.id.linearLayout);
        mSignature = new signature(this, null);
        mSignature.setBackgroundColor(Color.WHITE);
        mContent.addView(mSignature, LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
        mClear = (Button)findViewById(R.id.clear);
        mGetSign = (Button)findViewById(R.id.getsign);
        mGetSign.setEnabled(false);
        mCancel = (Button)findViewById(R.id.cancel);
        mView = mContent;

        yourName = (EditText) findViewById(R.id.yourName);

        mClear.setOnClickListener(new OnClickListener() 
        {        
            public void onClick(View v) 
            {
                Log.v("log_tag", "Panel Cleared");
                mSignature.clear();
                mGetSign.setEnabled(false);
            }
        });

        mGetSign.setOnClickListener(new OnClickListener() 
        {        
            public void onClick(View v) 
            {
                Log.v("log_tag", "Panel Saved");
                boolean error = captureSignature();
                if(!error){
                    mView.setDrawingCacheEnabled(true);
                    mSignature.save(mView);
                    Bundle b = new Bundle();
                    b.putString("status", "done");
                    Intent intent = new Intent();
                    intent.putExtras(b);
                    setResult(RESULT_OK,intent);   
                    finish();
                }
            }
        });

        mCancel.setOnClickListener(new OnClickListener() 
        {        
            public void onClick(View v) 
            {
                Log.v("log_tag", "Panel Canceled");
                Bundle b = new Bundle();
                b.putString("status", "cancel");
                Intent intent = new Intent();
                intent.putExtras(b);
                setResult(RESULT_OK,intent);  
                finish();
            }
        });

    }

    @Override
    protected void onDestroy() {
        Log.w("GetSignature", "onDestory");
        super.onDestroy();
    }

    private boolean captureSignature() {

        boolean error = false;
        String errorMessage = "";


        if(yourName.getText().toString().equalsIgnoreCase("")){
            errorMessage = errorMessage + "Please enter your Name\n";
            error = true;
        }   

        if(error){
            Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.TOP, 105, 50);
            toast.show();
        }

        return error;
    }

    private String getTodaysDate() { 

        final Calendar c = Calendar.getInstance();
        int todaysDate =     (c.get(Calendar.YEAR) * 10000) + 
        ((c.get(Calendar.MONTH) + 1) * 100) + 
        (c.get(Calendar.DAY_OF_MONTH));
        Log.w("DATE:",String.valueOf(todaysDate));
        return(String.valueOf(todaysDate));

    }

    private String getCurrentTime() {

        final Calendar c = Calendar.getInstance();
        int currentTime =     (c.get(Calendar.HOUR_OF_DAY) * 10000) + 
        (c.get(Calendar.MINUTE) * 100) + 
        (c.get(Calendar.SECOND));
        Log.w("TIME:",String.valueOf(currentTime));
        return(String.valueOf(currentTime));

    }


    private boolean prepareDirectory() 
    {
        try 
        {
            if (makedirs()) 
            {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) 
        {
            e.printStackTrace();
            Toast.makeText(this, "Could not initiate File System.. Is Sdcard mounted properly?", 1000).show();
            return false;
        }
    }

    private boolean makedirs() 
    {
        File tempdir = new File(tempDir);
        if (!tempdir.exists())
            tempdir.mkdirs();

        if (tempdir.isDirectory()) 
        {
            File[] files = tempdir.listFiles();
            for (File file : files) 
            {
                if (!file.delete()) 
                {
                    System.out.println("Failed to delete " + file);
                }
            }
        }
        return (tempdir.isDirectory());
    }

    public class signature extends View 
    {
        private static final float STROKE_WIDTH = 5f;
        private static final float HALF_STROKE_WIDTH = STROKE_WIDTH / 2;
        private Paint paint = new Paint();
        private Path path = new Path();

        private float lastTouchX;
        private float lastTouchY;
        private final RectF dirtyRect = new RectF();

        public signature(Context context, AttributeSet attrs) 
        {
            super(context, attrs);
            paint.setAntiAlias(true);
            paint.setColor(Color.BLACK);
            paint.setStyle(Paint.Style.STROKE);
            paint.setStrokeJoin(Paint.Join.ROUND);
            paint.setStrokeWidth(STROKE_WIDTH);
        }

        public void save(View v) 
        {
            Log.v("log_tag", "Width: " + v.getWidth());
            Log.v("log_tag", "Height: " + v.getHeight());
            if(mBitmap == null)
            {
                mBitmap =  Bitmap.createBitmap (mContent.getWidth(), mContent.getHeight(), Bitmap.Config.RGB_565);;
            }
            Canvas canvas = new Canvas(mBitmap);
            try 
            {
                FileOutputStream mFileOutStream = new FileOutputStream(mypath);

                v.draw(canvas); 
                mBitmap.compress(Bitmap.CompressFormat.PNG, 90, mFileOutStream); 
                mFileOutStream.flush();
                mFileOutStream.close();
                String url = Images.Media.insertImage(getContentResolver(), mBitmap, "title", null);
                Log.v("log_tag","url: " + url);
                //In case you want to delete the file
                //boolean deleted = mypath.delete();
                //Log.v("log_tag","deleted: " + mypath.toString() + deleted);
                //If you want to convert the image to string use base64 converter

            }
            catch(Exception e) 
            { 
                Log.v("log_tag", e.toString()); 
            } 
        }

        public void clear() 
        {
            path.reset();
            invalidate();
        }

        @Override
        protected void onDraw(Canvas canvas) 
        {
            canvas.drawPath(path, paint);
        }

        @Override
        public boolean onTouchEvent(MotionEvent event) 
        {
            float eventX = event.getX();
            float eventY = event.getY();
            mGetSign.setEnabled(true);

            switch (event.getAction()) 
            {
            case MotionEvent.ACTION_DOWN:
                path.moveTo(eventX, eventY);
                lastTouchX = eventX;
                lastTouchY = eventY;
                return true;

            case MotionEvent.ACTION_MOVE:

            case MotionEvent.ACTION_UP:

                resetDirtyRect(eventX, eventY);
                int historySize = event.getHistorySize();
                for (int i = 0; i < historySize; i++) 
                {
                    float historicalX = event.getHistoricalX(i);
                    float historicalY = event.getHistoricalY(i);
                    expandDirtyRect(historicalX, historicalY);
                    path.lineTo(historicalX, historicalY);
                }
                path.lineTo(eventX, eventY);
                break;

            default:
                debug("Ignored touch event: " + event.toString());
                return false;
            }

            invalidate((int) (dirtyRect.left - HALF_STROKE_WIDTH),
                    (int) (dirtyRect.top - HALF_STROKE_WIDTH),
                    (int) (dirtyRect.right + HALF_STROKE_WIDTH),
                    (int) (dirtyRect.bottom + HALF_STROKE_WIDTH));

            lastTouchX = eventX;
            lastTouchY = eventY;

            return true;
        }

        private void debug(String string){
        }

        private void expandDirtyRect(float historicalX, float historicalY) 
        {
            if (historicalX < dirtyRect.left) 
            {
                dirtyRect.left = historicalX;
            } 
            else if (historicalX > dirtyRect.right) 
            {
                dirtyRect.right = historicalX;
            }

            if (historicalY < dirtyRect.top) 
            {
                dirtyRect.top = historicalY;
            } 
            else if (historicalY > dirtyRect.bottom) 
            {
                dirtyRect.bottom = historicalY;
            }
        }

        private void resetDirtyRect(float eventX, float eventY) 
        {
            dirtyRect.left = Math.min(lastTouchX, eventX);
            dirtyRect.right = Math.max(lastTouchX, eventX);
            dirtyRect.top = Math.min(lastTouchY, eventY);
            dirtyRect.bottom = Math.max(lastTouchY, eventY);
        }
    }
}

Source for 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">
    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:text="@string/hello"
        android:textSize="25sp" android:paddingBottom="20dp"
        android:textStyle="bold" />
    <Button android:text="Get My Signature" android:id="@+id/signature"
        android:layout_width="wrap_content" android:layout_height="wrap_content" />
</LinearLayout>

Source for signature.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="@+id/linearLayout1"
    android:layout_width="600dp" android:layout_height="400dp"
    android:orientation="vertical" xmlns:android="http://schemas.android.com/apk/res/android">
    <LinearLayout android:layout_height="wrap_content"
        android:id="@+id/linearLayout2" android:layout_width="match_parent">
        <Button android:layout_height="50dp" android:layout_weight=".30"
            android:text="Cancel" android:layout_width="0dp" android:id="@+id/cancel" />
        <Button android:layout_height="50dp" android:layout_weight=".35"
            android:text="Clear" android:layout_width="0dp" android:id="@+id/clear" />
        <Button android:layout_height="50dp" android:layout_weight=".35"
            android:text="Save" android:layout_width="0dp" android:id="@+id/getsign" />
    </LinearLayout>
    <TableLayout android:layout_height="wrap_content"
        android:id="@+id/tableLayout1" android:layout_width="match_parent">
        <TableRow android:id="@+id/tableRow1" android:layout_width="wrap_content"
            android:layout_height="wrap_content">
            <TextView android:layout_height="wrap_content" android:id="@+id/textView2"
                android:text="Your Name" android:textAppearance="?android:attr/textAppearanceMedium"
                android:layout_width="wrap_content" android:paddingLeft="10sp"
                android:layout_gravity="right" />
            <EditText android:layout_height="wrap_content" android:id="@+id/yourName"
                android:layout_weight="1" android:layout_width="match_parent"
                android:maxLength="30">
                <requestFocus />
            </EditText>
        </TableRow>
        <TableRow android:id="@+id/tableRow3" android:layout_width="wrap_content"
            android:layout_height="wrap_content">
            <TextView android:layout_height="wrap_content" android:id="@+id/textView2"
                android:text="" android:maxLength="30"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:layout_width="wrap_content" />
            <TextView android:layout_height="wrap_content" android:id="@+id/textView2"
                android:text="Please Sign below ..." android:maxLength="30"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:layout_width="wrap_content" />
        </TableRow>
    </TableLayout>
    <LinearLayout android:layout_height="match_parent"
        android:id="@+id/linearLayout" android:layout_width="match_parent" />
</LinearLayout>

Source for AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.as400samplecode" android:versionCode="1"
    android:versionName="1.0">
    <uses-sdk android:minSdkVersion="13" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
   
    <application android:icon="@drawable/icon" android:label="@string/app_name"
        android:theme="@android:style/Theme.Holo.Light">
        <activity android:name=".CaptureSignatureActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".CaptureSignature" android:label="Signature Confirmation"
            android:theme="@android:style/Theme.Holo.Light.Dialog" />
    </application>
</manifest>

Source for strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, CaptureSignatureActivity!</string>
    <string name="app_name">CaptureSignature</string>
    <string name="external_dir">GetSignature</string>
</resources>

Android capture signature using Canvas

Steps to Run the application on an Android Phone with Version 2.3.3 API level 10


1) Change your project build Target to Android 2.3.3


2) CaptureSignature manifest file Androidmanifest.xml with version and Theme changes as Holo theme is not available in API level 10.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.as400samplecode" android:versionCode="1"
    android:versionName="1.0">
    <uses-sdk android:minSdkVersion="10" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
   
    <application android:icon="@drawable/icon" android:label="@string/app_name"
        android:theme="@android:style/Theme.Light">
        <activity android:name=".CaptureSignatureActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".CaptureSignature" android:label="Signature Confirmation"
            android:theme="@android:style/Theme.Dialog" />
    </application>
</manifest>

3) Change the signature.xml file with new layout width and height
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="@+id/linearLayout1"
    android:layout_width="400dp" android:layout_height="300dp"
    .......


Signature capture in Android Phone with Version 2.3.3 API level 10
Signature capture in Android Phone with Version 2.3.3 API level 10

How to display the saved signature from base64 String

 //convert the string to byte array
 byte[] imageAsBytes = Base64.decode(myStringImage.getBytes());
 //get reference to the image view where you want to display the image
 ImageView image = (ImageView)this.findViewById(R.id.ImageView);
 //set the image by decoding the byte array to bitmap
 image.setImageBitmap(
  BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length)
 );

Store file on Tomcat Server or any other servlet container

Option 1: Get application Real path

filePath = getServletContext().getRealPath("") + "/docs/" + filename;

Option 2: Save the path in WEB.xml

filePath = getServletContext().getInitParameter("filePath") + "/docs/" + filename;

Create directory if one doesn't exists

File file = new File(filePath);
        if (!file.exists()) {
            file.mkdir();
        }

Android how to delete a file

File file = new File(myFilePath);
boolean deleted = file.delete();
Log.v("log_tag","deleted: " + deleted);

You must pass the complete path to file that you want to delete in myFilePath
Example: /data/data/com.as400samplecode/myDirectory/20111113_153214_abc.png

Android Shared Preferences example using PreferenceFragment - Store, fetch and edit

Android provides several options for you to save persistent application data and one of them is Shared Preferences. The solution you choose depends on your specific needs, such as whether the data should be private to your application or accessible to other applications (and the user) and how much space your data requires.

Your data storage options are the following:
  • Shared Preferences
    • Store private primitive data in key-value pairs.
  • Internal Storage
  • External Storage
  • SQLite Databases
  • Network Connection
Please note: This tutorial has been updated to use PreferenceFragment, addPreferencesFromResource method has been deprecated in in API level 11.

In this tutorial we are going to explore the Shared Preferences in many different ways 
  1. Shared Prefernces using the Preference activity
  2. Manipulate the Preference summary to display the value 
  3. Ability to put buttons on a preference screen for other actions
  4. Custom shared preferences not using Preference activity
Android Shared Preferences eclipse Project
Android Shared Preferences example
Android Standard Preferences
Android Preferences within Preferences
Android Preferences with Values displayed in Summary
Android custom Preferences without extending PreferenceActivity

The SharedPreferences class provides a general framework that allows you to save and retrieve persistent key-value pairs of primitive data types. You can use SharedPreferences to save any primitive data: booleans, floats, ints, longs, and strings. This data will persist across user sessions (even if your application is killed).

Shared preferences are not strictly for saving "user preferences," such as what ringtone a user has chosen.

To get a SharedPreferences object for your application, use one of two methods:
  • getSharedPreferences() 
    • Use this if you need multiple preferences files identified by name, which you specify with the first parameter.
  • getPreferences()
    • Use this if you need only one preferences file for your Activity. Because this will be the only preferences file for your Activity, you don't supply a name.

To write values:
  1. Call edit() to get a SharedPreferences.Editor.
  2. Add values with methods such as putBoolean() and putString().
  3. Commit the new values with commit()

To read values, use SharedPreferences methods such as getBoolean() and getString().

Andorid application manifest file - AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.as400samplecode"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="15"
        android:targetSdkVersion="15" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity 
            android:name=".Preferences" 
            android:label="@string/app_name"
   android:theme="@android:style/Theme.Holo.Light.Dialog.NoActionBar">
  </activity>
  <activity 
            android:name=".Preferences2" 
            android:label="@string/app_name"
   android:theme="@android:style/Theme.Holo.Light.Dialog.NoActionBar">
  </activity>
  <activity 
            android:name=".Preferences3" 
            android:label="@string/app_name"
   android:theme="@android:style/Theme.Holo.Light.Dialog.NoActionBar">
  </activity>
  <activity 
            android:name=".Preferences4" 
            android:label="@string/app_name"
   android:theme="@android:style/Theme.Holo.Light.Dialog.NoActionBar">
  </activity>
    </application>

</manifest>

Application strings resource - strings.xml

<resources>

    <string name="app_name">Android Shared Preferences</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">Android Preferences Tutorial and Sample Code</string>
    <string name="prefs_text1">Standard Preferences</string>
    <string name="prefs_text2">Preferences with value displayed as summary</string>
    <string name="prefs_text3">Custom Preferences without extending PreferenceActivity</string>

</resources>

Application array resource - arrays.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="listArray">
   <item>Dog</item>
   <item>Cat</item>
   <item>Other</item>
</string-array>
 
<string-array name="listValues">
   <item>1</item>
   <item>2</item>
   <item>3</item>
</string-array>
</resources>

Application main layout - activity_main.xml

<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
 android:layout_height="match_parent">

 <TextView android:id="@+id/textView1" android:layout_width="wrap_content"
  android:layout_height="wrap_content" android:layout_alignParentLeft="true"
  android:layout_alignParentTop="true" android:layout_marginLeft="10dp"
  android:layout_marginTop="10dp" android:text="@string/title_activity_main"
  android:textAppearance="?android:attr/textAppearanceMedium" />

 <Button android:id="@+id/preferences1" style="?android:attr/buttonStyleSmall"
  android:layout_width="fill_parent" android:layout_height="wrap_content"
  android:layout_alignParentLeft="true" android:layout_below="@+id/textView1"
  android:text="@string/prefs_text1" />

 <Button android:id="@+id/preferences2" style="?android:attr/buttonStyleSmall"
  android:layout_width="fill_parent" android:layout_height="wrap_content"
  android:layout_alignParentLeft="true" android:layout_below="@+id/preferences1"
  android:text="@string/prefs_text2" />

 <Button android:id="@+id/preferences3" style="?android:attr/buttonStyleSmall"
  android:layout_width="fill_parent" android:layout_height="wrap_content"
  android:layout_alignParentLeft="true" android:layout_below="@+id/preferences2"
  android:text="@string/prefs_text3" />

</RelativeLayout>

Application main Activity - MainActivity.java

package com.as400samplecode;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

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

  Button preferencesButton1 = (Button) findViewById(R.id.preferences1);
  preferencesButton1.setOnClickListener(new OnClickListener() {

   public void onClick(View v) {
    Intent settingsActivity = new Intent(getBaseContext(),
      Preferences.class);
    startActivity(settingsActivity);
   }
  });

  Button preferencesButton2 = (Button) findViewById(R.id.preferences2);
  preferencesButton2.setOnClickListener(new OnClickListener() {

   public void onClick(View v) {
    Intent settingsActivity = new Intent(getBaseContext(),
      Preferences3.class);
    startActivity(settingsActivity);
   }
  });

  Button preferencesButton3 = (Button) findViewById(R.id.preferences3);
  preferencesButton3.setOnClickListener(new OnClickListener() {

   public void onClick(View v) {
    Intent settingsActivity = new Intent(getBaseContext(),
      Preferences4.class);
    startActivity(settingsActivity);
   }
  });


 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  getMenuInflater().inflate(R.menu.activity_main, menu);
  return true;
 }
}

Standard Preferences XML layout - preferences.xml

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
 <PreferenceCategory android:title="My list of Preferences">
  <CheckBoxPreference android:title="Checkbox Preference"
   android:defaultValue="false" android:summary="This preference can be true or false"
   android:key="checkboxPref" />
  <ListPreference android:title="Your favorite Pet"
   android:summary="This preference allows to select an item in a array"
   android:key="listPref" android:defaultValue="digiGreen"
   android:entries="@array/listArray" android:entryValues="@array/listValues" />
  <EditTextPreference android:name="EditText Preference"
   android:summary="This allows you to enter a string"
   android:defaultValue="Nothing" android:title="Edit This Text"
   android:key="editTextPref" />
  <RingtonePreference android:name="Ringtone Preference"
   android:summary="Select a ringtone" android:title="Ringtones"
   android:key="ringtonePref" />
  <PreferenceScreen android:key="SecondPrefScreen"
   android:title="Secondary Level" android:summary="This is a sub PreferenceScreen">
   <intent android:action="android.intent.action.VIEW"
    android:targetPackage="com.as400samplecode" android:targetClass="com.as400samplecode.Preferences2" />
  </PreferenceScreen>
  <Preference android:title="Custom Preference"
   android:summary="This works almost like a button" android:key="customPref" />
 </PreferenceCategory>
</PreferenceScreen>

Standard Preferences Activity - Preferences.java

package com.as400samplecode;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
import android.widget.Toast;

public class Preferences extends PreferenceActivity {

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  getFragmentManager().beginTransaction().replace(android.R.id.content,
    new PrefsFragment()).commit();
  PreferenceManager.setDefaultValues(Preferences.this, R.xml.preferences, false);
  
 }
 
 public class PrefsFragment extends PreferenceFragment {
  
  @Override
  public void onCreate(Bundle savedInstanceState) {
   
   super.onCreate(savedInstanceState);
   addPreferencesFromResource(R.xml.preferences);
   
   // Get the custom preference
   Preference customPref = (Preference) findPreference("customPref");
   customPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {

    public boolean onPreferenceClick(Preference preference) {
     Toast.makeText(getBaseContext(), "The custom preference has been clicked",
       Toast.LENGTH_LONG).show();
     SharedPreferences customSharedPreference = getSharedPreferences(
       "myCustomSharedPrefs", Activity.MODE_PRIVATE);
     SharedPreferences.Editor editor = customSharedPreference.edit();
     editor.putString("myCustomPref", "The preference has been clicked");
     editor.commit();
     return true;
    }

   });
   
  }
  
 }
}

Standard sub Preferences XML layout - preferences2.xml

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
 <PreferenceCategory android:title="My secondary list of Preferences">
  <CheckBoxPreference android:title="Checkbox Preference"
   android:defaultValue="false" android:summary="This preference can be true or false"
   android:key="checkboxPref2" />
  <EditTextPreference android:name="EditText Preference"
   android:summary="This allows you to enter a string"
   android:defaultValue="Nothing" android:title="Edit This Text"
   android:key="editTextPref2" />
 </PreferenceCategory>
</PreferenceScreen>

Standard sub Preferences Activity - Preferences2.java

package com.as400samplecode;

import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;

public class Preferences2 extends PreferenceActivity {

 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getFragmentManager().beginTransaction().replace(android.R.id.content,
    new PrefsFragment()).commit();
  PreferenceManager.setDefaultValues(Preferences2.this, R.xml.preferences, false);
  
    }
 
 public static class PrefsFragment extends PreferenceFragment {
  
  @Override
  public void onCreate(Bundle savedInstanceState) {
   
   super.onCreate(savedInstanceState);
   addPreferencesFromResource(R.xml.preferences2);
  }
 }
 
}

Preferences with summary Text XML layout - preferences3.xml

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
 <PreferenceCategory android:title="Preferences with value displayed as summary">
  <EditTextPreference android:summary="Enter URL for Web Web Connetivity"
   android:defaultValue="" android:title="URL for connectivity"
   android:key="editURLPref" />
  <EditTextPreference android:summary="Enter Secret Word for secure Transactions"
   android:defaultValue="" android:title="Secret Word" android:key="editKey"
   android:password="true" />
 </PreferenceCategory>
</PreferenceScreen>

Preference window with close button XML layout - pref_window.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">
 <FrameLayout android:id="@+id/displayPrefs"
  android:layout_width="wrap_content" android:layout_height="wrap_content">
  <ListView android:id="@android:id/list" android:layout_width="fill_parent"
  android:layout_height="fill_parent" android:layout_weight="1" />
 </FrameLayout> 
 <LinearLayout android:layout_height="wrap_content"
  android:layout_width="match_parent" android:id="@+id/linearLayout1"
  android:layout_gravity="right" android:orientation="horizontal">
  <TextView android:layout_width="wrap_content"
   android:layout_height="wrap_content" android:text=" " android:id="@+id/textView1"
   android:layout_weight="1" />
  <Button android:layout_width="wrap_content" android:id="@+id/close"
   android:layout_height="wrap_content" android:text="Close" />
 </LinearLayout>
</LinearLayout>

Preferences with buttons and summary Text Activity - Preferences3.java

package com.as400samplecode;

import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceCategory;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class Preferences3 extends PreferenceActivity{

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.prefs_window);
  
  getFragmentManager().beginTransaction().replace(R.id.displayPrefs,
    new PrefsFragment()).commit();
  PreferenceManager.setDefaultValues(Preferences3.this, R.xml.preferences3, false);
  
  Button mClose = (Button)findViewById(R.id.close);
  mClose.setOnClickListener(new OnClickListener() 
  {         
   public void onClick(View v) 
   {
    finish();
   }
  });
  
 }

 public static class PrefsFragment extends PreferenceFragment implements OnSharedPreferenceChangeListener{

  @Override
  public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);

   addPreferencesFromResource(R.xml.preferences3);
   
   for(int i=0;i<getPreferenceScreen().getPreferenceCount();i++){
    initSummary(getPreferenceScreen().getPreference(i));
   }

  }
  
  @Override
  public void onResume(){
   super.onResume();
   // Set up a listener whenever a key changes             
   getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
  }

  @Override
  public void onPause() { 
   super.onPause();
   // Unregister the listener whenever a key changes             
   getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);     
  } 

  public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { 
   updatePrefSummary(findPreference(key));
  }

  private void initSummary(Preference p){
   if (p instanceof PreferenceCategory){
    PreferenceCategory pCat = (PreferenceCategory)p;
    for(int i=0;i<pCat.getPreferenceCount();i++){
     initSummary(pCat.getPreference(i));
    }
   }else{
    updatePrefSummary(p);
   }

  }

  private void updatePrefSummary(Preference p){
   if (p instanceof ListPreference) {
    ListPreference listPref = (ListPreference) p; 
    p.setSummary(listPref.getEntry()); 
   }
   if (p instanceof EditTextPreference) {
    EditTextPreference editTextPref = (EditTextPreference) p; 
    if(p.getKey().equalsIgnoreCase("editKey")){
     p.setSummary("I am not going to display a password!"); 
    }
    else {
     p.setSummary(editTextPref.getText()); 
    }
   }

  }

 }

}

Custom Preferences without PreferenceActivity XML layout - custom_pref.xml

<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
 android:layout_height="match_parent">

 <TextView android:id="@+id/textView1" android:layout_width="wrap_content"
  android:layout_height="wrap_content" android:layout_alignParentLeft="true"
  android:layout_alignParentTop="true" android:layout_marginTop="10dp"
  android:text="Custom Preferences without extending PreferenceActivity"
  android:textAppearance="?android:attr/textAppearanceMedium" />

 <TextView android:id="@+id/textView2" android:layout_width="wrap_content"
  android:layout_height="wrap_content" android:layout_alignParentLeft="true"
  android:layout_below="@+id/textView1" android:layout_marginTop="20dp"
  android:text="EditText Preference" android:textAppearance="?android:attr/textAppearanceMedium" />

 <EditText android:id="@+id/editText1" android:layout_width="wrap_content"
  android:layout_height="wrap_content" android:layout_alignParentLeft="true"
  android:layout_below="@+id/textView2" android:ems="10">

  <requestFocus />
 </EditText>

 <TextView android:id="@+id/textView3" android:layout_width="wrap_content"
  android:layout_height="wrap_content" android:layout_alignParentLeft="true"
  android:layout_below="@+id/editText1" android:text="Checkbox Preference"
  android:textAppearance="?android:attr/textAppearanceMedium" />

 <CheckBox android:id="@+id/checkBox1" android:layout_width="wrap_content"
  android:layout_height="wrap_content" android:layout_alignParentLeft="true"
  android:layout_below="@+id/textView3" android:text="CheckBox" />

 <TextView android:id="@+id/textView4" android:layout_width="wrap_content"
  android:layout_height="wrap_content" android:layout_alignParentLeft="true"
  android:layout_below="@+id/checkBox1" android:text="Radio Button Preference"
  android:textAppearance="?android:attr/textAppearanceMedium" />

 <RadioGroup android:id="@+id/radioGroup1"
  android:layout_width="wrap_content" android:layout_height="wrap_content"
  android:layout_alignParentLeft="true" android:layout_below="@+id/textView4">

  <RadioButton android:id="@+id/radio0"
   android:layout_width="wrap_content" android:layout_height="wrap_content"
   android:checked="true" android:text="RadioButton" />

  <RadioButton android:id="@+id/radio1"
   android:layout_width="wrap_content" android:layout_height="wrap_content"
   android:text="RadioButton" />

  <RadioButton android:id="@+id/radio2"
   android:layout_width="wrap_content" android:layout_height="wrap_content"
   android:text="RadioButton" />
 </RadioGroup>

 <Button android:id="@+id/save" style="?android:attr/buttonStyleSmall"
  android:layout_width="wrap_content" android:layout_height="wrap_content"
  android:layout_alignParentLeft="true" android:layout_below="@+id/radioGroup1"
  android:text="Save" />

 <Button android:id="@+id/close" style="?android:attr/buttonStyleSmall"
  android:layout_width="wrap_content" android:layout_height="wrap_content"
  android:layout_alignBaseline="@+id/save" android:layout_alignBottom="@+id/save"
  android:layout_toRightOf="@+id/save" android:text="Cancel" />

</RelativeLayout>

Custom Preferences without PreferenceActivity - Preferences4.java

package com.as400samplecode;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;


public class Preferences4 extends Activity {

 private EditText prefEditText;
 private CheckBox prefCheckbox;
 private RadioGroup prefRadioGroup;
 
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.custom_pref);

  SharedPreferences customSharedPreference = getSharedPreferences("myCustomSharedPrefs", Activity.MODE_PRIVATE);
  
  prefEditText = (EditText) findViewById(R.id.editText1);
  prefEditText.setText(customSharedPreference.getString("myEditTextPref", ""));
  
  prefCheckbox = (CheckBox) findViewById(R.id.checkBox1);
  prefCheckbox.setChecked(customSharedPreference.getBoolean("myCheckBoxPref", false));
  
  prefRadioGroup = (RadioGroup) findViewById(R.id.radioGroup1);
  RadioButton radioButton0 = (RadioButton) findViewById(R.id.radio0);
  prefRadioGroup.check(customSharedPreference.getInt("myRadioGroupPref",radioButton0.getId()));
  
  Button mClose = (Button)findViewById(R.id.close);
  mClose.setOnClickListener(new OnClickListener() 
  {         
   public void onClick(View v) 
   {
    finish();
   }
  });

  Button mSave = (Button)findViewById(R.id.save);
  mSave.setOnClickListener(new OnClickListener() 
  {         
   public void onClick(View v) 
   {
    savePreferences();
    finish();
   }
  });

 }

 private void savePreferences(){

  SharedPreferences customSharedPreference = getSharedPreferences("myCustomSharedPrefs", Activity.MODE_PRIVATE);
  SharedPreferences.Editor editor = customSharedPreference.edit();
  editor.putString("myEditTextPref", prefEditText.getText().toString());
  editor.putBoolean("myCheckBoxPref",prefCheckbox.isChecked());
  editor.putInt("myRadioGroupPref", prefRadioGroup.getCheckedRadioButtonId());
  editor.commit();

  RadioButton radioButton = (RadioButton) findViewById(prefRadioGroup.getCheckedRadioButtonId());
  Log.v("Preferences:", "Radio Text: " + radioButton.getText());
 }
}