Difference between revisions of "Teams Winter 2011/team5/assignment/tutorial"
Abhishekbh (talk | contribs) |
Abhishekbh (talk | contribs) (→Create Android Project) |
||
(One intermediate revision by the same user not shown) | |||
Line 1: | Line 1: | ||
=== Create Android Project === | === Create Android Project === | ||
− | 1.1 Setup Eclipse with the ADT plugin as directed to ttp://www.vogella.de/articles/Android/article.html#installation here] | + | 1.1 Setup Eclipse with the ADT plugin as directed to ttp://www.vogella.de/articles/Android/article.html#installation here]<br/> |
− | 1.2. Create a new android project in your eclipse: ''File -> New -> Android Project'':<br/> | + | 1.2 Create a new Android virtual machine, of API Level 8 for this application<br/> |
+ | 1.3 Create a new android project in your eclipse: ''File -> New -> Android Project'':<br/> | ||
=== Database Helper === | === Database Helper === | ||
Line 1,432: | Line 1,433: | ||
=== ProximityBroadcastReceiver - Broadcast Receiver Code === | === ProximityBroadcastReceiver - Broadcast Receiver Code === | ||
− | + | <pre> | |
package dps914.team5.thingsToDo; | package dps914.team5.thingsToDo; |
Latest revision as of 14:40, 16 April 2011
Contents
Create Android Project
1.1 Setup Eclipse with the ADT plugin as directed to ttp://www.vogella.de/articles/Android/article.html#installation here]
1.2 Create a new Android virtual machine, of API Level 8 for this application
1.3 Create a new android project in your eclipse: File -> New -> Android Project:
Database Helper
package dps914.team5.thingsToDo; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; public class DAL { // Logcat Tag private static final String TAG = DAL.class.getSimpleName(); // DB info private static final String DATABASE_NAME = "mytasks.db"; private static final String DATABASE_TABLE = "mytasks_table"; private static final int DATABASE_VERSION = 1; // DB Attributes public static final String KEY_ROW_ID = "_id"; public static final String KEY_TASK_NAME = "task_name"; public static final String KEY_TASK_DESC = "task_desc"; public static final String KEY_TASK_LAT = "task_latitude"; public static final String KEY_TASK_LONG = "task_longitude"; public static final String KEY_TASK_ADDRESS = "task_address"; public static final String KEY_TASK_COMPLETE_TIME = "task_complete_time"; public static final String KEY_TASK_CREATE_TIME = "task_create_time"; public static final String KEY_TASK_COMPLETED = "task_completed"; public static final String KEY_TASK_GEOLOCATED = "task_geolocated"; // DB Stuff private Context ctx; private SQLiteDatabase db; // Create DB String private static final String CREATE_TABLE = "create table mytasks_table (" + "_id integer primary key autoincrement, " + "task_name text not null," + "task_desc text," + "task_latitude real," + "task_longitude real," + "task_address text," + "task_complete_time text," + "task_create_time text," + "task_completed boolean default 0," + "task_geolocated boolean default 0" +");"; /* * DAL * DAL Context Constructor */ public DAL(Context context) { ctx = context; OpenHelper oh = new OpenHelper(ctx); db = oh.getWritableDatabase(); } /* * close * Close DB */ public void close() { db.close(); } /* * createRow * Insert a new row */ public void createRow(String tName, String tDesc, String address, String createTime, String completeTime, boolean geolocated, float tLat, float tLong) { ContentValues initialValues = new ContentValues(); initialValues.put(KEY_TASK_NAME, tName); initialValues.put(KEY_TASK_DESC, tDesc); initialValues.put(KEY_TASK_LAT, tLat); initialValues.put(KEY_TASK_LONG, tLong); initialValues.put(KEY_TASK_ADDRESS, address); initialValues.put(KEY_TASK_COMPLETE_TIME, completeTime); initialValues.put(KEY_TASK_CREATE_TIME, createTime); initialValues.put(KEY_TASK_COMPLETED, 1); initialValues.put(KEY_TASK_GEOLOCATED, geolocated); db.insert(DATABASE_TABLE, null, initialValues); } /* * updateRow * Update a row based on rowId */ public void updateRow(long rowId, String tName, String tDesc, String address, String createTime, String completeTime, boolean completed, boolean geolocated, float tLat, float tLong) { ContentValues updatedValues = new ContentValues(); updatedValues.put(KEY_TASK_NAME, tName); updatedValues.put(KEY_TASK_DESC, tDesc); updatedValues.put(KEY_TASK_LAT, tLat); updatedValues.put(KEY_TASK_LONG, tLong); updatedValues.put(KEY_TASK_ADDRESS, address); updatedValues.put(KEY_TASK_COMPLETE_TIME, completeTime); updatedValues.put(KEY_TASK_CREATE_TIME, createTime); updatedValues.put(KEY_TASK_COMPLETED, completed); updatedValues.put(KEY_TASK_GEOLOCATED, geolocated); db.update(DATABASE_TABLE, updatedValues,"_id='" + rowId + "'", null); } /* * getAllRows * Retrieve all rows */ public Cursor getAllRows() { try { return db.query(DATABASE_TABLE, new String[] {KEY_ROW_ID, KEY_TASK_NAME, KEY_TASK_DESC , KEY_TASK_LAT, KEY_TASK_LONG, KEY_TASK_ADDRESS, KEY_TASK_COMPLETE_TIME, KEY_TASK_CREATE_TIME, KEY_TASK_COMPLETED, KEY_TASK_GEOLOCATED}, null, null, null, null, null); } catch (SQLiteException e) { Log.e(TAG, "Exception on query"); return null; } } /* * getRowByName * Retrieve specific rows by name */ public Cursor getRowByName(String taskName) { Cursor cursor = db.query("mytasks_table", new String[] {"_id", "task_name", "task_desc", "task_address", "task_geolocated"}, "task_name like '" + taskName + "'", null, null, null, null); return cursor; } /* * getRowByName * Retrieve specific rows by id */ public Cursor getRowById(int _id) { Cursor cursor = db.query("mytasks_table", new String[] {"_id", "task_name", "task_desc", "task_address", "task_geolocated"}, "_id = '" + _id + "'", null, null, null, null); return cursor; } /* * updateRow * Update row by id */ public void updateRow(String tName, String tDesc, String address, float tLat, float tLong, int _id) { ContentValues updatedValues = new ContentValues(); updatedValues.put(KEY_TASK_NAME, tName); updatedValues.put(KEY_TASK_DESC, tDesc); updatedValues.put(KEY_TASK_ADDRESS, address); updatedValues.put(KEY_TASK_LAT, tLat); updatedValues.put(KEY_TASK_LONG, tLong); db.update(DATABASE_TABLE, updatedValues,"_id='" + _id + "'", null); } /* * deleteRow * Delete a row */ public void deleteRow(long rowId) { db.delete(DATABASE_TABLE, "_id=" + rowId, null); } /* * OpenHelper * Opens the DB, and updates it if needed */ private static class OpenHelper extends SQLiteOpenHelper { public OpenHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { Log.d(TAG, "onCreate sql " + CREATE_TABLE); db.execSQL(CREATE_TABLE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE); onCreate(db); } } }
ThingsToDo Activity Code
package dps914.team5.thingsToDo; import android.app.ListActivity; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.AdapterView; import android.widget.CheckBox; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import android.widget.TableRow; import android.widget.TextView; public class ThingsToDo extends ListActivity { // UI Connections private TableRow titleBarMain; private TextView titlebarText; // Tag for Log private static final String TAG = null; // DB Helper and Cursor private DAL dbHelper; private Cursor cur; // Selected task id private int listViewTasksId; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // Create the DAL dbHelper = new DAL(ThingsToDo.this); // Get UI Elements titleBarMain = (TableRow)findViewById(R.id.titleBarMain); // Retrieve Tasks retrieveTasks(); } private void retrieveTasks() { cur = dbHelper.getAllRows(); startManagingCursor(cur); SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter( this, R.layout.task_row, cur, new String[] {DAL.KEY_TASK_NAME, DAL.KEY_TASK_COMPLETE_TIME, DAL.KEY_TASK_COMPLETED, DAL.KEY_ROW_ID}, new int[] {R.id.task_name, R.id.task_date} ); ListAdapter adapter = cursorAdapter; setListAdapter(adapter); final ListView tasksList = getListView(); // Upon Task Select - Click Listener tasksList.setOnItemClickListener(new ListView.OnItemClickListener() { public void onItemClick(AdapterView<?> a, View v, int position, long id) { try { // Remembers the selected Index setListViewTasksId(tasksList.getSelectedItemPosition()); Log.d(TAG, "############################## Selected POSITION " + position); Log.d(TAG, "############################## Selected ID " + id); Log.d(TAG, "############################## Selected ADAPTERVIEW " + a); Log.d(TAG, "############################## Selected ADAPTERVIEWPOSITION " + tasksList.getItemAtPosition(position)); String taskNameRetrieved = (String)((Cursor)tasksList.getItemAtPosition(position)).getString(1); Intent shiftIntent = new Intent(ThingsToDo.this, TTDEditTask.class); shiftIntent.putExtra("taskName", taskNameRetrieved); shiftIntent.putExtra("taskId", id); startActivity(shiftIntent); Log.d(TAG, "############################## Activity Started"); } catch(Exception e) { Log.d(TAG, "############################## Exception in onItemClick " + e); } } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main_menu, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // Edit Contact case R.id.contact_create: Log.d(TAG, "############################## Create button clicked"); Intent i = new Intent(this, TTDNewTask.class); startActivity(i); break; // Exit App case R.id.contact_exit: Log.d(TAG, "############################## Exit button clicked"); finish(); break; } return super.onOptionsItemSelected(item); } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { return super.onMenuItemSelected(featureId, item); } public void setListViewTasksId(int listViewTasksId) { this.listViewTasksId = listViewTasksId; } public int getListViewTasksId() { return listViewTasksId; } public void setTitleBarMain(TableRow titleBarMain) { this.titleBarMain = titleBarMain; } public TableRow getTitleBarMain() { return titleBarMain; } public void setTitlebarText(TextView titlebarText) { this.titlebarText = titlebarText; } public TextView getTitlebarText() { return titlebarText; } }
ThingsToDo Activity Layout
<?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" > <TableRow android:layout_height="wrap_content" android:layout_width="match_parent" android:id="@+id/titleBarMain" android:background="#848285" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/titlebar_text" android:gravity="center_horizontal" android:textColor="#ffffff" android:textStyle="bold" android:padding="3sp" android:textSize="15sp" /> </TableRow> <ListView android:layout_height="wrap_content" android:layout_width="match_parent" android:headerDividersEnabled="true" android:footerDividersEnabled="true" android:id="@+id/android:list"/> </LinearLayout>
And a row layout for the list layout:
<?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:layout_gravity="fill_horizontal" android:orientation="vertical" > <TableRow android:id="@+id/TableRow07" android:layout_height="wrap_content" android:layout_width="match_parent" > <CheckBox android:text="" android:id="@+id/cb_task_done" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <LinearLayout android:id="@+id/linearLayout23" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" > <TextView android:id="@+id/task_name" android:text="@string/view_task_name" android:layout_gravity="left" android:height="30sp" android:layout_height="wrap_content" android:layout_width="wrap_content" android:textSize="20sp" android:padding="1sp" /> <TextView android:id="@+id/task_date" android:text="@string/view_task_date" android:layout_gravity="left" android:layout_height="wrap_content" android:layout_width="wrap_content" android:textSize="10sp" android:padding="1sp" /> </LinearLayout> </TableRow> </LinearLayout>
ThingsToDo Activity Menu
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:title="@string/main_menu_create" android:id="@+id/contact_create" android:icon="@android:drawable/ic_menu_edit" /> <item android:title="@string/main_menu_exit" android:id="@+id/contact_exit" android:icon="@android:drawable/ic_menu_close_clear_cancel" /> </menu>
TTDNewTask Activity Code
package dps914.team5.thingsToDo; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; import java.util.SimpleTimeZone; import java.util.TimeZone; import android.app.Activity; import android.app.AlarmManager; import android.app.DatePickerDialog; import android.app.Dialog; import android.app.PendingIntent; import android.app.TimePickerDialog; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.TextView; import android.widget.TimePicker; import android.widget.CheckBox; import android.widget.Toast; public class TTDNewTask extends Activity { // Tag for Log private static final String TAG = null; private Geocoder localGeoCoder; //private MapView myMap; // Location based variables private LocationManager locationManager; private static final long ALERT_RADIUS = 1000; private static final long ALERT_EXPIRATION = -1; // User Input Values private String task_name = null; private String task_desc = null; private String task_address = null; private String sdf_time = null; private boolean task_geolocated = false; private PendingIntent pendingIntent; // UI for date and time static final int DATE_DIALOG_ID = 0; static final int TIME_DIALOG_ID = 1; private int dueHour= 0; private int dueMin= 0; private int dueDate= 22; private int dueMon= 9; private int dueYear= 2011; StringBuilder dueTime = null; /** * @return the dueHour */ protected int getDueHour() { return dueHour; } /** * @param dueHour the dueHour to set */ protected void setDueHour(int dueHour) { this.dueHour = dueHour; } /** * @return the dueMin */ protected int getDueMin() { return dueMin; } /** * @param dueMin the dueMin to set */ protected void setDueMin(int dueMin) { this.dueMin = dueMin; } /** * @return the dueDate */ protected int getDueDate() { return dueDate; } /** * @param dueDate the dueDate to set */ protected void setDueDate(int dueDate) { this.dueDate = dueDate; } /** * @return the dueMon */ protected int getDueMon() { return dueMon; } /** * @param dueMon the dueMon to set */ protected void setDueMon(int dueMon) { this.dueMon = dueMon; } /** * @return the dueYear */ protected int getDueYear() { return dueYear; } /** * @param dueYear the dueYear to set */ protected void setDueYear(int dueYear) { this.dueYear = dueYear; } // Date format to am/pm protected String hourToTwelve(int incomingHour, int incomingMinute) { String am_pm = " AM"; String retVal = null; if (incomingHour > 11) { am_pm = " PM"; } else if (incomingHour == 0) { } if (incomingMinute < 10) { if (incomingHour == 0) { retVal = "0" + incomingHour + ":0" + incomingMinute + am_pm; } else { retVal = incomingHour + ":0" + incomingMinute + am_pm; } } else { if (incomingHour == 0) { retVal = "0" + incomingHour + ":" + incomingMinute + am_pm; } else { retVal = incomingHour + ":" + incomingMinute + am_pm; } } return retVal; } // Date format to month protected String setMonthOutput (int incomingMonthIndex) { String[] months = {"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"}; return months[incomingMonthIndex]; } // Callback for datepicker final DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() { public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { Log.d(TAG, "############################## Year: " + year); Log.d(TAG, "############################## Mon: " + monthOfYear); Log.d(TAG, "############################## Date: " + dayOfMonth); setDueYear(year); setDueMon(monthOfYear); setDueDate(dayOfMonth); dueTime = new StringBuilder().append("Due On: ").append(setMonthOutput(dueMon)).append(" ").append(dueDate).append(", ").append(dueYear).append(" at "); Log.d(TAG, "############################## StringBuilder: : " + dueTime.toString()); showDialog(TIME_DIALOG_ID); } }; // Callback for timepicker final TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() { public void onTimeSet(TimePicker view, int hourOfDay, int minute) { Log.d(TAG, "############################## Hour: " + hourOfDay); Log.d(TAG, "############################## Min: " + minute); setDueHour(hourOfDay); setDueMin(minute); dueTime.append(" ").append(hourToTwelve(hourOfDay, minute)); Log.d(TAG, "############################## StringBuilder: : " + dueTime.toString()); } }; // Dialog handler @Override protected Dialog onCreateDialog (int id) { String[] ids = TimeZone.getAvailableIDs(-5 * 60 * 60 * 1000); if (ids.length == 0) System.exit(0); SimpleTimeZone edt = new SimpleTimeZone(-7 * 60 * 60 * 1000, ids[0]); Calendar calendar = new GregorianCalendar(edt); Date nowTime = new Date(); calendar.setTime(nowTime); switch (id) { case DATE_DIALOG_ID: return new DatePickerDialog(this, mDateSetListener, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE) + 1); case TIME_DIALOG_ID: return new TimePickerDialog(this, mTimeSetListener, calendar.get(Calendar.HOUR), calendar.get(Calendar.MINUTE), false); } return null; } /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.ttd_new_task); Log.d(TAG, "############################## New Task"); // Buttons and Checkboxes Button datetime_button = (Button) findViewById(R.id.btn_dueon); Button save_button = (Button) findViewById(R.id.btn_save); CheckBox geolocate_button = (CheckBox) findViewById(R.id.checkbox_geolocate); // UI Elements to erase final EditText addressEdit = (EditText) findViewById(R.id.task_address_edit); addressEdit.setVisibility(View.GONE); final TextView addressEditLabel = (TextView) findViewById(R.id.TextView03); addressEditLabel.setVisibility(View.GONE); // Location manager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 1000, 1, new LocalLocationListener() ); //////////////////////////////////////////////////////////////////////////////////////// // Show Dialog datetime_button.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { Log.d(TAG, "############################## Due On Clicked"); try { showDialog(DATE_DIALOG_ID); } catch (Exception e) { Log.d(TAG, "############################## Exception: " + e.getMessage()); } } }); // Show address edit text geolocate_button.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { Log.d(TAG, "############################## Add Address Clicked"); if (addressEdit.getVisibility() == 0) { addressEdit.setVisibility(View.GONE); addressEditLabel.setVisibility(View.GONE); } else { addressEdit.setVisibility(View.VISIBLE); addressEditLabel.setVisibility(View.VISIBLE); } task_geolocated = false; } }); //////////////////////////////////////////////////////////////////////////////////////// // Save Button save_button.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { // DAL DAL localDal = new DAL(TTDNewTask.this); // User's Values task_name = ((EditText)findViewById(R.id.task_name_edit)).getText().toString(); task_desc = ((EditText)findViewById(R.id.task_desc_edit)).getText().toString(); task_address = ((EditText)findViewById(R.id.task_address_edit)).getText().toString(); // Current Time Date now = new Date(); SimpleDateFormat textTime = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); sdf_time = textTime.format(now); // Address logcat Log.d(TAG, "############################## Address: "+ task_address); Log.d(TAG, "############################## Going into geolocateAddress()"); // Geolocate address Float[] returnedLocation = this.geolocateAddress(task_address); // Latitude and Longitude logcat Log.d(TAG, "############################## Latitude: "+ returnedLocation[0]); Log.d(TAG, "############################## Longitude: "+ returnedLocation[1]); Log.d(TAG, "############################################################"); Log.d(TAG, "############################################################"); Log.d(TAG, "############################################################"); Log.d(TAG, "############################################################"); Log.d(TAG, "############################## Name: "+ task_name); Log.d(TAG, "############################## Desc: "+ task_desc); Log.d(TAG, "############################## Addr: "+ task_address); Log.d(TAG, "############################## SDF: "+ sdf_time); //Log.d(TAG, "############################## DUE: "+ dueTime.toString()); Log.d(TAG, "############################## Geolocated: "+ task_geolocated); Log.d(TAG, "############################## Lat: "+ returnedLocation[0]); Log.d(TAG, "############################## Long: "+ returnedLocation[1]); Log.d(TAG, "############################################################"); Log.d(TAG, "############################################################"); Log.d(TAG, "############################################################"); Log.d(TAG, "############################################################"); addProximityAlert(43.7700,-79.3437); //addProximityAlert(returnedLocation[0],returnedLocation[1]); // Save and End localDal.createRow(task_name, task_desc, task_address, sdf_time, dueTime.toString(), task_geolocated, returnedLocation[0], returnedLocation[1]); Log.d(TAG, "############################## row saved"); Log.d(TAG, "############################## save button clicked"); // Set Alarm Intent alarmServiceIntent = new Intent(TTDNewTask.this, TaskAlarmService.class); alarmServiceIntent.putExtra("taskName", task_name); pendingIntent = PendingIntent.getService(TTDNewTask.this, 0, alarmServiceIntent, 0); AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE); Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.YEAR, dueYear); calendar.set(Calendar.MONTH, dueMon); calendar.set(Calendar.DATE, dueDate); calendar.set(Calendar.HOUR, dueHour); calendar.set(Calendar.MINUTE, dueMin); Log.d(TAG, "Year: " + dueYear); Log.d(TAG, "Month: " + dueMon); Log.d(TAG, "Date: " + dueDate); Log.d(TAG, "Hour: " + dueHour); Log.d(TAG, "Minute: " + dueMin); alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent); Toast.makeText(TTDNewTask.this, "Alarm Set", Toast.LENGTH_LONG).show(); // End activity finish(); } private void addProximityAlert(double latitude, double longitude) { Intent tempIntent = new Intent(TTDNewTask.this, ProximityBroadcastReceiver.class); pendingIntent = PendingIntent.getService(TTDNewTask.this, 0, tempIntent, 0); PendingIntent proximityIntent = PendingIntent.getBroadcast(TTDNewTask.this, 0, tempIntent, 0); try { locationManager.addProximityAlert(latitude,longitude,ALERT_RADIUS,ALERT_EXPIRATION,proximityIntent); } catch (Exception e) { Log.d(TAG, "Could not set proximity alert: " + e); } //IntentFilter filter = new IntentFilter(ANON_ALERT_INTENT); //registerReceiver(new ProximityBroadcastReceiver(), filter); } protected Float[] geolocateAddress(String addressIncoming) { localGeoCoder = new Geocoder(TTDNewTask.this); Float[] retArr = {(float) 0.0, (float) 0.0}; try { Log.d(TAG, "############################## Address: " + addressIncoming); // Geolocate Address List<Address> foundAdresses = localGeoCoder.getFromLocationName(addressIncoming, 1); // If Address not found /* if (foundAdresses.size() == 0) { Log.d(TAG, "############################## Lat and Long NOT FOUND"); Dialog locationError = new AlertDialog.Builder(TTDNewTask.this) .setIcon(0) .setTitle("Error") .setPositiveButton(R.string.task_ok, null) .setMessage("Sorry, your address doesn't exist.") .create(); locationError.show(); } else {*/ Log.d(TAG, "############################## Found Lat and Long"); // Get Latitude and Longitude for (int i = 0; i < foundAdresses.size(); ++i) { // Set returned latitude and longitude Address returnedAddress = foundAdresses.get(i); retArr[0] = (float) returnedAddress.getLatitude(); retArr[1] = (float) returnedAddress.getLongitude(); } // Show on Map //navigateToLocation((geolocatedLat * 1000000), (geolocatedLonlon * 1000000), myMap); //} } catch (Exception e) { Log.d(TAG, "############################## Exception: " + e); } Log.d(TAG, "############################## LAT: " + retArr[0]); Log.d(TAG, "############################## LON: " + retArr[1]); return retArr; } }); } public class LocalLocationListener implements LocationListener { public void onLocationChanged(Location location) {} public void onStatusChanged(String s, int i, Bundle b) {} public void onProviderDisabled(String s) {} public void onProviderEnabled(String s) {} } }
TTDNewTask Activity Layout
<?xml version="1.0" encoding="utf-8"?> <TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <TableRow android:layout_height="wrap_content" android:layout_width="match_parent" android:id="@+id/titleBarNew" android:background="#848285" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/titlebar_new_text" android:gravity="center_horizontal" android:textColor="#ffffff" android:textStyle="bold" android:padding="3sp" android:textSize="15sp" /> </TableRow> <TableRow android:id="@+id/TableRow01"> <TextView android:id="@+id/TextView01" android:text="@string/task_name" android:width="115px" /> </TableRow> <TableRow android:id="@+id/TableRow11"> <EditText android:id="@+id/task_name_edit" android:hint="eg. Get groceries " android:layout_height="match_parent" android:layout_width="match_parent"/> </TableRow> <TableRow android:id="@+id/TableRow02"> <TextView android:id="@+id/TextView02" android:text="@string/task_desc" android:width="115px" /> </TableRow> <TableRow android:id="@+id/TableRow12"> <EditText android:id="@+id/task_desc_edit" android:hint="eg. milk, tomatoes, eggs " android:layout_height="match_parent" android:layout_width="match_parent"/> </TableRow> <TableRow android:id="@+id/TableRow03"> <CheckBox android:text="@string/task_geolocated" android:id="@+id/checkbox_geolocate" android:layout_width="match_parent" android:layout_height="match_parent" /> </TableRow> <TableRow android:id="@+id/TableRow04"> <TextView android:id="@+id/TextView03" android:text="@string/task_address" android:width="115px" /> </TableRow> <TableRow android:id="@+id/TableRow14"> <EditText android:id="@+id/task_address_edit" android:hint="24 Sussex Drive, Ottawa, Canada" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </TableRow> <TableRow android:id="@+id/TableRow05"> <Button android:text="@string/task_date" android:id="@+id/btn_dueon" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </TableRow> <TableRow android:id="@+id/TableRow06"> <Button android:text="@string/task_save" android:id="@+id/btn_save" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </TableRow> </TableLayout>
TTDEditTask Activity Code
package dps914.team5.thingsToDo; import java.util.List; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.database.Cursor; import android.location.Address; import android.location.Geocoder; 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.TextView; public class TTDEditTask extends Activity { // Tag for Log private static final String TAG = "TaskMan"; private Geocoder localGeoCoder; private int task_geolocated = 0; private int taskIdRetrieved = 0; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.ttd_edit_task); Log.d(TAG, "############################## Edit Task"); // DbHelper DAL dalInstance = new DAL(TTDEditTask.this); String taskNameRetrieved = null; String taskDescRetrieved = null; String taskAddressRetrieved = null; // UI Objects EditText taskNameDisplay = (EditText) findViewById(R.id.task_name_edit); EditText taskDescDisplay = (EditText) findViewById(R.id.task_desc_edit); EditText taskAddressDisplay = (EditText) findViewById(R.id.task_address_edit); CheckBox geolocate_button = (CheckBox) findViewById(R.id.checkbox_geolocate); Button saveEditTask = (Button) findViewById(R.id.btn_save); // UI Elements to erase final EditText addressEdit = (EditText) findViewById(R.id.task_address_edit); addressEdit.setVisibility(View.GONE); final TextView addressEditLabel = (TextView) findViewById(R.id.TextView03); addressEditLabel.setVisibility(View.GONE); // Get name from extras bundle // taskIdRetrieved = Integer.parseInt(this.getIntent().getExtras().getString("taskId").trim()); String taskNameExtras = this.getIntent().getExtras().getString("taskName").trim(); // Query DB using incoming taskName Cursor retVal = dalInstance.getRowByName(taskNameExtras); Log.d(TAG, ">>>>>>>>1: " + retVal.getColumnName(0)); Log.d(TAG, ">>>>>>>>2: " + retVal.getColumnName(1)); Log.d(TAG, ">>>>>>>>3: " + retVal.getColumnName(2)); //Log.d(TAG, ">>>>>>>>4: " + retVal.getColumnName(3)); //Log.d(TAG, ">>>>>>>>5: " + taskIdRetrieved); // Set cursor to first row if (retVal.moveToFirst()) { Log.d(TAG, ">>>>>>>>>>>> Found record"); // Read the retrieved values taskNameRetrieved = retVal.getString(retVal.getColumnIndex("task_name")); taskDescRetrieved = retVal.getString(retVal.getColumnIndex("task_desc")); taskAddressRetrieved = retVal.getString(retVal.getColumnIndex("task_address")); taskIdRetrieved = retVal.getInt(retVal.getColumnIndex("_id")); taskIdRetrieved = 1; task_geolocated = retVal.getInt(retVal.getColumnIndex("task_geolocated")); Log.d(TAG, ">>>>>>>>>>>> Task Geolocated? " + task_geolocated); Log.d(TAG, ">>>>>>>>>>>> Task Address: " + taskAddressRetrieved); } // If address exists, then show the address edittext if (taskAddressRetrieved != null || taskAddressRetrieved != "") { Log.d(TAG, ">>>>>>>>>>>> Task is geolocated"); addressEdit.setVisibility(View.VISIBLE); addressEditLabel.setVisibility(View.VISIBLE); geolocate_button.setVisibility(View.GONE); } // Read Cursor into UI taskNameDisplay.setText(taskNameRetrieved); taskDescDisplay.setText(taskDescRetrieved); taskAddressDisplay.setText(taskAddressRetrieved); Log.d(TAG, "UI Changed"); // Show address edit text geolocate_button.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { Log.d(TAG, "############################## Add Address Clicked"); if (addressEdit.getVisibility() == 0) { addressEdit.setVisibility(View.GONE); addressEditLabel.setVisibility(View.GONE); } else { addressEdit.setVisibility(View.VISIBLE); addressEditLabel.setVisibility(View.VISIBLE); } setTask_geolocated(1); } }); // Save Button saveEditTask.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { Log.d(TAG, "Button Clicked"); DAL localDAL = new DAL(TTDEditTask.this); // UI Objects EditText taskNameDisplay = (EditText) findViewById(R.id.task_name_edit); EditText taskDescDisplay = (EditText) findViewById(R.id.task_desc_edit); EditText taskAddressDisplay = (EditText) findViewById(R.id.task_address_edit); Float[] returnedLocation = geolocateAddress(taskAddressDisplay.getText().toString()); try { // Update Row localDAL.updateRow( taskNameDisplay.getText().toString(), taskDescDisplay.getText().toString(), taskAddressDisplay.getText().toString(), returnedLocation[0], returnedLocation[1], taskIdRetrieved ); Log.d(TAG, "UPDATED ROW"); } catch (Exception e) { Log.d(TAG, "COULD NOT UPDATE ROW"); Log.d(TAG, "" + e); } finish(); } }); } protected Float[] geolocateAddress(String addressIncoming) { localGeoCoder = new Geocoder(TTDEditTask.this); Float[] retArr = {(float) 0.0, (float) 0.0}; try { Log.d(TAG, "############################## Address: " + addressIncoming); // Geolocate Address List<Address> foundAdresses = localGeoCoder.getFromLocationName(addressIncoming, 1); // If Address not found if (foundAdresses.size() == 0) { Log.d(TAG, "############################## Lat and Long NOT FOUND"); Dialog locationError = new AlertDialog.Builder(TTDEditTask.this) .setIcon(0) .setTitle("Error") .setPositiveButton(R.string.task_ok, null) .setMessage("Sorry, your address doesn't exist.") .create(); locationError.show(); } else { Log.d(TAG, "############################## Found Lat and Long"); // Get Latitude and Longitude for (int i = 0; i < foundAdresses.size(); ++i) { // Set returned latitude and longitude Address returnedAddress = foundAdresses.get(i); retArr[0] = (float) returnedAddress.getLatitude(); retArr[1] = (float) returnedAddress.getLongitude(); } // Show on Map //navigateToLocation((geolocatedLat * 1000000), (geolocatedLonlon * 1000000), myMap); } } catch (Exception e) { Log.d(TAG, "############################## Exception: " + e); } Log.d(TAG, "############################## LAT: " + retArr[0]); Log.d(TAG, "############################## LON: " + retArr[1]); return retArr; } public void setTask_geolocated(int task_geolocated) { this.task_geolocated = task_geolocated; } public int isTask_geolocated() { return task_geolocated; } }
TTDEditTask Activity Layout
<?xml version="1.0" encoding="utf-8"?> <TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <TableRow android:id="@+id/TableRow01"> <TextView android:id="@+id/TextView01" android:text="@string/task_name" android:width="115px" /> </TableRow> <TableRow android:id="@+id/TableRow11"> <EditText android:id="@+id/task_name_edit" android:hint="eg. Get groceries" android:layout_height="match_parent" android:layout_width="match_parent"/> </TableRow> <TableRow android:id="@+id/TableRow02"> <TextView android:id="@+id/TextView02" android:text="@string/task_desc" android:width="115px" /> </TableRow> <TableRow android:id="@+id/TableRow12"> <EditText android:id="@+id/task_desc_edit" android:hint="eg. milk, tomatoes, eggs" android:layout_height="match_parent" android:layout_width="match_parent"/> </TableRow> <TableRow android:id="@+id/TableRow03"> <CheckBox android:text="@string/task_geolocated" android:id="@+id/checkbox_geolocate" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <CheckBox android:text="@string/task_geolocated_remove" android:id="@+id/checkbox_geolocate_remove" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </TableRow> <TableRow android:id="@+id/TableRow04"> <TextView android:id="@+id/TextView03" android:text="@string/task_address" android:width="115px" /> </TableRow> <TableRow android:id="@+id/TableRow14"> <EditText android:id="@+id/task_address_edit" android:hint="24 Sussex Drive, Ottawa, Canada" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </TableRow> <TableRow android:id="@+id/TableRow05"> <Button android:text="@string/task_date" android:id="@+id/btn_dueon" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </TableRow> <TableRow android:id="@+id/TableRow06"> <Button android:text="@string/task_save" android:id="@+id/btn_save" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </TableRow> </TableLayout>
TaskAlarmService - Service Code
package dps914.team5.thingsToDo; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.os.IBinder; import android.widget.Toast; public class TaskAlarmService extends Service { private static final int NOTIFICATION_ID = 1001; private String taskName = null; /** * @return the taskName */ protected String getTaskName() { return taskName; } /** * @param taskName the taskName to set */ protected void setTaskName(String taskName) { this.taskName = taskName; } @Override public void onCreate() { // TODO Auto-generated method stub } /* (non-Javadoc) * @see android.app.Service#onStartCommand(android.content.Intent, int, int) */ @Override public int onStartCommand(Intent intent, int flags, int startId) { // Get name from extras bundle setTaskName(intent.getExtras().getString("taskName").trim()); Toast.makeText(this, "THIS: " + intent.getExtras().getString("taskName").trim(), Toast.LENGTH_LONG).show(); getFromNotificationManager(); return super.onStartCommand(intent, flags, startId); } public void getFromNotificationManager() { // Notification Manager String ns = Context.NOTIFICATION_SERVICE; NotificationManager notificationManager = (NotificationManager) getSystemService(ns); notificationManager.notify(NOTIFICATION_ID, createNotification()); } public Notification createNotification() { //int icon = android.R.drawable.ic_popup_reminder; int icon = android.R.drawable.ic_menu_agenda; CharSequence tickerText = "TTD: Reminder!"; long when = System.currentTimeMillis(); Notification notification = new Notification(icon, tickerText, when); Context context = getApplicationContext(); CharSequence contentTitle = "TTD: Reminder!"; CharSequence contentText = "Remember: " + taskName; Intent notificationIntent = new Intent(this, TaskAlarmService.class); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); // Notification Defaults notification.defaults |= Notification.DEFAULT_SOUND; //notification.defaults |= Notification.DEFAULT_VIBRATE; //notification.defaults |= Notification.DEFAULT_LIGHTS; notification.flags |= Notification.FLAG_AUTO_CANCEL; notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent); return notification; } @Override public IBinder onBind(Intent intent) { return null; } @Override public void onDestroy() { super.onDestroy(); } @Override public void onStart(Intent intent, int startId) { super.onStart(intent, startId); } @Override public boolean onUnbind(Intent intent) { return super.onUnbind(intent); } }
ProximityBroadcastReceiver - Broadcast Receiver Code
package dps914.team5.thingsToDo; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.location.LocationManager; import android.util.Log; public class ProximityBroadcastReceiver extends BroadcastReceiver { private static final int NOTIFICATION_ID = 1001; // Tag for Log private static final String TAG = null; @Override public void onReceive(Context context, Intent intent) { String key = LocationManager.KEY_PROXIMITY_ENTERING; Boolean locale = intent.getBooleanExtra(key, false); if (locale) { Log.d(TAG, "Entering alarm area"); } else { Log.d(TAG, "Exiting alarm area"); } // Notification Manager NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, null, 0); // Notification Notification notification = createNotification(); notification.setLatestEventInfo(context, "Proximity Alert!", "TTD Reminder", pendingIntent); // Deploy Notification notificationManager.notify(NOTIFICATION_ID, notification); } // Create Notification private Notification createNotification() { Notification notification = new Notification(); // Flags and Defaults notification.icon = android.R.drawable.ic_menu_agenda; notification.when = System.currentTimeMillis(); notification.flags |= Notification.FLAG_AUTO_CANCEL; notification.flags |= Notification.FLAG_SHOW_LIGHTS; notification.defaults |= Notification.DEFAULT_VIBRATE; notification.defaults |= Notification.DEFAULT_LIGHTS; return notification; } }