Jan 17, 2013

Get Latitude and Longitude from gpx file

GPX, or GPS eXchange Format is an XML schema designed as a common GPS data format for software applications.

It can be used to describe waypoints, tracks, and routes. The format is open and can be used without the need to pay license fees. Its tags store location, elevation, and time and can in this way be used to interchange data between GPS devices and software packages. Such computer programs allow users, for example, to view their tracks, project their tracks on satellite images or other maps, annotate maps, and tag photographs with the geolocation in the Exif metadata.

~ source: Wikipedia - GPS eXchange Format.

This example demonstrate how to parse gpx file, to generate a list of Location.

Get Latitude and Longitude from gpx file


Create a text file "test.gpx", copy and modify from the example in Wikipedia - GPS eXchange Format, save in temp folder of Android device's sdcard.
/sdcard/temp/test.gpx
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>

<gpx xmlns="http://www.topografix.com/GPX/1/1" xmlns:gpxx="http://www.garmin.com/xmlschemas/GpxExtensions/v3" xmlns:gpxtpx="http://www.garmin.com/xmlschemas/TrackPointExtension/v1" creator="Oregon 400t" version="1.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd http://www.garmin.com/xmlschemas/GpxExtensions/v3 http://www.garmin.com/xmlschemas/GpxExtensionsv3.xsd http://www.garmin.com/xmlschemas/TrackPointExtension/v1 http://www.garmin.com/xmlschemas/TrackPointExtensionv1.xsd">
  <metadata>
    <link href="http://www.garmin.com">
      <text>Garmin International</text>
    </link>
    <time>2009-10-17T22:58:43Z</time>
  </metadata>
  <trk>
    <name>Example GPX Document</name>
    <trkseg>
      <trkpt lat="47.644548" lon="-122.326897">
        <ele>4.46</ele>
        <time>2009-10-17T18:37:26Z</time>
      </trkpt>
      <trkpt lat="47.644001" lon="-122.326001">
        <ele>4.94</ele>
        <time>2009-10-17T18:37:31Z</time>
      </trkpt>
      <trkpt lat="47.644002" lon="-122.326002">
        <ele>6.87</ele>
        <time>2009-10-17T18:37:34Z</time>
      </trkpt>
    </trkseg>
  </trk>
</gpx>


package com.example.androidcodinggpx;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import android.location.Location;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  String path = Environment.getExternalStorageDirectory().toString() + "/temp/test.gpx";
  
  TextView textInfo = (TextView)findViewById(R.id.info);
  String info = "";
  
  File gpxFile = new File(path);
  info += gpxFile.getPath() +"\n\n";
  

  List<Location> gpxList = decodeGPX(gpxFile);

  for(int i = 0; i < gpxList.size(); i++){
   info += ((Location)gpxList.get(i)).getLatitude() 
     + " : " 
     + ((Location)gpxList.get(i)).getLongitude() + "\n";
  }
  
  textInfo.setText(info);
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  getMenuInflater().inflate(R.menu.activity_main, menu);
  return true;
 }
 
 private List<Location> decodeGPX(File file){
  List<Location> list = new ArrayList<Location>();

  DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
  try {
   DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
   FileInputStream fileInputStream = new FileInputStream(file);
   Document document = documentBuilder.parse(fileInputStream);
   Element elementRoot = document.getDocumentElement();
   
   NodeList nodelist_trkpt = elementRoot.getElementsByTagName("trkpt");

   for(int i = 0; i < nodelist_trkpt.getLength(); i++){
    
    Node node = nodelist_trkpt.item(i);
    NamedNodeMap attributes = node.getAttributes();
    
    String newLatitude = attributes.getNamedItem("lat").getTextContent();
    Double newLatitude_double = Double.parseDouble(newLatitude);
    
    String newLongitude = attributes.getNamedItem("lon").getTextContent();
    Double newLongitude_double = Double.parseDouble(newLongitude);
    
    String newLocationName = newLatitude + ":" + newLongitude;
    Location newLocation = new Location(newLocationName);
    newLocation.setLatitude(newLatitude_double);
    newLocation.setLongitude(newLongitude_double);
    
    list.add(newLocation);

   }
   
   fileInputStream.close();
   
  } catch (ParserConfigurationException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (SAXException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
  return list;
 }


}


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/info"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

</LinearLayout>


Next: GPX decoding in Android, with custom class.

Jan 10, 2013

Get location from mobile or WIFI networks

Refer to last post, modify the String PROVIDER = LocationManager.NETWORK_PROVIDER to make it determines location based on availability of cell tower and WiFi access points. Results of location are retrieved by means of a network lookup.

 //String PROVIDER = LocationManager.GPS_PROVIDER;
 String PROVIDER = LocationManager.NETWORK_PROVIDER;


Get location from GPS

Android system provide android.location.LocationManager class to access the system location services. These services allow applications to obtain periodic updates of the device's geographical location, or to fire an application-specified Intent when the device enters the proximity of a given geographical location.

You do not instantiate this class directly; instead, retrieve it through Context.getSystemService(Context.LOCATION_SERVICE).

All Location API methods require the ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permissions. If your application only has the coarse permission then it will not have access to the GPS or passive location providers. Other providers will still return location results, but the update rate will be throttled and the exact location will be obfuscated to a coarse level of accuracy.

Example:
Get location from GPS


package com.example.androidmylocation;

import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.widget.TextView;

public class MainActivity extends Activity {

 TextView testViewStatus, textViewLatitude, textViewLongitude;
 
 LocationManager myLocationManager;
 String PROVIDER = LocationManager.GPS_PROVIDER;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  testViewStatus = (TextView)findViewById(R.id.status);
  textViewLatitude = (TextView)findViewById(R.id.latitude);
  textViewLongitude = (TextView)findViewById(R.id.longitude);
  
  myLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
  
  //get last known location, if available
  Location location = myLocationManager.getLastKnownLocation(PROVIDER);
  showMyLocation(location); 
 }
 
 @Override
 protected void onPause() {
  // TODO Auto-generated method stub
  super.onPause();
  myLocationManager.removeUpdates(myLocationListener);
 }

 @Override
 protected void onResume() {
  // TODO Auto-generated method stub
  super.onResume();
  myLocationManager.requestLocationUpdates(
    PROVIDER,     //provider
    0,       //minTime
    0,       //minDistance
    myLocationListener); //LocationListener
 }

 private void showMyLocation(Location l){
  if(l == null){
   testViewStatus.setText("No Location!");
  }else{
   textViewLatitude.setText("Latitude: " + l.getLatitude());
   textViewLongitude.setText("Longitude: " + l.getLongitude());
  }
  
 }
 
 private LocationListener myLocationListener
 = new LocationListener(){

  @Override
  public void onLocationChanged(Location location) {
   showMyLocation(location);
  }

  @Override
  public void onProviderDisabled(String provider) {
   // TODO Auto-generated method stub
   
  }

  @Override
  public void onProviderEnabled(String provider) {
   // TODO Auto-generated method stub
   
  }

  @Override
  public void onStatusChanged(String provider, int status, Bundle extras) {
   // TODO Auto-generated method stub
   
  }};

}


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
    <TextView
        android:id="@+id/status"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>
    <TextView
        android:id="@+id/latitude"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>
    <TextView
        android:id="@+id/longitude"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.androidmylocation"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="16" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.androidmylocation.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>
    </application>

</manifest>


Related:
- Get location from mobile or WIFI networks


Jan 9, 2013

Get various version strings of Android devices

Get various version strings of Android devices


package com.example.androidsysinfo;

import android.os.Build;
import android.os.Bundle;
import android.app.Activity;
import android.widget.TextView;

public class MainActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  //setContentView(R.layout.activity_main);
  TextView infoView = new TextView(this);
  setContentView(infoView);
  
  String version = "Version:\n";
  
  version += "CODENAME: " + Build.VERSION.CODENAME + "\n"
    +  "INCREMENTAL: " + Build.VERSION.INCREMENTAL + "\n"
    +  "RELEASE: " + Build.VERSION.RELEASE + "\n"
    +  "SDK_INT: " + Build.VERSION.SDK_INT + "\n"
    +  "\n";
  
  infoView.setText(version);
 }

}


Related: Get Android system info

Jan 8, 2013

Get Android system info

To get Android system info, we can read information about the current build from android.os.Build. The information are extracted from system properties.

package com.example.androidsysinfo;

import android.os.Build;
import android.os.Bundle;
import android.app.Activity;
import android.widget.TextView;

public class MainActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  //setContentView(R.layout.activity_main);
  TextView infoView = new TextView(this);
  setContentView(infoView);
  
  String info = "System Info:\n";
  
  info += "BOARD: " + Build.BOARD + "\n"
     + "BOOTLOADER: " + Build.BOOTLOADER + "\n"
     + "BRAND: " + Build.BRAND + "\n"
     + "CPU_ABI: " + Build.CPU_ABI + "\n"
     + "CPU_ABI2: " + Build.CPU_ABI2 + "\n"
     + "DEVICE: " + Build.DEVICE + "\n"
     + "DISPLAY: " + Build.DISPLAY + "\n"
     + "FINGERPRINT: " + Build.FINGERPRINT + "\n"
     + "HARDWARE: " + Build.HARDWARE + "\n"
     + "HOST: " + Build.HOST + "\n"
     + "ID: " + Build.ID + "\n"
     + "MANUFACTURER: " + Build.MANUFACTURER + "\n"
     + "MODEL: " + Build.MODEL + "\n"
     + "PRODUCT: " + Build.PRODUCT + "\n"
     + "SERIAL: " + Build.SERIAL + "\n"
     + "TAGS: " + Build.TAGS + "\n"
     + "TIME: " + Build.TIME + "\n"
     + "TYPE: " + Build.TYPE + "\n"
     + "USER: " + Build.USER + "\n"
     + "RadioVersion: " + Build.getRadioVersion() + "\n"
     +" \n";
  
  infoView.setText(info);
 }

}


Android system info


Related: Get various version strings of Android devices

Infolinks In Text Ads