Jan 30, 2013

List files with specified extension using listFiles() with FilenameFilter.

To list all files in a folder, we can call listFiles() method. If you want to list only the files with specified extension, you can call listFiles(FilenameFilter filter) with custom FilenameFilter.

Example:

package com.example.androidlistfile;

import java.io.File;
import java.io.FilenameFilter;

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

public class MainActivity extends Activity {
 
 File root;
 File[] fileArray;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TextView textView = new TextView(this);
        setContentView(textView);
        
        root = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
        fileArray = root.listFiles(new FilenameFilter(){

   @Override
   public boolean accept(File dir, String filename) {
    return filename.toLowerCase().endsWith(".jpg");
   }});
        
        String f = root.getAbsolutePath() + "\n\n";
        for(int i=0; i < fileArray.length; i++){
         f += fileArray[i].getName() + "\n";
        }
        textView.setText(f);
    }

}

List files with specified extension using listFiles() with FilenameFilter.

Jan 29, 2013

Two or more marquee TextView run at the same time

Refer to the article "Implement auto scroll TextView in XML" to implement auto run marquee TextView. If more than one marquee TextView are included in a same layout, only one of them will run. To enable all run at the same time, call setSelected(true) method of the TextViews.

Two or more marquee TextView run at the same time


<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/marqueetext1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:singleLine="true"
        android:scrollHorizontally="true"
        android:ellipsize="marquee"
        android:marqueeRepeatLimit ="marquee_forever"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:text="Hello AndroidCoding: http://android-coding.blogspot.com/" />
    <TextView
        android:id="@+id/marqueetext2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:singleLine="true"
        android:scrollHorizontally="true"
        android:ellipsize="marquee"
        android:marqueeRepeatLimit ="marquee_forever"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:text="Hello AndroidCoding: http://android-coding.blogspot.com/" />

</LinearLayout>


package com.example.androidtext;

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 marqueeText1 = (TextView)findViewById(R.id.marqueetext1);
        TextView marqueeText2 = (TextView)findViewById(R.id.marqueetext2);
        marqueeText1.setSelected(true);
        marqueeText2.setSelected(true);
    }
    
}


Call getLayoutInflater() with Context

If you have to get LayoutInflater object with Context, in case of not in Activity. Call getLayoutInflater() with context using the code:

   
   LayoutInflater inflater = 
     (LayoutInflater)myContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE );
   


Jan 28, 2013

Draw icon beside text, using XML.

We can assign android:drawableLeft, drawableTop, drawableRight and drawableBottom to draw drawable icon beside text. Here show how to draw icon on right of text inside TextView and Button, using XML.

Draw icon beside test within TextView/Button

<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:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:singleLine="true"
        android:scrollHorizontally="true"
        android:ellipsize="marquee"
        android:marqueeRepeatLimit ="marquee_forever"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:text="Hello AndroidCoding: http://android-coding.blogspot.com/" 
        android:drawableRight="@drawable/ic_launcher"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:drawableRight="@drawable/ic_launcher"
        android:text="Button with icon"/>

</LinearLayout>


Jan 27, 2013

Implement auto scroll TextView in XML

Here demonstrate how to implement a auto scroll horizontally TextView in XML.

<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:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:singleLine="true"
        android:scrollHorizontally="true"
        android:ellipsize="marquee"
        android:marqueeRepeatLimit ="marquee_forever"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:text="Hello AndroidCoding: http://android-coding.blogspot.com/" />

</LinearLayout>

auto scroll horizontally TextView


If you define more than one marquee TextView in the layout, only the first one will run. To enable them run together, refer HERE.

Jan 25, 2013

Get extension and MIME type of file using MimeTypeMap

Example to get extension and MIME type of file using MimeTypeMap.

 String extension = MimeTypeMap.getFileExtensionFromUrl(fileUrl);
 String mimetype = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);


Jan 24, 2013

Define and apply style on text

To define style, create a xml in res/values/ directory, The name is arbitrary. For example: mystle.xml.

/res/values/mystyle.xml
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android">
    <style name="bigred_mono" parent="@android:style/TextAppearance.Medium">
        <item name="android:layout_width">fill_parent</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:textSize">30sp</item>
        <item name="android:textColor">#FF0000</item>
        <item name="android:typeface">monospace</item>
    </style>
    <style name="smallblue" parent="@android:style/TextAppearance.Medium">
        <item name="android:layout_width">fill_parent</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:textSize">10sp</item>
        <item name="android:textColor">#0000FF</item>
    </style>
</resources>


Then, you can apply the style in your layout xml.

<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:layout_width="wrap_content"
        android:layout_height="wrap_content"
        style="@style/bigred_mono"
        android:text="It's bigred_mono" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        style="@style/smallblue"
        android:text="It's smallblue" />

</LinearLayout>


Define and apply style on text

Jan 22, 2013

Example of using SimpleDateFormat

The example demonstrate how to convert a Date object to string using a specified format, and convert back.

SimpleDateFormat

package com.example.androidsimpledateformat;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
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 dateNow = (TextView)findViewById(R.id.datenow);
        TextView dateFormatted = (TextView)findViewById(R.id.dateformatted);
        TextView dateBack = (TextView)findViewById(R.id.dateback);
        
        //Initializes this Date instance to the current time.
        Date now = new Date();
        
        //Convert current time to String using specified format
        String format = "yyyy-MM-dd'T'HH:mm:ssZ";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format, Locale.US);
        String formattedNow = simpleDateFormat.format(now);
        
        //Convert the string back to Date object
        Date dateConvertBack = null;
        try {
   dateConvertBack = simpleDateFormat.parse(formattedNow);
  } catch (ParseException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
        
        dateNow.setText(now.toString());
        dateFormatted.setText(formattedNow);
        dateBack.setText(dateConvertBack.toString());
    }
    
}


<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/datenow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    <TextView
        android:id="@+id/dateformatted"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    <TextView
        android:id="@+id/dateback"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</LinearLayout>


Jan 18, 2013

GPX decoding in Android, with time and ele.

Read last two article "Get Latitude and Longitude from gpx file" and "GPX decoding in Android, with custom class", it's further modified to decode "time" and "ele" also.

GPX decoding in Android, with time and ele.


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<GpxNode> gpxList = decodeGPX(gpxFile);

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

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  getMenuInflater().inflate(R.menu.activity_main, menu);
  return true;
 }
 
 class GpxNode{
  
  Location location;
  String ele;
  String time;
  
  GpxNode(){
   location = null;
   ele = "";
   time = "";
  }
  
  GpxNode(Location loc){
   location = loc;
   ele = "";
   time = "";
  }
  
  GpxNode(Location loc, String e, String t){
   location = loc;
   ele = e;
   time = t;
  }
  
  void setEle(String e){
   ele = e;
  }
  
  void setTime(String t){
   time = t;
  }
  
  Location getLocation(){
   return location;
  }
  
  String getLocationString(){
   return location.getLatitude() + ":" + location.getLongitude();
  }
  
  String getGpsNodeInfo(){
   return location.getLatitude() + ":" + location.getLongitude() + "\n"
     + time + "\n"
     + ele + "\n";
  }
 }
 
 private List<GpxNode> decodeGPX(File file){
  List<GpxNode> list = new ArrayList<GpxNode>();

  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);
    
    NodeList childNodes = node.getChildNodes();
    
    String newEle = searchNodeListForTaget(childNodes, "ele");
    String newTime = searchNodeListForTaget(childNodes, "time");
    
    //insert in list
    GpxNode newGpxNode = new GpxNode(newLocation, newEle, newTime);
    list.add(newGpxNode);

   }
   
   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;
 }
 
 String searchNodeListForTaget(NodeList src, String target){
  
  for(int i = 0; i < src.getLength(); i++){
   Node n = src.item(i);
   if (n.getNodeName().equals(target)){
    return n.getFirstChild().getNodeValue();
   }
  }
  return "";
 }

}


GPX decoding in Android, with custom class.

Last post describe "Get Latitude and Longitude from gpx file on Android". In order to prepare further expand the function, a custom class, GpxNode, is implemented. It will be enrich in further post.

GPX decoding in Android


It have the same output as in the last article "Get Latitude and Longitude from gpx file".

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<GpxNode> gpxList = decodeGPX(gpxFile);

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

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  getMenuInflater().inflate(R.menu.activity_main, menu);
  return true;
 }
 
 class GpxNode{
  
  Location location;
  String ele;
  String time;
  
  GpxNode(){
   location = null;
   ele = "";
   time = "";
  }
  
  GpxNode(Location loc){
   location = loc;
   ele = "";
   time = "";
  }
  
  GpxNode(Location loc, String e, String t){
   location = loc;
   ele = e;
   time = t;
  }
  
  void setEle(String e){
   ele = e;
  }
  
  void setTime(String t){
   time = t;
  }
  
  Location getLocation(){
   return location;
  }
  
  String getLocationString(){
   return location.getLatitude() + ":" + location.getLongitude();
  }
  
 }
 
 private List<GpxNode> decodeGPX(File file){
  List<GpxNode> list = new ArrayList<GpxNode>();

  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);
    
    GpxNode newGpxNode = new GpxNode(newLocation);
    list.add(newGpxNode);

   }
   
   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;
 }

}


Next: GPX decoding in Android, with time and ele.

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

Jan 4, 2013

Implement TextToSpeech (TTS) function, with TTS engine selectable.

Last two article demonstrate how to Get installed TTS engines and Get features supported by various installed TextToSpeech Engine. Now we can make it speak with the selected TTS Engine.

Implement TextToSpeech (TTS) function, with TTS engine selectable.


package com.example.androidtexttospeech;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Set;

import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.EngineInfo;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.app.Activity;

public class MainActivity extends Activity implements OnInitListener{
 
 TextView tvDefaultTTS, tvTTSInfo;
 EditText textIn;
 Button buttoSpeak;
 
 Spinner spInstalledEngines;
 TextToSpeech tts;
 List<TextToSpeech.EngineInfo> listInstalledEngines;
 List<String> listInstalledEnginesName;
 String defaultTTS;
 
 private ArrayAdapter<String> adapter;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  tvDefaultTTS = (TextView)findViewById(R.id.defaulttts);
  spInstalledEngines = (Spinner)findViewById(R.id.installedengines);
  tvTTSInfo = (TextView)findViewById(R.id.ttsinfo);
  
  tts = new TextToSpeech(this, this);
  listInstalledEngines = tts.getEngines();
  listInstalledEnginesName = new ArrayList<String>();

        for(int i = 0; i < listInstalledEngines.size(); i++){
         listInstalledEnginesName.add(listInstalledEngines.get(i).label);
        }
        
        adapter = new ArrayAdapter<String>(
    this, android.R.layout.simple_spinner_item, listInstalledEnginesName);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spInstalledEngines.setAdapter(adapter);
  
        defaultTTS = tts.getDefaultEngine();
        tvDefaultTTS.setText("Default TTS Engine: " + defaultTTS);
        
        spInstalledEngines.setOnItemSelectedListener(myOnItemSelectedListener);
        
        textIn = (EditText)findViewById(R.id.textin);
        textIn.setText("Android Coding"); //pre-set text
     buttoSpeak = (Button)findViewById(R.id.speak);
     buttoSpeak.setOnClickListener(new OnClickListener(){

   @Override
   public void onClick(View v) {
    String textToBeSpeech = textIn.getText().toString();
       tts.speak(textToBeSpeech, TextToSpeech.QUEUE_ADD, null);
    
   }});
     
 }
 
 OnItemSelectedListener myOnItemSelectedListener
 = new OnItemSelectedListener(){

  @Override
  public void onItemSelected(AdapterView<?> parent, View iew, int position,
    long id) {
   
   //shutdown old tts
   if(tts != null){
    tts.shutdown();
   }
   
   //switch to new tts
   EngineInfo selectedEngineInfo = listInstalledEngines.get(position);
   String engine = selectedEngineInfo.name;
   tts = new TextToSpeech(MainActivity.this, MainActivity.this, engine);
   
  }

  @Override
  public void onNothingSelected(AdapterView<?> arg0) {
   // TODO Auto-generated method stub
   
  }};
 
 private void updateTTSInfo(){
  
  String info = "";
  
  Locale locale = tts.getLanguage();
  
  if(locale != null){
   info += "Country: " + locale.getDisplayCountry() + "\n"
     + "Language: " + locale.getDisplayLanguage() + "\n";
   
   Set<String> feature = tts.getFeatures(locale);
   
   String[] featureArray = new String[feature.size()];
   feature.toArray(featureArray);
   for(int i = 0; i < featureArray.length; i++){
    info += "feature : " + featureArray[i] + "\n";
   }
  }
  
  tvTTSInfo.setText(info);
 }

 @Override
 public void onInit(int status) {
  updateTTSInfo();
 }

 @Override
 protected void onDestroy() {
  // TODO Auto-generated method stub
  super.onDestroy();
  tts.shutdown();
 }

}


<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:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/hello_world" />
    <TextView
        android:id="@+id/defaulttts"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>
    <Spinner 
        android:id="@+id/installedengines"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    <EditText
        android:id="@+id/textin"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    <Button
        android:id="@+id/speak"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Speak"/>
    <TextView
        android:id="@+id/ttsinfo"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>
    
</LinearLayout>


Jan 3, 2013

Get features supported by TextToSpeech Engine

From Android API level 15, getFeatures(Locale locale) method of TextToSpeech was provided to queries the engine for the set of features it supports for a given locale.

Here is a example demonstrate how to get supported features from TextToSpeech Engineer.

Get features supported by TextToSpeech Engine


package com.example.androidtexttospeech;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Set;

import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.EngineInfo;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.app.Activity;

public class MainActivity extends Activity implements OnInitListener{
 
 TextView tvDefaultTTS, tvTTSInfo;
 
 Spinner spInstalledEngines;
 TextToSpeech tts;
 List<TextToSpeech.EngineInfo> listInstalledEngines;
 List<String> listInstalledEnginesName;
 String defaultTTS;
 
 private ArrayAdapter<String> adapter;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  tvDefaultTTS = (TextView)findViewById(R.id.defaulttts);
  spInstalledEngines = (Spinner)findViewById(R.id.installedengines);
  tvTTSInfo = (TextView)findViewById(R.id.ttsinfo);
  
  tts = new TextToSpeech(this, this);
  listInstalledEngines = tts.getEngines();
  listInstalledEnginesName = new ArrayList<String>();

        for(int i = 0; i < listInstalledEngines.size(); i++){
         listInstalledEnginesName.add(listInstalledEngines.get(i).label);
        }
        
        adapter = new ArrayAdapter<String>(
    this, android.R.layout.simple_spinner_item, listInstalledEnginesName);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spInstalledEngines.setAdapter(adapter);
  
        defaultTTS = tts.getDefaultEngine();
        tvDefaultTTS.setText("Default TTS Engine: " + defaultTTS);
        
        spInstalledEngines.setOnItemSelectedListener(myOnItemSelectedListener);
 }
 
 OnItemSelectedListener myOnItemSelectedListener
 = new OnItemSelectedListener(){

  @Override
  public void onItemSelected(AdapterView<?> parent, View iew, int position,
    long id) {
   
   //shutdown old tts
   if(tts != null){
    tts.shutdown();
   }
   
   //switch to new tts
   EngineInfo selectedEngineInfo = listInstalledEngines.get(position);
   String engine = selectedEngineInfo.name;
   tts = new TextToSpeech(MainActivity.this, MainActivity.this, engine);
   
  }

  @Override
  public void onNothingSelected(AdapterView<?> arg0) {
   // TODO Auto-generated method stub
   
  }};
 
 private void updateTTSInfo(){
  
  String info = "";
  
  Locale locale = tts.getLanguage();
  
  if(locale != null){
   info += "Country: " + locale.getDisplayCountry() + "\n"
     + "Language: " + locale.getDisplayLanguage() + "\n";
   
   Set<String> feature = tts.getFeatures(locale);
   
   String[] featureArray = new String[feature.size()];
   feature.toArray(featureArray);
   for(int i = 0; i < featureArray.length; i++){
    info += "feature : " + featureArray[i] + "\n";
   }
  }
  
  tvTTSInfo.setText(info);
 }

 @Override
 public void onInit(int status) {
  updateTTSInfo();
 }

 @Override
 protected void onDestroy() {
  // TODO Auto-generated method stub
  super.onDestroy();
  tts.shutdown();
 }

}


<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:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/hello_world" />
    <TextView
        android:id="@+id/defaulttts"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>
    <Spinner 
        android:id="@+id/installedengines"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    <TextView
        android:id="@+id/ttsinfo"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>
    
</LinearLayout>


Please notice that in order to call getFeatures(Locale locale), android:minSdkVersion in AndroidManifest.xml have to be set at least "15".

Next: Implement TextToSpeech (TTS) function, with TTS engine selectable.


Infolinks In Text Ads