Example usage for android.database Cursor getDouble

List of usage examples for android.database Cursor getDouble

Introduction

In this page you can find the example usage for android.database Cursor getDouble.

Prototype

double getDouble(int columnIndex);

Source Link

Document

Returns the value of the requested column as a double.

Usage

From source file:edu.pdx.cecs.orcycle.NoteUploader.java

private JSONObject getNoteJSON(long noteId) throws JSONException {
    try {// w  w  w.  j a  va2s  . co m
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String noteImageFileName;

        mDb.openReadOnly();
        try {
            Cursor noteCursor = mDb.fetchNote(noteId);

            try {
                Map<String, Integer> fieldMap = new HashMap<String, Integer>();
                fieldMap.put(NOTE_TRIP_ID, noteCursor.getColumnIndex(DbAdapter.K_NOTE_TRIP_ID));
                fieldMap.put(NOTE_RECORDED, noteCursor.getColumnIndex(DbAdapter.K_NOTE_RECORDED));
                fieldMap.put(NOTE_LAT, noteCursor.getColumnIndex(DbAdapter.K_NOTE_LAT));
                fieldMap.put(NOTE_LGT, noteCursor.getColumnIndex(DbAdapter.K_NOTE_LGT));
                fieldMap.put(NOTE_HACC, noteCursor.getColumnIndex(DbAdapter.K_NOTE_ACC));
                fieldMap.put(NOTE_VACC, noteCursor.getColumnIndex(DbAdapter.K_NOTE_ACC));
                fieldMap.put(NOTE_ALT, noteCursor.getColumnIndex(DbAdapter.K_NOTE_ALT));
                fieldMap.put(NOTE_SPEED, noteCursor.getColumnIndex(DbAdapter.K_NOTE_SPEED));
                fieldMap.put(NOTE_DETAILS, noteCursor.getColumnIndex(DbAdapter.K_NOTE_DETAILS));
                fieldMap.put(NOTE_IMGURL, noteCursor.getColumnIndex(DbAdapter.K_NOTE_IMGURL));
                fieldMap.put(NOTE_REPORT_DATE, noteCursor.getColumnIndex(DbAdapter.K_NOTE_REPORT_DATE));
                fieldMap.put(NOTE_EMAIL_SENT, noteCursor.getColumnIndex(DbAdapter.K_NOTE_EMAIL_SENT));

                JSONObject note = new JSONObject();

                note.put(NOTE_TRIP_ID, noteCursor.getInt(fieldMap.get(NOTE_TRIP_ID)));
                note.put(NOTE_RECORDED, df.format(noteCursor.getDouble(fieldMap.get(NOTE_RECORDED))));
                note.put(NOTE_LAT, noteCursor.getDouble(fieldMap.get(NOTE_LAT)) / 1E6);
                note.put(NOTE_LGT, noteCursor.getDouble(fieldMap.get(NOTE_LGT)) / 1E6);
                note.put(NOTE_HACC, noteCursor.getDouble(fieldMap.get(NOTE_HACC)));
                note.put(NOTE_VACC, noteCursor.getDouble(fieldMap.get(NOTE_VACC)));
                note.put(NOTE_ALT, noteCursor.getDouble(fieldMap.get(NOTE_ALT)));
                note.put(NOTE_SPEED, noteCursor.getDouble(fieldMap.get(NOTE_SPEED)));
                note.put(NOTE_DETAILS, noteCursor.getString(fieldMap.get(NOTE_DETAILS)));
                note.put(NOTE_IMGURL, noteImageFileName = noteCursor.getString(fieldMap.get(NOTE_IMGURL)));

                long reportDate = noteCursor.getLong(fieldMap.get(NOTE_REPORT_DATE));
                String formattedDate = reportDateFormatter.format(reportDate);
                note.put(NOTE_REPORT_DATE, formattedDate);

                boolean emailSent = (noteCursor.getInt(fieldMap.get(NOTE_EMAIL_SENT)) == 1 ? true : false);
                note.put(NOTE_EMAIL_SENT, emailSent);

                if ((null != noteImageFileName) && (!noteImageFileName.equals("")))
                    imageData = mDb.getNoteImageData(noteId);
                else
                    imageData = null;

                return note;
            } catch (Exception ex) {
                Log.e(MODULE_TAG, ex.getMessage());
            } finally {
                noteCursor.close();
            }
            return null;
        } catch (Exception ex) {
            Log.e(MODULE_TAG, ex.getMessage());
        } finally {
            mDb.close();
        }
        return null;
    } catch (Exception ex) {
        Log.e(MODULE_TAG, ex.getMessage());
    }
    return null;
}

From source file:org.runnerup.view.DetailActivity.java

private void loadRoute() {
    final GraphProducer graphData = new GraphProducer();

    final String[] from = new String[] { DB.LOCATION.LATITUDE, DB.LOCATION.LONGITUDE, DB.LOCATION.TYPE,
            DB.LOCATION.TIME, DB.LOCATION.LAP, DB.LOCATION.HR };

    loadRouteTask = new AsyncTask<String, String, Route>() {

        @Override/*from  w  w w . ja  v  a  2s  .c  o m*/
        protected Route doInBackground(String... params) {

            int cnt = 0;
            Route route = null;
            Cursor c = mDB.query(DB.LOCATION.TABLE, from, "activity_id == " + mID, null, null, null, "_id",
                    null);
            if (c.moveToFirst()) {
                route = new Route();
                double acc_distance = 0;
                double tot_distance = 0;
                int cnt_distance = 0;
                LatLng lastLocation = null;
                long lastTime = 0;
                int lastLap = -1;
                int hr = 0;
                do {
                    cnt++;
                    LatLng point = new LatLng(c.getDouble(0), c.getDouble(1));
                    route.path.add(point);
                    route.bounds.include(point);
                    int type = c.getInt(2);
                    long time = c.getLong(3);
                    int lap = c.getInt(4);
                    if (!c.isNull(5))
                        hr = c.getInt(5);
                    MarkerOptions m;
                    switch (type) {
                    case DB.LOCATION.TYPE_START:
                    case DB.LOCATION.TYPE_END:
                    case DB.LOCATION.TYPE_PAUSE:
                    case DB.LOCATION.TYPE_RESUME:
                        if (type == DB.LOCATION.TYPE_PAUSE) {
                            if (lap != lastLap) {
                                graphData.clear(tot_distance);
                            } else if (lastTime != 0 && lastLocation != null) {
                                float res[] = { 0 };
                                Location.distanceBetween(lastLocation.latitude, lastLocation.longitude,
                                        point.latitude, point.longitude, res);
                                graphData.addObservation(time - lastTime, res[0], tot_distance, hr);
                                // hrList.clear();
                                graphData.clear(tot_distance);
                            }
                            lastLap = lap;
                            lastTime = 0;
                        } else if (type == DB.LOCATION.TYPE_RESUME) {
                            lastLap = lap;
                            lastTime = time;
                        }
                        m = new MarkerOptions();
                        m.position((lastLocation = point));
                        m.title(type == DB.LOCATION.TYPE_START ? "Start"
                                : type == DB.LOCATION.TYPE_END ? "Stop"
                                        : type == DB.LOCATION.TYPE_PAUSE ? "Pause"
                                                : type == DB.LOCATION.TYPE_RESUME ? "Resume" : "<Unknown>");
                        m.snippet(null);
                        m.draggable(false);
                        route.markers.add(m);
                        break;
                    case DB.LOCATION.TYPE_GPS:
                        float res[] = { 0 };
                        Location.distanceBetween(lastLocation.latitude, lastLocation.longitude, point.latitude,
                                point.longitude, res);
                        acc_distance += res[0];
                        tot_distance += res[0];

                        if (lap != lastLap) {
                            graphData.clear(tot_distance);
                        } else if (lastTime != 0) {
                            graphData.addObservation(time - lastTime, res[0], tot_distance, hr);
                        }
                        lastLap = lap;
                        lastTime = time;

                        if (acc_distance >= formatter.getUnitMeters()) {
                            cnt_distance++;
                            acc_distance = 0;
                            m = new MarkerOptions();
                            m.position(point);
                            m.title("" + cnt_distance + " " + formatter.getUnitString());
                            m.snippet(null);
                            m.draggable(false);
                            route.markers.add(m);
                        }
                        lastLocation = point;
                        break;
                    }
                } while (c.moveToNext());
                System.err.println("Finished loading " + cnt + " points");
            }
            c.close();
            return route;
        }

        @Override
        protected void onPostExecute(Route route) {

            if (route != null) {
                graphData.complete(graphView);
                if (!graphData.HasHRInfo()) {
                    graphTab.addView(graphView);
                } else {
                    graphTab.addView(graphView, new LayoutParams(LayoutParams.MATCH_PARENT, 0, 0.5f));

                    graphTab.addView(graphView2, new LayoutParams(LayoutParams.MATCH_PARENT, 0, 0.5f));
                }

                if (graphData.HasHRZHist()) {
                    hrzonesBarLayout.setVisibility(View.VISIBLE);
                    hrzonesBarLayout.addView(hrzonesBar);
                } else {
                    hrzonesBarLayout.setVisibility(View.GONE);
                }

                if (map != null) {
                    map.addPolyline(route.path);
                    mapBounds = route.bounds.build();
                    System.err.println("Added polyline");
                    int cnt = 0;
                    for (MarkerOptions m : route.markers) {
                        cnt++;
                        map.addMarker(m);
                    }
                    System.err.println("Added " + cnt + " markers");

                    route = new Route(); // release mem for old...
                }
            }
        }
    }.execute("kalle");
}

From source file:com.spoiledmilk.ibikecph.util.DB.java

public ArrayList<SearchListItem> getSearchHistoryForString(String srchString) {

    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 };/*  w  ww .j a v  a2s  .c  o m*/

    Cursor cursor = db.query(TABLE_SEARCH_HISTORY, columns, KEY_NAME + " LIKE ? OR " + KEY_ADDRESS + " LIKE ?",
            new String[] { "%" + srchString + "%", "%" + srchString + "%" }, 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.add(hd);
            cursor.moveToNext();
        }
    }

    if (cursor != null)
        cursor.close();

    db.close();

    return ret;
}

From source file:com.nogago.android.tracks.TrackListActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setVolumeControlStream(TextToSpeech.Engine.DEFAULT_STREAM);
    setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
    setContentView(R.layout.track_list);

    trackRecordingServiceConnection = new TrackRecordingServiceConnection(this, bindChangedCallback);

    getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE)
            .registerOnSharedPreferenceChangeListener(sharedPreferenceChangeListener);
    metricUnits = PreferencesUtils.getBoolean(this, R.string.metric_units_key,
            PreferencesUtils.METRIC_UNITS_DEFAULT);
    recordingTrackId = PreferencesUtils.getLong(this, R.string.recording_track_id_key);

    //    ImageButton recordImageButton = (ImageButton) findViewById(R.id.track_list_record_button);
    //    recordImageButton.setOnClickListener(new View.OnClickListener() {
    //      @Override
    //      public void onClick(View v) {
    //        updateMenuItems(true);
    //        startRecording();
    //      }//  ww w .  java 2 s . c  o  m
    //    });

    listView = (ListView) findViewById(R.id.track_list);
    listView.setEmptyView(findViewById(R.id.track_list_empty));
    listView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent intent = IntentUtils.newIntent(TrackListActivity.this, TrackDetailActivity.class)
                    .putExtra(TrackDetailActivity.EXTRA_TRACK_ID, id);
            startActivity(intent);
        }
    });
    resourceCursorAdapter = new ResourceCursorAdapter(this, R.layout.list_item, null, 0) {
        @Override
        public void bindView(View view, Context context, Cursor cursor) {
            int idIndex = cursor.getColumnIndex(TracksColumns._ID);
            int nameIndex = cursor.getColumnIndex(TracksColumns.NAME);
            int descriptionIndex = cursor.getColumnIndex(TracksColumns.DESCRIPTION);
            int categoryIndex = cursor.getColumnIndex(TracksColumns.CATEGORY);
            int startTimeIndex = cursor.getColumnIndexOrThrow(TracksColumns.STARTTIME);
            int totalDistanceIndex = cursor.getColumnIndexOrThrow(TracksColumns.TOTALDISTANCE);
            int totalTimeIndex = cursor.getColumnIndexOrThrow(TracksColumns.TOTALTIME);
            int iconIndex = cursor.getColumnIndex(TracksColumns.ICON);

            boolean isRecording = cursor.getLong(idIndex) == recordingTrackId;
            String name = cursor.getString(nameIndex);
            int iconId = isRecording ? R.drawable.menu_record_track
                    : TrackIconUtils.getIconDrawable(cursor.getString(iconIndex));
            String iconContentDescription = getString(
                    isRecording ? R.string.icon_recording : R.string.icon_track);
            String category = cursor.getString(categoryIndex);
            String totalTime = isRecording ? null
                    : StringUtils.formatElapsedTime(cursor.getLong(totalTimeIndex));
            String totalDistance = isRecording ? null
                    : StringUtils.formatDistance(TrackListActivity.this, cursor.getDouble(totalDistanceIndex),
                            metricUnits);
            long startTime = cursor.getLong(startTimeIndex);
            String description = cursor.getString(descriptionIndex);
            ListItemUtils.setListItem(TrackListActivity.this, view, name, iconId, iconContentDescription,
                    category, totalTime, totalDistance, startTime, description);
        }
    };
    listView.setAdapter(resourceCursorAdapter);
    ApiAdapterFactory.getApiAdapter().configureListViewContextualMenu(this, listView,
            contextualActionModeCallback);

    getSupportLoaderManager().initLoader(0, null, new LoaderCallbacks<Cursor>() {
        @Override
        public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
            return new CursorLoader(TrackListActivity.this, TracksColumns.CONTENT_URI, PROJECTION, null, null,
                    TracksColumns._ID + " DESC");
        }

        @Override
        public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
            resourceCursorAdapter.swapCursor(cursor);
        }

        @Override
        public void onLoaderReset(Loader<Cursor> loader) {
            resourceCursorAdapter.swapCursor(null);
        }
    });
    showStartupDialogs();
}

From source file:com.money.manager.ex.home.DashboardFragment.java

private View showTableLayoutTopWithdrawals(Cursor cursor) {
    LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dashboard_summary_layout, null);
    CurrencyService currencyService = new CurrencyService(getActivity().getApplicationContext());

    // Textview Title
    TextView title = (TextView) layout.findViewById(R.id.textViewTitle);
    title.setText(R.string.top_withdrawals_last_30_days);
    // Table/*from ww w.j  a va  2s . c  o m*/
    TableLayout tableLayout = (TableLayout) layout.findViewById(R.id.tableLayoutSummary);
    // Create Title
    tableLayout.addView(createTableRow(
            new String[] { "<small><b>" + getString(R.string.category) + "</b></small>",
                    "<small><b>" + getString(R.string.quantity) + "</b></small>",
                    "<small><b>" + getString(R.string.summary) + "</b></small>" },
            new Float[] { 1f, null, null }, new Integer[] { null, Gravity.RIGHT, Gravity.RIGHT },
            new Integer[][] { null, { 0, 0, padding_in_px, 0 }, null }));
    // add rows
    while (cursor.moveToNext()) {
        // load values
        String category = "<b>" + cursor.getString(cursor.getColumnIndex(ViewMobileData.Category)) + "</b>";
        if (!TextUtils.isEmpty(cursor.getString(cursor.getColumnIndex(ViewMobileData.Subcategory)))) {
            category += " : " + cursor.getString(cursor.getColumnIndex(ViewMobileData.Subcategory));
        }
        double total = cursor.getDouble(cursor.getColumnIndex("TOTAL"));
        int num = cursor.getInt(cursor.getColumnIndex("NUM"));
        // Add Row
        tableLayout.addView(createTableRow(
                new String[] { "<small>" + category + "</small>",
                        "<small><i>" + Integer.toString(num) + "</i></small>",
                        "<small>" + currencyService.getCurrencyFormatted(currencyService.getBaseCurrencyId(),
                                MoneyFactory.fromDouble(total)) + "</small>" },
                new Float[] { 1f, null, null }, new Integer[] { null, Gravity.RIGHT, Gravity.RIGHT },
                new Integer[][] { null, { 0, 0, padding_in_px, 0 }, null }));
    }
    // return Layout
    return layout;
}

From source file:com.upenn.chriswang1990.sunshine.DetailFragment.java

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {

    if (data != null && data.moveToFirst()) {
        // Read weather condition ID from cursor
        int weatherId = data.getInt(COL_WEATHER_CONDITION_ID);
        mIconView.setImageResource(Utility.getArtResourceForWeatherCondition(weatherId));

        //read city name and update
        String cityName = data.getString(COL_CITY_NAME);
        mCityNameView.setText(cityName);
        mCityNameView.setContentDescription(getString(R.string.a11y_city_name, cityName));

        // Read date from cursor and update views for day of week and date
        long unixTimestamp = data.getLong(COL_WEATHER_DATE_UNIX);
        String timezoneID = data.getString(COL_TIMEZONE_ID);
        String dateText = Utility.getFullFriendlyDayString(getActivity(), unixTimestamp, timezoneID);
        mDateView.setText(dateText);/*  w w  w . j a v  a  2  s.com*/

        // Read description from cursor and update view
        String description = Utility.getStringForWeatherCondition(getActivity(), weatherId);
        mDescriptionView.setText(description);
        mDescriptionView.setContentDescription(getString(R.string.a11y_forecast, description));
        // For accessibility, add a content description to the icon field. Because the ImageView
        // is independently focusable, it's better to have a description of the image. Using
        // null is appropriate when the image is purely decorative or when the image already
        // has text describing it in the same UI component.
        mIconView.setContentDescription(getString(R.string.a11y_forecast_icon, description));

        // Read high temperature from cursor and update view
        double high = data.getDouble(COL_WEATHER_MAX_TEMP);
        String highString = Utility.formatTemperature(getActivity(), high);
        mHighTempView.setText(highString);
        mHighTempView.setContentDescription(getString(R.string.a11y_high_temp, highString));

        // Read low temperature from cursor and update view
        double low = data.getDouble(COL_WEATHER_MIN_TEMP);
        String lowString = Utility.formatTemperature(getActivity(), low);
        mLowTempView.setText(lowString);
        mLowTempView.setContentDescription(getString(R.string.a11y_low_temp, lowString));

        // Read humidity from cursor and update view
        float humidity = data.getFloat(COL_WEATHER_HUMIDITY);
        mHumidityView.setText(getString(R.string.format_humidity, humidity));
        mHumidityView.setContentDescription(getString(R.string.a11y_humidity, mHumidityView.getText()));
        mHumidityLabelView.setContentDescription(mHumidityView.getContentDescription());

        // Read wind speed and direction from cursor and update view
        float windSpeedStr = data.getFloat(COL_WEATHER_WIND_SPEED);
        float windDirStr = data.getFloat(COL_WEATHER_DEGREES);
        mWindView.setText(Utility.getFormattedWind(getActivity(), windSpeedStr, windDirStr));
        mWindView.setContentDescription(getString(R.string.a11y_wind, mWindView.getText()));
        mWindLabelView.setContentDescription(mWindView.getContentDescription());

        // Read pressure from cursor and update view
        float pressure = data.getFloat(COL_WEATHER_PRESSURE);
        mPressureView.setText(getString(R.string.format_pressure, pressure));
        mPressureView.setContentDescription(getString(R.string.a11y_pressure, mPressureView.getText()));
        mPressureLabelView.setContentDescription(mPressureView.getContentDescription());

        forecastStr = String.format(getContext().getString(R.string.format_share_string), cityName, dateText,
                description, highString, lowString);

        AppCompatActivity activity = (AppCompatActivity) getActivity();
        Toolbar toolbarView = (Toolbar) getView().findViewById(R.id.toolbar);

        // We need to start the enter transition after the data has loaded
        if (activity instanceof DetailActivity) {
            activity.supportStartPostponedEnterTransition();

            if (null != toolbarView) {
                activity.setSupportActionBar(toolbarView);
                activity.getSupportActionBar().setDisplayShowTitleEnabled(false);
                activity.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            }
        } else {
            if (null != toolbarView) {
                Menu menu = toolbarView.getMenu();
                if (null != menu)
                    menu.clear();
                toolbarView.inflateMenu(R.menu.detail_fragment);
                finishCreatingMenu(toolbarView.getMenu());
            }
        }
    }
}

From source file:org.cowboycoders.cyclisimo.TrackListActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setVolumeControlStream(TextToSpeech.Engine.DEFAULT_STREAM);
    setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
    setContentView(R.layout.track_list);

    sharedPreferences = getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE);

    trackRecordingServiceConnection = new TrackRecordingServiceConnection(this, bindChangedCallback);

    trackController = new TrackController(this, trackRecordingServiceConnection, true, recordListener,
            stopListener);/*from   w w  w .j  a v  a  2s . com*/

    listView = (ListView) findViewById(R.id.track_list);
    listView.setEmptyView(findViewById(R.id.track_list_empty_view));
    listView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent intent = IntentUtils.newIntent(TrackListActivity.this, TrackDetailActivity.class)
                    .putExtra(TrackDetailActivity.EXTRA_TRACK_ID, id);
            intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
            intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
    });
    resourceCursorAdapter = new ResourceCursorAdapter(this, R.layout.list_item, null, 0) {
        @Override
        public void bindView(View view, Context context, Cursor cursor) {
            int idIndex = cursor.getColumnIndex(TracksColumns._ID);
            int iconIndex = cursor.getColumnIndex(TracksColumns.ICON);
            int nameIndex = cursor.getColumnIndex(TracksColumns.NAME);
            int categoryIndex = cursor.getColumnIndex(TracksColumns.CATEGORY);
            int totalTimeIndex = cursor.getColumnIndexOrThrow(TracksColumns.TOTALTIME);
            int totalDistanceIndex = cursor.getColumnIndexOrThrow(TracksColumns.TOTALDISTANCE);
            int startTimeIndex = cursor.getColumnIndexOrThrow(TracksColumns.STARTTIME);
            int descriptionIndex = cursor.getColumnIndex(TracksColumns.DESCRIPTION);

            boolean isRecording = cursor.getLong(idIndex) == recordingTrackId;
            int iconId = TrackIconUtils.getIconDrawable(cursor.getString(iconIndex));
            String name = cursor.getString(nameIndex);
            String totalTime = StringUtils.formatElapsedTime(cursor.getLong(totalTimeIndex));
            String totalDistance = StringUtils.formatDistance(TrackListActivity.this,
                    cursor.getDouble(totalDistanceIndex), metricUnits);
            long startTime = cursor.getLong(startTimeIndex);
            String startTimeDisplay = StringUtils.formatDateTime(context, startTime).equals(name) ? null
                    : StringUtils.formatRelativeDateTime(context, startTime);

            ListItemUtils.setListItem(TrackListActivity.this, view, isRecording, recordingTrackPaused, iconId,
                    R.string.icon_track, name, cursor.getString(categoryIndex), totalTime, totalDistance,
                    startTimeDisplay, cursor.getString(descriptionIndex));
        }
    };
    listView.setAdapter(resourceCursorAdapter);
    ApiAdapterFactory.getApiAdapter().configureListViewContextualMenu(this, listView,
            contextualActionModeCallback);

    getSupportLoaderManager().initLoader(0, null, new LoaderCallbacks<Cursor>() {
        @Override
        public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
            updateCurrentUserId();
            long userId = currentUserId.get();
            String selection = TracksColumns.OWNER + "=?";
            String[] args = new String[] { Long.toString(userId) };
            return new CursorLoader(TrackListActivity.this, TracksColumns.CONTENT_URI, PROJECTION, selection,
                    args, TracksColumns._ID + " DESC");
        }

        @Override
        public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
            resourceCursorAdapter.swapCursor(cursor);
        }

        @Override
        public void onLoaderReset(Loader<Cursor> loader) {
            resourceCursorAdapter.swapCursor(null);
        }
    });
    trackDataHub = TrackDataHub.newInstance(this);
    if (savedInstanceState != null) {
        startGps = savedInstanceState.getBoolean(START_GPS_KEY);
    }
    showStartupDialogs();
}

From source file:org.cowboycoders.cyclismo.TrackListActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setVolumeControlStream(TextToSpeech.Engine.DEFAULT_STREAM);
    setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
    setContentView(R.layout.track_list);

    sharedPreferences = getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE);

    trackRecordingServiceConnection = new TrackRecordingServiceConnection(this, bindChangedCallback);

    trackController = new TrackController(this, trackRecordingServiceConnection, true, recordListener,
            stopListener, -1);//from  w  w w . j av a2s  . c  o  m

    listView = (ListView) findViewById(R.id.track_list);
    listView.setEmptyView(findViewById(R.id.track_list_empty_view));
    listView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent intent = IntentUtils.newIntent(TrackListActivity.this, TrackDetailActivity.class)
                    .putExtra(TrackDetailActivity.EXTRA_TRACK_ID, id);
            if (isRecording() && id == recordingTrackId) {
                Log.d(TAG, "recordingTrackId: " + recordingTrackId);
                recordingCourseId = PreferencesUtils.getLong(TrackListActivity.this,
                        R.string.recording_course_track_id_key);
                intent.putExtra(TrackDetailActivity.EXTRA_COURSE_TRACK_ID, recordingCourseId)
                        .putExtra(TrackDetailActivity.EXTRA_USE_COURSE_PROVIDER, false);
            }
            intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
            intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
    });
    resourceCursorAdapter = new ResourceCursorAdapter(this, R.layout.list_item, null, 0) {
        @Override
        public void bindView(View view, Context context, Cursor cursor) {
            int idIndex = cursor.getColumnIndex(TracksColumns._ID);
            int iconIndex = cursor.getColumnIndex(TracksColumns.ICON);
            int nameIndex = cursor.getColumnIndex(TracksColumns.NAME);
            int categoryIndex = cursor.getColumnIndex(TracksColumns.CATEGORY);
            int totalTimeIndex = cursor.getColumnIndexOrThrow(TracksColumns.TOTALTIME);
            int totalDistanceIndex = cursor.getColumnIndexOrThrow(TracksColumns.TOTALDISTANCE);
            int startTimeIndex = cursor.getColumnIndexOrThrow(TracksColumns.STARTTIME);
            int descriptionIndex = cursor.getColumnIndex(TracksColumns.DESCRIPTION);

            boolean isRecording = cursor.getLong(idIndex) == recordingTrackId;
            int iconId = TrackIconUtils.getIconDrawable(cursor.getString(iconIndex));
            String name = cursor.getString(nameIndex);
            String totalTime = StringUtils.formatElapsedTime(cursor.getLong(totalTimeIndex));
            String totalDistance = StringUtils.formatDistance(TrackListActivity.this,
                    cursor.getDouble(totalDistanceIndex), metricUnits);
            long startTime = cursor.getLong(startTimeIndex);
            String startTimeDisplay = StringUtils.formatDateTime(context, startTime).equals(name) ? null
                    : StringUtils.formatRelativeDateTime(context, startTime);

            ListItemUtils.setListItem(TrackListActivity.this, view, isRecording, recordingTrackPaused, iconId,
                    R.string.icon_track, name, cursor.getString(categoryIndex), totalTime, totalDistance,
                    startTimeDisplay, cursor.getString(descriptionIndex));
        }
    };
    listView.setAdapter(resourceCursorAdapter);
    ApiAdapterFactory.getApiAdapter().configureListViewContextualMenu(this, listView,
            contextualActionModeCallback);

    getSupportLoaderManager().initLoader(0, null, new LoaderCallbacks<Cursor>() {
        @Override
        public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
            updateCurrentUserId();
            long userId = currentUserId.get();
            String selection = TracksColumns.OWNER + "=?";
            String[] args = new String[] { Long.toString(userId) };
            return new CursorLoader(TrackListActivity.this, TracksColumns.CONTENT_URI, PROJECTION, selection,
                    args, TracksColumns._ID + " DESC");
        }

        @Override
        public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
            resourceCursorAdapter.swapCursor(cursor);
        }

        @Override
        public void onLoaderReset(Loader<Cursor> loader) {
            resourceCursorAdapter.swapCursor(null);
        }
    });
    trackDataHub = TrackDataHub.newInstance(this);
    if (savedInstanceState != null) {
        startGps = savedInstanceState.getBoolean(START_GPS_KEY);
    }
    showStartupDialogs();
}

From source file:edu.cens.loci.provider.LociDbUtils.java

/**
 * Returns an average position fix//from  w ww .j av a  2s . c o  m
 * @param start beginning time
 * @param end ending time
 * @param accuracy filter position fixes with accuracy value higher than this value
 * @return average position within the provided time interval, filtered by accuracy
 */
public LociLocation getAveragePosition(long start, long end, int accuracy) {

    LociLocation placeLoc = null;

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

    ArrayList<LociLocation> track = new ArrayList<LociLocation>();

    MyLog.d(LociConfig.D.DB.UTILS, TAG,
            String.format("[DB] average position between %s-%s ==> #pos=%d (accuracy=%d)",
                    MyDateUtils.getTimeFormatLong(start), MyDateUtils.getTimeFormatLong(end), cursor.getCount(),
                    accuracy));

    if (cursor.moveToFirst()) {
        do {
            LociLocation loc = new LociLocation(LocationManager.GPS_PROVIDER);
            loc.setTime(cursor.getLong(cursor.getColumnIndex(Tracks.TIME)));
            loc.setLatitude(cursor.getDouble(cursor.getColumnIndex(Tracks.LATITUDE)));
            loc.setLongitude(cursor.getDouble(cursor.getColumnIndex(Tracks.LONGITUDE)));
            loc.setAltitude(cursor.getDouble(cursor.getColumnIndex(Tracks.ALTITUDE)));
            loc.setSpeed(cursor.getFloat(cursor.getColumnIndex(Tracks.SPEED)));
            loc.setBearing(cursor.getFloat(cursor.getColumnIndex(Tracks.BEARING)));
            loc.setAccuracy(cursor.getFloat(cursor.getColumnIndex(Tracks.ACCURACY)));
            track.add(loc);
        } while (cursor.moveToNext());

        placeLoc = LociLocation.averageLocation(track, accuracy);
    }
    cursor.close();
    return placeLoc;

}

From source file:com.urs.triptracks.TripUploader.java

private String getCoordsJSON(long tripId) throws JSONException {
    JSONObject coord = new JSONObject();
    //HS-SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//use new SimpleDateFormat(String template, Locale locale) with for example Locale.US for ASCII dates

    mDb.openReadOnly();//from   w  w w .  j ava 2 s.  c o  m
    Cursor tripCoordsCursor = mDb.fetchAllCoordsForTrip(tripId);

    // Build the map between JSON fieldname and phone db fieldname:
    Map<String, Integer> fieldMap = new HashMap<String, Integer>();
    fieldMap.put(TRIP_COORDS_TIME, tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_TIME));
    fieldMap.put(TRIP_COORDS_LAT, tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_LAT));
    fieldMap.put(TRIP_COORDS_LON, tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_LGT));
    fieldMap.put(TRIP_COORDS_ALT, tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_ALT));
    fieldMap.put(TRIP_COORDS_SPEED, tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_SPEED));
    fieldMap.put(TRIP_COORDS_HACCURACY, tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_ACC));
    fieldMap.put(TRIP_COORDS_VACCURACY, tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_ACC));

    // Build JSON objects for each coordinate:
    JSONArray tripCoords = new JSONArray();
    String str = new String();

    JSONArray key = new JSONArray();
    while (!tripCoordsCursor.isAfterLast()) {
        //
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
        coord.put(TRIP_COORDS_TIME, df.format(tripCoordsCursor.getDouble(fieldMap.get(TRIP_COORDS_TIME))));
        coord.put(TRIP_COORDS_LAT, tripCoordsCursor.getDouble(fieldMap.get(TRIP_COORDS_LAT)) / 1E6);
        coord.put(TRIP_COORDS_LON, tripCoordsCursor.getDouble(fieldMap.get(TRIP_COORDS_LON)) / 1E6);
        coord.put(TRIP_COORDS_ALT, tripCoordsCursor.getInt(fieldMap.get(TRIP_COORDS_ALT)));
        coord.put(TRIP_COORDS_SPEED, tripCoordsCursor.getDouble(fieldMap.get(TRIP_COORDS_SPEED)));
        coord.put(TRIP_COORDS_HACCURACY, tripCoordsCursor.getDouble(fieldMap.get(TRIP_COORDS_HACCURACY)));
        coord.put(TRIP_COORDS_VACCURACY, tripCoordsCursor.getDouble(fieldMap.get(TRIP_COORDS_VACCURACY)));

        //tripCoords.put(coord.getString("rec"), coord);
        //JSONObject jo=new JSONObject();
        /*key.put("coord");
        // jo.put("coord", coord);
        tripCoords.put(coord);
        tripCoordsCursor.moveToNext();
        Log.v("coordsoutputtosee1:", tripCoords.toString());
        tripCoords.put(coord);
        Log.v("coordsoutputtosee2:", tripCoords.toString());*/
        str = str.concat("{\"coord\":");
        str = str.concat(coord.toString());
        str = str.concat("}");
        tripCoordsCursor.moveToNext();
        if (!tripCoordsCursor.isAfterLast()) {
            str = str.concat(",");
        }
    }
    tripCoordsCursor.close();
    mDb.close();
    return str;
}