Lab 13 Part 2
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="mdad.Lab13"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="18"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="mdad.Lab13.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>
MainActivity.java
package mdad.Lab13;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.text.method.ScrollingMovementMethod;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private TextView tvLatitude;
private TextView tvLongitude,mapGoogleUrl;
private Button btnInsert;
private TextView provText;
private EditText etPlaceName;
private TextView tvStatus;
private String provider;
String latit ,longit;
private LocationManager locationManager;
private MyLocationListener mylistener;
private Criteria criteria;
private Location location;
SQLiteDatabase db ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mapGoogleUrl = (TextView) findViewById(R.id.tvMapURL);
mapGoogleUrl.setClickable(true);
mapGoogleUrl.setMovementMethod(LinkMovementMethod.getInstance());
String defaultURL = "<a href='http://maps.google.com/maps?q=1.346269,103.931793'> Map</a>";
mapGoogleUrl.setText(Html.fromHtml( defaultURL));
tvLatitude = (TextView) findViewById(R.id.tvLat);
tvLongitude = (TextView) findViewById(R.id.tvLong);
provText = (TextView) findViewById(R.id.tvProvider);
etPlaceName = (EditText) findViewById(R.id.etPlaceName);
tvStatus = (TextView) findViewById(R.id.tvStatus);
tvStatus.setMovementMethod(new ScrollingMovementMethod()); //Scrollbar
tvStatus.setMovementMethod(LinkMovementMethod.getInstance()); //Hyperlink
//Create Database and Table
String sql="create table if not exists FavoritePlaces (recId integer PRIMARY KEY autoincrement, PlaceName text, latitude text, longitude text, mapURL text)";
String result = createDatabase(sql,"FavPlaces.db");
//Display data on TextView tvStatus from FavPlaces.db
queryTable("Select * from FavoritePlaces order by recId desc", tvStatus);
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the location provider
criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE); //default
criteria.setCostAllowed(false);
// get the best provider depending on the criteria
provider = locationManager.getBestProvider(criteria, false);
// the last known location of this provider
location = locationManager.getLastKnownLocation(provider);
mylistener = new MyLocationListener();
if (location != null) {
mylistener.onLocationChanged(location);
} else {
// leads to the settings because there is no last known location
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
// location updates: at least 1 meter and 200millsecs change
locationManager.requestLocationUpdates(provider, 200, 1, mylistener);
//========Insert Records with Lat, Long, Name of Place =========
btnInsert = (Button) findViewById(R.id.btnInsert1);
btnInsert.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
try
{
latit = String.valueOf(location.getLatitude());
longit= String.valueOf(location.getLongitude());
String placeName = etPlaceName.getText().toString();
String mapUrl = "http://maps.google.com/maps?q="+latit+","+longit;
String sql = "insert into FavoritePlaces (PlaceName,latitude,longitude,mapURL) values('"+placeName+"','"+latit+"','"+longit+"','"+mapUrl+"')";
String result = updateTable(sql);
tvStatus.setText(result);
queryTable("Select * from FavoritePlaces order by recId desc", tvStatus);
}
catch(Exception e)
{
Toast.makeText(MainActivity.this, "Unable to get GPS signal...", Toast.LENGTH_SHORT).show();
}
}
});
//========btnInsert=========
}
String createDatabase(String sql,String dbName)
{
//Create SQLite database below
try{
System.out.println(sql); //Print to console for debugging
db = SQLiteDatabase.openOrCreateDatabase("sdcard/"+dbName,null);
db.beginTransaction();
db.execSQL(sql);
db.setTransactionSuccessful();
db.endTransaction();
}
catch (Exception e) {
Toast.makeText(this,e.getMessage(),Toast.LENGTH_LONG).show();
System.out.println(e.toString());
return ("error open DB");
}
return "DB"+dbName+" Created...";
} //end of createDatabase method
//SQL statements for Insert, Delete , Update
String updateTable(String sql)
{
try{
System.out.println(sql);
db.beginTransaction();
db.execSQL(sql);
db.setTransactionSuccessful();
db.endTransaction();
}catch (Exception e) { System.out.println(e.toString());
return ("Error updating DB");
}
return ("DB updated");
}
// SQL query statement or Select statement
String queryTable(String sql, TextView displayResults)
{
boolean noData= true;
String htmlText ="<b><pre>Name Latitude Longitude map Link </pre></b><br>";
try{
System.out.println(sql);
displayResults.setText(""); //clear text from display
Cursor cursor = db.rawQuery(sql,null);
while (cursor.moveToNext()) {
noData =false; //there is data found
String placeName = cursor.getString(cursor.getColumnIndex("PlaceName"));
String latitude = cursor.getString(cursor.getColumnIndex("latitude"));
String longitude = cursor.getString(cursor.getColumnIndex("longitude"));
String mapUrl = " <a href='http://maps.google.com/maps?q="+latitude+","+longitude+"'> Maps </a> ";
htmlText +=placeName+" "+latitude+" "+longitude +" "+mapUrl+"<br>";
}
System.out.println(htmlText);
displayResults.append(Html.fromHtml( htmlText));
}
catch (Exception e) {
System.out.println(e.toString());
return ("Error Retrieving DB");
}
if (noData)
{
return("Not found");
}
else
return ("Search Results");
}
private class MyLocationListener implements LocationListener {
@Override
public void onLocationChanged(Location location) {
// Initialize the location fields
MainActivity.this.location = location;
latit = String.valueOf(location.getLatitude());
longit= String.valueOf(location.getLongitude());
tvLatitude.setText("Latitude: "+ latit);
tvLongitude.setText("Longitude: "+ longit);
String text = "<a href='http://maps.google.com/maps?q="+ latit+","+ longit+"'> Map of Current Location </a>";
mapGoogleUrl.setText(Html.fromHtml( text));
provText.setText(provider + " provider has been selected.");
Toast.makeText(MainActivity.this, "Location changed!", Toast.LENGTH_SHORT).show();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Toast.makeText(MainActivity.this, provider + "'s status changed to "+status +"!",
Toast.LENGTH_SHORT).show();
}
@Override
public void onProviderEnabled(String provider) {
Toast.makeText(MainActivity.this, "Provider " + provider + " enabled!",
Toast.LENGTH_SHORT).show();
}
@Override
public void onProviderDisabled(String provider) {
Toast.makeText(MainActivity.this, "Provider " + provider + " disabled!",
Toast.LENGTH_SHORT).show();
}
} //End of MyLocationListener Inner class
}// End of MainActivity class
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/tvProvider"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="No provider selected yet"
android:textSize="20dp" />
<TextView
android:id="@+id/tvLat"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="Latitude: -"
android:textSize="20dp" />
<TextView
android:id="@+id/tvLong"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Longitude: -"
android:textSize="20dp" />
<EditText
android:id="@+id/etPlaceName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Location Name">
<requestFocus />
</EditText>
<Button
android:id="@+id/btnInsert1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Insert" />
<TextView
android:id="@+id/tvMapURL"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Map"
android:textSize="20dp" />
<TextView
android:id="@+id/tvStatus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/etQty"
android:layout_below="@+id/btnInsert"
android:layout_marginTop="34dp"
android:maxLines = "20"
android:scrollbars = "vertical"
android:text="Status" />
</LinearLayout>