List of usage examples for android.database Cursor getDouble
double getDouble(int columnIndex);
From source file:com.ichi2.libanki.Stats.java
/** * Hourly Breakdown/*from w w w . ja v a 2s . c o m*/ */ public boolean calculateBreakdown(int type) { mTitle = R.string.stats_breakdown; mAxisTitles = new int[] { R.string.stats_time_of_day, R.string.stats_percentage_correct, R.string.stats_reviews }; mValueLabels = new int[] { R.string.stats_percentage_correct, R.string.stats_answers }; mColors = new int[] { R.color.stats_counts, R.color.stats_hours }; mType = type; String lim = _revlogLimit().replaceAll("[\\[\\]]", ""); if (lim.length() > 0) { lim = " and " + lim; } Calendar sd = GregorianCalendar.getInstance(); sd.setTimeInMillis(mCol.getCrt() * 1000); int pd = _periodDays(); if (pd > 0) { lim += " and id > " + ((mCol.getSched().getDayCutoff() - (86400 * pd)) * 1000); } long cutoff = mCol.getSched().getDayCutoff(); long cut = cutoff - sd.get(Calendar.HOUR_OF_DAY) * 3600; ArrayList<double[]> list = new ArrayList<double[]>(); Cursor cur = null; String query = "select " + "23 - ((cast((" + cut + " - id/1000) / 3600.0 as int)) % 24) as hour, " + "sum(case when ease = 1 then 0 else 1 end) / " + "cast(count() as float) * 100, " + "count() " + "from revlog where type in (0,1,2) " + lim + " " + "group by hour having count() > 30 order by hour"; Timber.d(sd.get(Calendar.HOUR_OF_DAY) + " : " + cutoff + " breakdown query: %s", query); try { cur = mCol.getDb().getDatabase().rawQuery(query, null); while (cur.moveToNext()) { list.add(new double[] { cur.getDouble(0), cur.getDouble(1), cur.getDouble(2) }); } } finally { if (cur != null && !cur.isClosed()) { cur.close(); } } //TODO adjust for breakdown, for now only copied from intervals //small adjustment for a proper chartbuilding with achartengine if (list.size() == 0) { list.add(0, new double[] { 0, 0, 0 }); } for (int i = 0; i < list.size(); i++) { double[] data = list.get(i); int intHour = (int) data[0]; int hour = (intHour - 4) % 24; if (hour < 0) hour += 24; data[0] = hour; list.set(i, data); } Collections.sort(list, new Comparator<double[]>() { @Override public int compare(double[] s1, double[] s2) { if (s1[0] < s2[0]) return -1; if (s1[0] > s2[0]) return 1; return 0; } }); mSeriesList = new double[4][list.size()]; mPeak = 0.0; mMcount = 0.0; double minHour = Double.MAX_VALUE; double maxHour = 0; for (int i = 0; i < list.size(); i++) { double[] data = list.get(i); int hour = (int) data[0]; //double hour = data[0]; if (hour < minHour) minHour = hour; if (hour > maxHour) maxHour = hour; double pct = data[1]; if (pct > mPeak) mPeak = pct; mSeriesList[0][i] = hour; mSeriesList[1][i] = pct; mSeriesList[2][i] = data[2]; if (i == 0) { mSeriesList[3][i] = pct; } else { double prev = mSeriesList[3][i - 1]; double diff = pct - prev; diff /= 3.0; diff = Math.round(diff * 10.0) / 10.0; mSeriesList[3][i] = prev + diff; } if (data[2] > mMcount) mMcount = data[2]; if (mSeriesList[1][i] > mMaxCards) mMaxCards = (int) mSeriesList[1][i]; } mFirstElement = mSeriesList[0][0]; mLastElement = mSeriesList[0][mSeriesList[0].length - 1]; mMaxElements = (int) (maxHour - minHour); //some adjustments to not crash the chartbuilding with emtpy data if (mMaxElements == 0) { mMaxElements = 10; } if (mMcount == 0) { mMcount = 10; } if (mFirstElement == mLastElement) { mFirstElement = 0; mLastElement = 23; } if (mMaxCards == 0) mMaxCards = 10; return list.size() > 0; }
From source file:net.niyonkuru.koodroid.ui.UsageFragment.java
@Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { int id = loader.getId(); switch (id) { case AIRTIME_TOKEN: { String used = null;/*ww w . j a va 2s .c om*/ String included = null; String chargeable = null; String remaining = null; Object timestamp = null; if (data.moveToFirst()) { used = data.getString(AirtimesQuery.USED); included = data.getString(AirtimesQuery.INCLUDED); chargeable = data.getString(AirtimesQuery.CHARGEABLE); remaining = data.getString(AirtimesQuery.REMAINING); timestamp = Timestamp.valueOf(data.getString(AirtimesQuery.UPDATED)); } mAirtimeUsed.setText(used); mAirtimeIncluded.setText(included); mAirtimeChargeable.setText(chargeable); mAirtimeRemaining.setText(remaining); mAirtimeUpdateTime.setTag(timestamp); break; } case TEXT_TOKEN: { data.moveToFirst(); mTextUsed.setText(data.getString(UsagesQuery.COUNT)); mTextCharged.setText(formatMoney(data.getString(UsagesQuery.AMOUNT))); saveUsageTimestamps(data); break; } case DATA_TOKEN: { data.moveToFirst(); mDataUsed.setText(UsageUtils.format(mContext, data.getDouble(UsagesQuery.COUNT), getNumberFormat())); mDataCharged.setText(formatMoney(data.getString(UsagesQuery.AMOUNT))); saveUsageTimestamps(data); break; } } updateTimestamps(); }
From source file:com.SecUpwN.AIMSICD.fragments.MapFragment.java
/** * Description: Loads Signal Strength Database details to plot on the map, * only entries which have a location (lon, lat) are used. *//*from w w w. ja v a 2s . c om*/ private void loadEntries() { new AsyncTask<Void, Void, GeoPoint>() { @Override protected GeoPoint doInBackground(Void... voids) { //int signal; mCellTowerGridMarkerClusterer.getItems().clear(); //New function only gets bts from DBe_import by sim network loadOcidMarkersByNetwork(); List<CellTowerMarker> items = new LinkedList<>(); Cursor c = null; try { // Grab cell data from CELL_TABLE (cellinfo) --> DBi_bts c = mDbHelper.getCellData(); } catch (IllegalStateException ix) { log.error("Problem getting data from CELL_TABLE", ix); } /* This function is getting cells we logged from DBi_bts */ if (c != null && c.moveToFirst()) { do { if (isCancelled()) { return null; } // The indexing here is that of DB table final int cellID = c.getInt(c.getColumnIndex(DBTableColumnIds.DBI_BTS_CID)); // CID final int lac = c.getInt(c.getColumnIndex(DBTableColumnIds.DBI_BTS_LAC)); // LAC final int mcc = c.getInt(c.getColumnIndex(DBTableColumnIds.DBI_BTS_MCC)); // MCC final int mnc = c.getInt(c.getColumnIndex(DBTableColumnIds.DBI_BTS_MNC)); // MNC final double dLat = c.getDouble(c.getColumnIndex(DBTableColumnIds.DBI_BTS_LAT)); // Lat final double dLng = c.getDouble(c.getColumnIndex(DBTableColumnIds.DBI_BTS_LON)); // Lon if (Double.doubleToRawLongBits(dLat) == 0 && Double.doubleToRawLongBits(dLng) == 0) { continue; } // TODO this (signal) is not in DBi_bts // signal = 1; //c.getInt(c.getColumnIndex(DBTableColumnIds.DBE_IMPORT_AVG_SIGNAL)); // signal // In case of missing or negative signal, set a default fake signal, // so that we can still draw signal circles. ? //if (signal <= 0) { // signal = 20; //} if (Double.doubleToRawLongBits(dLat) != 0 || Double.doubleToRawLongBits(dLng) != 0) { loc = new GeoPoint(dLat, dLng); CellTowerMarker ovm = new CellTowerMarker(getActivity(), mMap, "Cell ID: " + cellID, "", loc, new MarkerData(String.valueOf(cellID), String.valueOf(loc.getLatitude()), String.valueOf(loc.getLongitude()), String.valueOf(lac), String.valueOf(mcc), String.valueOf(mnc), "", false)); // The pin of our current position ovm.setIcon(getResources().getDrawable(R.drawable.ic_map_pin_blue)); items.add(ovm); } } while (c.moveToNext()); } else { getActivity().runOnUiThread(new Runnable() { @Override public void run() { Helpers.msgLong(getActivity(), getString(R.string.no_tracked_locations_found)); } }); } GeoPoint ret = new GeoPoint(0, 0); if (mBound) { try { int mcc = mAimsicdService.getCell().getMCC(); double[] d = mDbHelper.getDefaultLocation(mcc); ret = new GeoPoint(d[0], d[1]); } catch (Exception e) { log.error("Error getting default location!", e); } } if (c != null) { c.close(); } // plot neighbouring cells while (mAimsicdService == null) { try { if (isCancelled()) { return null; } Thread.sleep(100); } catch (InterruptedException e) { log.warn("thread interrupted", e); } } List<Cell> nc = mAimsicdService.getCellTracker().updateNeighbouringCells(); for (Cell cell : nc) { if (isCancelled()) { return null; } try { loc = new GeoPoint(cell.getLat(), cell.getLon()); CellTowerMarker ovm = new CellTowerMarker(getActivity(), mMap, getString(R.string.cell_id_label) + cell.getCID(), "", loc, new MarkerData(String.valueOf(cell.getCID()), String.valueOf(loc.getLatitude()), String.valueOf(loc.getLongitude()), String.valueOf(cell.getLAC()), String.valueOf(cell.getMCC()), String.valueOf(cell.getMNC()), "", false)); // The pin of other BTS ovm.setIcon(getResources().getDrawable(R.drawable.ic_map_pin_orange)); items.add(ovm); } catch (Exception e) { log.error("Error plotting neighbouring cells", e); } } mCellTowerGridMarkerClusterer.addAll(items); return ret; } /** * TODO: We need a manual way to add our own location in case: * a) GPS is jammed or not working * b) WiFi location is not used * c) Default MCC is too far off * * @param defaultLoc Default location to open map on */ @Override protected void onPostExecute(GeoPoint defaultLoc) { if (loc != null && (Double.doubleToRawLongBits(loc.getLatitude()) != 0 && Double.doubleToRawLongBits(loc.getLongitude()) != 0)) { mMap.getController().setZoom(16); mMap.getController().animateTo(new GeoPoint(loc.getLatitude(), loc.getLongitude())); } else { if (mBound) { // Try and find last known location and zoom there GeoLocation lastLoc = mAimsicdService.lastKnownLocation(); if (lastLoc != null) { loc = new GeoPoint(lastLoc.getLatitudeInDegrees(), lastLoc.getLongitudeInDegrees()); mMap.getController().setZoom(16); mMap.getController().animateTo(new GeoPoint(loc.getLatitude(), loc.getLongitude())); } else { //Use MCC to move camera to an approximate location near Countries Capital loc = defaultLoc; mMap.getController().setZoom(12); mMap.getController().animateTo(new GeoPoint(loc.getLatitude(), loc.getLongitude())); } } } if (mCellTowerGridMarkerClusterer != null) { if (BuildConfig.DEBUG && mCellTowerGridMarkerClusterer.getItems() != null) { log.verbose("CellTowerMarkers.invalidate() markers.size():" + mCellTowerGridMarkerClusterer.getItems().size()); } //Drawing markers of cell tower immediately as possible mCellTowerGridMarkerClusterer.invalidate(); } } }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); }
From source file:com.ichi2.libanki.Stats.java
/** * Weekly Breakdown//from www .ja va 2 s.co m */ public boolean calculateWeeklyBreakdown(int type) { mTitle = R.string.stats_weekly_breakdown; mAxisTitles = new int[] { R.string.stats_day_of_week, R.string.stats_percentage_correct, R.string.stats_reviews }; mValueLabels = new int[] { R.string.stats_percentage_correct, R.string.stats_answers }; mColors = new int[] { R.color.stats_counts, R.color.stats_hours }; mType = type; String lim = _revlogLimit().replaceAll("[\\[\\]]", ""); if (lim.length() > 0) { lim = " and " + lim; } Calendar sd = GregorianCalendar.getInstance(); sd.setTimeInMillis(mCol.getSched().getDayCutoff() * 1000); int pd = _periodDays(); if (pd > 0) { lim += " and id > " + ((mCol.getSched().getDayCutoff() - (86400 * pd)) * 1000); } long cutoff = mCol.getSched().getDayCutoff(); long cut = cutoff - sd.get(Calendar.HOUR_OF_DAY) * 3600; ArrayList<double[]> list = new ArrayList<double[]>(); Cursor cur = null; String query = "SELECT strftime('%w',datetime( cast(id/ 1000 -" + sd.get(Calendar.HOUR_OF_DAY) * 3600 + " as int), 'unixepoch')) as wd, " + "sum(case when ease = 1 then 0 else 1 end) / " + "cast(count() as float) * 100, " + "count() " + "from revlog " + "where type in (0,1,2) " + lim + " " + "group by wd " + "order by wd"; Timber.d(sd.get(Calendar.HOUR_OF_DAY) + " : " + cutoff + " weekly breakdown query: %s", query); try { cur = mCol.getDb().getDatabase().rawQuery(query, null); while (cur.moveToNext()) { list.add(new double[] { cur.getDouble(0), cur.getDouble(1), cur.getDouble(2) }); } } finally { if (cur != null && !cur.isClosed()) { cur.close(); } } //TODO adjust for breakdown, for now only copied from intervals // small adjustment for a proper chartbuilding with achartengine if (list.size() == 0) { list.add(0, new double[] { 0, 0, 0 }); } mSeriesList = new double[4][list.size()]; mPeak = 0.0; mMcount = 0.0; double minHour = Double.MAX_VALUE; double maxHour = 0; for (int i = 0; i < list.size(); i++) { double[] data = list.get(i); int hour = (int) data[0]; //double hour = data[0]; if (hour < minHour) minHour = hour; if (hour > maxHour) maxHour = hour; double pct = data[1]; if (pct > mPeak) mPeak = pct; mSeriesList[0][i] = hour; mSeriesList[1][i] = pct; mSeriesList[2][i] = data[2]; if (i == 0) { mSeriesList[3][i] = pct; } else { double prev = mSeriesList[3][i - 1]; double diff = pct - prev; diff /= 3.0; diff = Math.round(diff * 10.0) / 10.0; mSeriesList[3][i] = prev + diff; } if (data[2] > mMcount) mMcount = data[2]; if (mSeriesList[1][i] > mMaxCards) mMaxCards = (int) mSeriesList[1][i]; } mFirstElement = mSeriesList[0][0]; mLastElement = mSeriesList[0][mSeriesList[0].length - 1]; mMaxElements = (int) (maxHour - minHour); //some adjustments to not crash the chartbuilding with emtpy data if (mMaxElements == 0) { mMaxElements = 10; } if (mMcount == 0) { mMcount = 10; } if (mFirstElement == mLastElement) { mFirstElement = 0; mLastElement = 6; } if (mMaxCards == 0) mMaxCards = 10; return list.size() > 0; }
From source file:edu.cens.loci.provider.LociDbUtils.java
public LociLocation getPlaceLocationEstimationWithBestAccuracy(long start, long end) { LociLocation placeLoc = null;//from w ww . jav a 2 s . c om String[] columns = new String[] { Tracks._ID, Tracks.TIME, Tracks.LATITUDE, Tracks.LONGITUDE, Tracks.ALTITUDE, Tracks.SPEED, Tracks.BEARING, Tracks.ACCURACY }; String selection = Tracks.TIME + ">=" + start + " AND " + Tracks.TIME + " <= " + end; final SQLiteDatabase db = mDbHelper.getWritableDatabase(); Cursor cursor = db.query(Tables.TRACKS, columns, selection, null, null, null, null); float minAccuracy = Float.MAX_VALUE; if (cursor.moveToFirst()) { do { if (minAccuracy > cursor.getFloat(cursor.getColumnIndex(Tracks.ACCURACY))) { if (placeLoc == null) placeLoc = new LociLocation(LocationManager.GPS_PROVIDER); placeLoc.setTime(cursor.getLong(cursor.getColumnIndex(Tracks.TIME))); placeLoc.setLatitude(cursor.getDouble(cursor.getColumnIndex(Tracks.LATITUDE))); placeLoc.setLongitude(cursor.getDouble(cursor.getColumnIndex(Tracks.LONGITUDE))); placeLoc.setAltitude(cursor.getDouble(cursor.getColumnIndex(Tracks.ALTITUDE))); placeLoc.setSpeed(cursor.getFloat(cursor.getColumnIndex(Tracks.SPEED))); placeLoc.setBearing(cursor.getFloat(cursor.getColumnIndex(Tracks.BEARING))); placeLoc.setAccuracy(cursor.getFloat(cursor.getColumnIndex(Tracks.ACCURACY))); minAccuracy = placeLoc.getAccuracy(); } } while (cursor.moveToNext()); } cursor.close(); return placeLoc; }
From source file:com.balakrish.gpstracker.WaypointsListActivity.java
/** * Handle activity menu//from w w w. ja va2 s . com */ @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); final long waypointId = waypointsArrayAdapter.getItem((int) info.id).getId(); Cursor tmpCursor; String sql; switch (item.getItemId()) { case 0: // update waypoint in db updateWaypoint(waypointId); return true; case 1: deleteWaypoint(waypointId); return true; case 2: // email waypoint data using default email client String elevationUnit = app.getPreferences().getString("elevation_units", "m"); String elevationUnitLocalized = Utils.getLocalizedElevationUnit(this, elevationUnit); sql = "SELECT * FROM waypoints WHERE _id=" + waypointId + ";"; tmpCursor = app.getDatabase().rawQuery(sql, null); tmpCursor.moveToFirst(); double lat1 = tmpCursor.getDouble(tmpCursor.getColumnIndex("lat")) / 1E6; double lng1 = tmpCursor.getDouble(tmpCursor.getColumnIndex("lng")) / 1E6; String messageBody = getString(R.string.title) + ": " + tmpCursor.getString(tmpCursor.getColumnIndex("title")) + "\n\n" + getString(R.string.lat) + ": " + Utils.formatLat(lat1, 0) + "\n" + getString(R.string.lng) + ": " + Utils.formatLng(lng1, 0) + "\n" + getString(R.string.elevation) + ": " + Utils.formatElevation(tmpCursor.getFloat(tmpCursor.getColumnIndex("elevation")), elevationUnit) + elevationUnitLocalized + "\n\n" + "http://maps.google.com/?ll=" + lat1 + "," + lng1 + "&z=10"; tmpCursor.close(); final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND); emailIntent.setType("plain/text"); emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, getResources().getString(R.string.email_subject_waypoint)); emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, messageBody); this.startActivity(Intent.createChooser(emailIntent, getString(R.string.sending_email))); return true; case 3: this.showOnMap(waypointId); return true; case 4: // TODO: use a thread for online sync // sync one waypoint data with remote server // create temp waypoint from current record Waypoint wp = Waypoints.get(app.getDatabase(), waypointId); try { // preparing query string for calling web service String lat = Location.convert(wp.getLocation().getLatitude(), 0); String lng = Location.convert(wp.getLocation().getLongitude(), 0); String title = URLEncoder.encode(wp.getTitle()); String userName = app.getPreferences().getString("user_name", ""); String userPassword = app.getPreferences().getString("user_password", ""); String sessionValue = userName + "@" + Utils.md5("aripuca_session" + userPassword); if (userName.equals("") || userPassword.equals("")) { Toast.makeText(WaypointsListActivity.this, R.string.username_or_password_required, Toast.LENGTH_SHORT).show(); return false; } String queryString = "?do=ajax_map_handler&aripuca_session=" + sessionValue + "&action=add_point&lat=" + lat + "&lng=" + lng + "&z=16&n=" + title + "&d=AndroidSync"; // http connection HttpClient httpClient = new DefaultHttpClient(); HttpContext localContext = new BasicHttpContext(); HttpGet httpGet = new HttpGet( app.getPreferences().getString("online_sync_url", "http://tracker.aripuca.com") + queryString); HttpResponse response = httpClient.execute(httpGet, localContext); ByteArrayOutputStream outstream = new ByteArrayOutputStream(); response.getEntity().writeTo(outstream); // parsing JSON return JSONObject jsonObject = new JSONObject(outstream.toString()); Toast.makeText(WaypointsListActivity.this, jsonObject.getString("message").toString(), Toast.LENGTH_SHORT).show(); } catch (ClientProtocolException e) { Toast.makeText(WaypointsListActivity.this, "ClientProtocolException: " + e.getMessage(), Toast.LENGTH_SHORT).show(); } catch (IOException e) { Toast.makeText(WaypointsListActivity.this, "IOException " + e.getMessage(), Toast.LENGTH_SHORT) .show(); } catch (JSONException e) { Toast.makeText(WaypointsListActivity.this, "JSONException " + e.getMessage(), Toast.LENGTH_SHORT) .show(); } return true; default: return super.onContextItemSelected(item); } }
From source file:com.spoiledmilk.ibikecph.util.DB.java
public ArrayList<SearchListItem> getSearchHistory() { ArrayList<SearchListItem> ret = new ArrayList<SearchListItem>(); SQLiteDatabase db = getReadableDatabase(); if (db == null) return null; String[] columns = { KEY_ID, KEY_NAME, KEY_ADDRESS, KEY_START_DATE, KEY_END_DATE, KEY_SOURCE, KEY_SUBSOURCE, KEY_LAT, KEY_LONG };//from w ww. j a va2 s . co m Cursor cursor = db.query(TABLE_SEARCH_HISTORY, columns, null, null, null, null, KEY_START_DATE + " DESC", null); if (cursor != null && cursor.moveToFirst()) { while (cursor != null && !cursor.isAfterLast()) { int colId = cursor.getColumnIndex(KEY_ID); int colName = cursor.getColumnIndex(KEY_NAME); int colAddress = cursor.getColumnIndex(KEY_ADDRESS); int colStartDate = cursor.getColumnIndex(KEY_START_DATE); int colEndDate = cursor.getColumnIndex(KEY_END_DATE); int colSource = cursor.getColumnIndex(KEY_SOURCE); int colSubSource = cursor.getColumnIndex(KEY_SUBSOURCE); int colLat = cursor.getColumnIndex(KEY_LAT); int colLong = cursor.getColumnIndex(KEY_LONG); HistoryData hd = new HistoryData(cursor.getInt(colId), cursor.getString(colName), cursor.getString(colAddress), cursor.getString(colStartDate), cursor.getString(colEndDate), cursor.getString(colSource), cursor.getString(colSubSource), cursor.getDouble(colLat), cursor.getDouble(colLong)); if (hd.getName() != null && !hd.getName().trim().equals("")) { ret.add(hd); } if (ret.size() > 10) { break; } cursor.moveToNext(); } } if (cursor != null) cursor.close(); db.close(); return ret; }
From source file:com.spoiledmilk.ibikecph.util.DB.java
public SearchListItem getSearchHistoryByName(String name) { SearchListItem ret = null;//from ww w.j a v a 2 s .com SQLiteDatabase db = getReadableDatabase(); if (db == null) return null; String[] columns = { KEY_ID, KEY_NAME, KEY_ADDRESS, KEY_START_DATE, KEY_END_DATE, KEY_SOURCE, KEY_SUBSOURCE, KEY_LAT, KEY_LONG }; Cursor cursor = db.query(TABLE_SEARCH_HISTORY, columns, KEY_NAME + " = ? ", new String[] { name.trim() }, null, null, null, null); if (cursor != null && cursor.moveToFirst()) { while (cursor != null && !cursor.isAfterLast()) { int colId = cursor.getColumnIndex(KEY_ID); int colName = cursor.getColumnIndex(KEY_NAME); int colAddress = cursor.getColumnIndex(KEY_ADDRESS); int colStartDate = cursor.getColumnIndex(KEY_START_DATE); int colEndDate = cursor.getColumnIndex(KEY_END_DATE); int colSource = cursor.getColumnIndex(KEY_SOURCE); int colSubSource = cursor.getColumnIndex(KEY_SUBSOURCE); int colLat = cursor.getColumnIndex(KEY_LAT); int colLong = cursor.getColumnIndex(KEY_LONG); HistoryData hd = new HistoryData(cursor.getInt(colId), cursor.getString(colName), cursor.getString(colAddress), cursor.getString(colStartDate), cursor.getString(colEndDate), cursor.getString(colSource), cursor.getString(colSubSource), cursor.getDouble(colLat), cursor.getDouble(colLong)); if (hd.getName() != null && !hd.getName().trim().equals("")) { ret = hd; } break; } } if (cursor != null) cursor.close(); db.close(); return ret; }
From source file:edu.pdx.cecs.orcycle.TripUploader.java
@SuppressLint("SimpleDateFormat") private JSONObject getCoordsJSON(long tripId) throws JSONException { JSONObject jsonTripCoords = null;/*w w w.j a v a2s . co m*/ JSONArray jsonSensorReadings = null; SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); mDb.openReadOnly(); try { Cursor cursorTripCoords = mDb.fetchAllCoordsForTrip(tripId); // Build the map between JSON field name and phone db field name: Map<String, Integer> fieldMap = new HashMap<String, Integer>(); fieldMap.put(TRIP_COORDS_TIME, cursorTripCoords.getColumnIndex(DbAdapter.K_POINT_TIME)); fieldMap.put(TRIP_COORDS_LAT, cursorTripCoords.getColumnIndex(DbAdapter.K_POINT_LAT)); fieldMap.put(TRIP_COORDS_LON, cursorTripCoords.getColumnIndex(DbAdapter.K_POINT_LGT)); fieldMap.put(TRIP_COORDS_ALT, cursorTripCoords.getColumnIndex(DbAdapter.K_POINT_ALT)); fieldMap.put(TRIP_COORDS_SPEED, cursorTripCoords.getColumnIndex(DbAdapter.K_POINT_SPEED)); fieldMap.put(TRIP_COORDS_HACCURACY, cursorTripCoords.getColumnIndex(DbAdapter.K_POINT_ACC)); fieldMap.put(TRIP_COORDS_VACCURACY, cursorTripCoords.getColumnIndex(DbAdapter.K_POINT_ACC)); // Build JSON objects for each coordinate: jsonTripCoords = new JSONObject(); double coordTime; while (!cursorTripCoords.isAfterLast()) { // ***************** // * Get coordinates // ***************** coordTime = cursorTripCoords.getDouble(fieldMap.get(TRIP_COORDS_TIME)); JSONObject jsonCoord = new JSONObject(); jsonCoord.put(TRIP_COORDS_TIME, df.format(coordTime)); jsonCoord.put(TRIP_COORDS_LAT, cursorTripCoords.getDouble(fieldMap.get(TRIP_COORDS_LAT)) / 1E6); jsonCoord.put(TRIP_COORDS_LON, cursorTripCoords.getDouble(fieldMap.get(TRIP_COORDS_LON)) / 1E6); jsonCoord.put(TRIP_COORDS_ALT, dr1(cursorTripCoords.getDouble(fieldMap.get(TRIP_COORDS_ALT)))); jsonCoord.put(TRIP_COORDS_SPEED, dr1(cursorTripCoords.getDouble(fieldMap.get(TRIP_COORDS_SPEED)))); jsonCoord.put(TRIP_COORDS_HACCURACY, cursorTripCoords.getDouble(fieldMap.get(TRIP_COORDS_HACCURACY))); jsonCoord.put(TRIP_COORDS_VACCURACY, cursorTripCoords.getDouble(fieldMap.get(TRIP_COORDS_VACCURACY))); // ********************************************************** // * Get all sensor readings corresponding to this time index // ********************************************************** jsonSensorReadings = getJsonSensorReadings(coordTime); if ((null != jsonSensorReadings) && (jsonSensorReadings.length() > 0)) { jsonCoord.put(TRIP_COORDS_SENSOR_READINGS, jsonSensorReadings); } // **************************************************** // * Insert sensor readings into jSON coordinate object // **************************************************** jsonTripCoords.put(jsonCoord.getString("r"), jsonCoord); // move to next coordinate cursorTripCoords.moveToNext(); } cursorTripCoords.close(); } catch (Exception ex) { Log.e(MODULE_TAG, ex.getMessage()); } finally { mDb.close(); } return jsonTripCoords; }
From source file:nl.sogeti.android.gpstracker.viewer.LoggerMap.java
private void createListeners() { mFab.setOnClickListener(new View.OnClickListener() { @Override/* www .j a v a 2 s .com*/ public void onClick(View v) { Intent intent = new Intent(LoggerMap.this, ControlTracking.class); startActivityForResult(intent, MENU_TRACKING); } }); /******************************************************* * 8 Runnable listener actions */ speedCalculator = new Runnable() { @Override public void run() { double avgspeed = 0.0; ContentResolver resolver = LoggerMap.this.getContentResolver(); Cursor waypointsCursor = null; try { waypointsCursor = resolver.query( Uri.withAppendedPath(Tracks.CONTENT_URI, LoggerMap.this.mTrackId + "/waypoints"), new String[] { "avg(" + Waypoints.SPEED + ")", "max(" + Waypoints.SPEED + ")" }, null, null, null); if (waypointsCursor != null && waypointsCursor.moveToLast()) { double average = waypointsCursor.getDouble(0); double maxBasedAverage = waypointsCursor.getDouble(1) / 2; avgspeed = Math.min(average, maxBasedAverage); } if (avgspeed < 2) { avgspeed = 5.55d / 2; } } finally { if (waypointsCursor != null) { waypointsCursor.close(); } } mAverageSpeed = avgspeed; runOnUiThread(new Runnable() { @Override public void run() { updateSpeedColoring(); } }); } }; mServiceConnected = new Runnable() { @Override public void run() { updateBlankingBehavior(); } }; /******************************************************* * 8 Various dialog listeners */ mNoteSelectDialogListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Uri selected = (Uri) mGallery.getSelectedItem(); SegmentOverlay.handleMedia(LoggerMap.this, selected); } }; mGroupCheckedChangeListener = new android.widget.RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { switch (checkedId) { case R.id.layer_google_satellite: setSatelliteOverlay(true); break; case R.id.layer_google_regular: setSatelliteOverlay(false); break; default: break; } } }; mCheckedChangeListener = new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { int checkedId; checkedId = buttonView.getId(); switch (checkedId) { case R.id.layer_traffic: setTrafficOverlay(isChecked); break; case R.id.layer_speed: setSpeedOverlay(isChecked); break; case R.id.layer_altitude: setAltitudeOverlay(isChecked); break; case R.id.layer_distance: setDistanceOverlay(isChecked); break; case R.id.layer_compass: setCompassOverlay(isChecked); break; case R.id.layer_location: setLocationOverlay(isChecked); break; default: break; } } }; mNoTrackDialogListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Log.d( TAG, "mNoTrackDialogListener" + which); Intent tracklistIntent = new Intent(LoggerMap.this, TrackList.class); tracklistIntent.putExtra(Tracks._ID, LoggerMap.this.mTrackId); startActivityForResult(tracklistIntent, MENU_TRACKLIST); } }; /** * Listeners to events outside this mapview */ mSharedPreferenceChangeListener = new OnSharedPreferenceChangeListener() { @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (key.equals(Constants.TRACKCOLORING)) { mAverageSpeed = 0.0; updateSpeedColoring(); } else if (key.equals(Constants.DISABLEBLANKING) || key.equals(Constants.DISABLEDIMMING)) { updateBlankingBehavior(); } else if (key.equals(Constants.SPEED)) { updateSpeedDisplayVisibility(); } else if (key.equals(Constants.ALTITUDE)) { updateAltitudeDisplayVisibility(); } else if (key.equals(Constants.DISTANCE)) { updateDistanceDisplayVisibility(); } else if (key.equals(Constants.COMPASS)) { updateCompassDisplayVisibility(); } else if (key.equals(Constants.TRAFFIC)) { updateGoogleOverlays(); } else if (key.equals(Constants.SATELLITE)) { updateGoogleOverlays(); } else if (key.equals(Constants.LOCATION)) { updateLocationDisplayVisibility(); } } }; mTrackMediasObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfUpdate) { if (!selfUpdate) { if (mLastSegmentOverlay != null) { mLastSegmentOverlay.calculateMedia(); mMapView.postInvalidate(); } } else { Log.w(this, "mTrackMediasObserver skipping change on " + mLastSegment); } } }; mTrackSegmentsObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfUpdate) { if (!selfUpdate) { LoggerMap.this.updateDataOverlays(); } else { Log.w(this, "mTrackSegmentsObserver skipping change on " + mLastSegment); } } }; mSegmentWaypointsObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfUpdate) { if (!selfUpdate) { LoggerMap.this.updateTrackNumbers(); if (mLastSegmentOverlay != null) { moveActiveViewWindow(); } else { Log.e(this, "Error the last segment changed but it is not on screen! " + mLastSegment); } } else { Log.w(this, "mSegmentWaypointsObserver skipping change on " + mLastSegment); } } }; mUnitsChangeListener = new UnitsI18n.UnitsChangeListener() { @Override public void onUnitsChange() { mAverageSpeed = 0.0; updateTrackNumbers(); updateSpeedColoring(); } }; }