Location tracker in Android using GPS positioning and SQLite

Introduction

Android is an Open source software stack which has gained market in leaps and bounce. This includes operating system, middleware and key applications. The advantage android brings along with it is the ease of application development. Android application can be developed at a brisk rate with lesser learning curve using the tools and API provided by Android SDK. The tools and key applications have made the life of developers very easy.

Android basically has Linux as the core operating system with a Java interface. Android applications are run on Dalvik Virtual Machines. Each android application will run on different instances of DVM. Dalvik has the capabilities to run different VM’s efficiently. SQLite is Android specific database available by default in Android phones. SQLite is a lightweight and powerful database engine, and can be used in any type of application development.

also read:

SQLite Database in Android

Every mobile application might be handling data which have to be permanently stored and retrieved at a later instance of time. In android, SQLite is a lightweight database which is embedded into the platform by default. Most of the common database operations can be done using methods available in SQLite. The syntax is very similar to SQL syntax.

SQLite is a lightweight database which does not require any configuration. As the memory space required is minimal, it is suitable for mobile applications.

Android SDK provides two classes, which can be used by developers in order to use SQLite.

  • SQLiteOpenHelper- This class helps in creating the database and controlling version changes
  • SQLiteDatabase- This class helps in performing basic database operations

GPS in Android

Nowadays we are seeing many application related to location provider or location finder. The technique explained in this document may be used in developing several applications like Find a friend, get the updates about the location when you enter near the proximity of a given location etc.

To build a location based application classes are available in the android library, like Location Provider , Location Manager , Location etc . To find the location of the particular device Location Listener interface should be implemented by the class.

Introduction to the application

The document explains SQLite and Location Provider through an application which gets the GPS location and saves the location details in the database.

Step 1:

Create a simple android project. The project will have the below folder structure.

Step 2:

Create a class named as ‘GPSLocation’ in com.demo package. The class should extend ‘Activity’ class.

public class GPSLocation extends Activity {
		public void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			setContentView(R.layout.main);
		}
	}

Step 3:

Create an inner class named as ”MylocListener’. This class implements ‘LocationListerner’ interface.It is used for receiving notification from the LocationManager class when the location changes. LocationManager class is an inbuilt class in Android which allows applications to obtain latitude and longitude co-ordinates of the mobile device.

LocationListener interface has four unimplemented methods which have to be implemented in MylocListener class.

  • onLocationChanged()- Whenever location has been changed for a device the LocationManager class will implicitly call this method passing the new location has a parameter in the form of location object.
  • onProviderDisabled
  • onStatusChanged
  • onProviderEnabled

The other three methods can be left blank as those are not required in this application.

public class MylocListener implements LocationListener {
		public void onLocationChanged(Location loc) {
			// TODO Auto-generated method stub
            String text = " My location is  Latitude ="+loc.getLatitude() + " Longitude =" + loc.getLongitude();
            lat=loc.getLatitude() + "";
            log=loc.getLongitude()+"";
            updateDatabase();
		}
		public void onProviderDisabled(String provider) {
			// TODO Auto-generated method stub
		}
		public void onProviderEnabled (String provider) {
			// TODO Auto-generated method stub
		}
		public void onStatusChanged(String provider, int status, Bundle extras) {
			// TODO Auto-generated method stub
		}
	}

The onLocationChanged methods has Location object as a parameter. The latitude and longitude of the location can be obtained from this object by using getLatitude() and getLognitude() methods.

Step 4:

Inside the onCreate() method create an instance of LocationManager class. getSystemService is an inbuilt method available for getting the handler on a particular service by passing appropriate service name. Here the service name is ‘LOCATION_SERVICE’.
Create a reference of LocationListener and initialize with the inner class created in Step 3. The inner class implements LocationListner interface. From ‘mylocman’ object call the method named as requestLocationUpdates(). This methods accepts four parameters, namely:

  • The default GPS provider available in the mobile device
  • Minimum time internal between successive notification
  • Minimum distance internal between successive notification in meters
  • The LocationListener object, whose onLocationChanged() method will be called for each location update
LocationManager mylocman = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
	LocationListener myloclist = new MylocListener();
	mylocman.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,myloclist);

Step 5:

The GPS location will be available in the location object. Now the location details have to be stored in the database. Create a database utility class named as ‘GPSDatabase’.

Create an inner classs named DBhelper which extends SQLiteOpenHelper class. SQLiteOpenHelper is a helper class to manage database creation activities. This takes care of opening the database if it exits else creates a new one.

The SQLiteOpenHelper has two unimplemented methods which should be implemented:

  • OnCreate()
  • onUpgrade()

onCreate() method is called when the database is created for the first time. The creation of tables and population of data happens in this method. onUpgrade method is called whenever to drop, add or alter the tables.

In the code given below execSQL() method is called to create a table. The method takes a query in the form of string as a parameter.

Open method and close method are used to open and close the connection with database. There are two user defined methods:

  • insertRow()
  • getAllRows()
public class GPSDatabase {
		private Context context;
		private DbHelper dbHelper;
		public final String DBNAME="gps1";
		public final int DBVERSION=3;
		public SQLiteDatabase db;
		public final String COLUMN2="latitude";
		public final String COLUMN3="longitude";
		public final String COLUMN1="locationId";
		public final String TABLENAME="location";
		public final String CREATERDB="create table location(locationId integer primary key autoincrement,
						latitude text not null, longitude text not null);";
		//const
		public GPSDatabase(Context context){
			this.context=context;
			dbHelper=new DbHelper(context);
		}
		public class DbHelper extends SQLiteOpenHelper{
			public DbHelper(Context context){
				super(context,DBNAME,null,DBVERSION);
			}
			@Override
			public void onCreate(SQLiteDatabase db) {
				// TODO Auto-generated method stub
				db.execSQL(CREATERDB);
			}
			@Override
			public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
				// TODO Auto-generated method stub
			}
		}
		public long insertRows(String column2, String column3){
			ContentValues value=new ContentValues();
			value.put(COLUMN2, column2);
			value.put(COLUMN3, column3);
			return db.insert(TABLENAME,null,value);
		}
		public Cursor getAllRows(){
			Cursor cursor=db.query(TABLENAME, new String[]{COLUMN1,COLUMN2,COLUMN3}, null,null, null, null, null);
			return cursor;
		}
		public void open() throws  SQLException{
			db=        dbHelper.getWritableDatabase();
			//return true;
		}
		public void close(){
			dbHelper.close();
			//return true;
		}
	}

In insertRows() create an object of ContentValues which can hold all the values to be inserted into the database. This can be achieved by calling insert()method of SQLilteDatabase class. The ContentValues object along with the table name should be passed as a parameter for the insert() method.

The method named getAllRows() queries all the rows from the corresponding table. The query() method of SQLilteDatabase class is used for retrieving data from the database. This method has eight parameters. The table to be queried is passed as the first parameter. The second parameter indicates the list of columns to be retrieved from the table. The other parameters are the different constraints that can be applied while querying the table(like groupby, orderBy having etc).These parameters can be set to null, if constraints are not required. The method returns a cursor containing the specified columns.

Step 6:

Whenever the device gets a new position from the GPS satellite, onlocationChange() method inside MylocListener class will be called. Since the position needs to be stored in database, the updateDatabase() method should be called.

In this method create an instance of GPSDaatbase class, which the database utility class. Open the database connection by calling the open() method. In order to insert the data call insetRow() method passing the values to be inserted as a parameter. In this case , the latitude and longitude coordinates will be passed as a parameter. After the successful insertion close the database by calling the close() method.

public  void updateDatabase(){
		GPSDatabase myDatabase=new GPSDatabase(context);
		myDatabase.open();
		myDatabase.insertRow(lat.substring(0,4),log.substring(0,4));
		myDatabase.close();
	}

Step 7:

In order to track all locations traversed by a particular device, the co-ordinate positions should be displayed. To achieve this, place a button on the activity and on the click of the button the detailed report is displayed. Since the list should be displayed on the click of the button, Activity class should implement OnClickListener interface. onClick() method is an unimplemented method of this interface, which should be implemented.

Inside the onClick() method create a instance of GPSDatabase class and call the open method. In order to display the detailed report call getAllRows() method which returns a cursor containing all the values from the database . The values are added to an ArrayList object from the cursor. This ArrayList object is bound to List item component in Activity through a ListAdapter.

public void onClick(View v) {
		Context context = getApplicationContext();
		GPSDatabase myDatabase=new GPSDatabase(this);
		myDatabase.open();
		Cursor cursor=myDatabase.getAllRows();
		cursor.moveToFirst();
		listContents= new ArrayList();
		for (int i = 0; i < cursor.getCount(); i++) {
			listContents.add("Lat=" +cursor.getString(1) +"  "+"Log "+ cursor.getString(2));
			cursor.moveToNext();
		}
		myDatabase.close();
		ListAdapter adapter=new ArrayAdapter(this,android.R.layout.simple_dropdown_item_1line, listContents);
		list=(ListView)findViewById(R.id.ListView01);
		list.setAdapter(adapter);
	}

Conclusion

The document explains how to track the location of the device and insert the values into SQLite database. The detailed steps used in order to achieve this requirement are briefed. This knowledge can be enhanced to develop any android apps related to database or location.

also read:

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Comments

  1. Grey_Matter says:

    If I want to traverse the same path and make sure I do not deviate what logic do I need to use in order to match the co-ordinates??

    • In this case you can sort the data by LocationID.
      but i would suggest when creating the database, you create a column for Timestamp. that will keep the coordinates in a chronological order.
      and you will be able to refer them by date.

  2. can u write xml file code please…

  3. Thank you for the information
    i hope this will work

  4. Hi Krishna;

    First of all thank for your share;
    i am working your example but i cant run it. i am missing a point. Could you send me source code as a zip file to my mail adress?

Trackbacks

  1. JavaPins says:

    Location tracker in Android using GPS positioning and SQLite…

    Thank you for submitting this cool story – Trackback from JavaPins…

Speak Your Mind

*

Close
Please support the site
By clicking any of these buttons you help our site to get better