Example usage for android.database Cursor getLong

List of usage examples for android.database Cursor getLong

Introduction

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

Prototype

long getLong(int columnIndex);

Source Link

Document

Returns the value of the requested column as a long.

Usage

From source file:com.udacity.sunshine.FetchWeatherTask.java

private long addLocation(String locationSetting, String cityName, double lat, double lon) {

    Log.v(LOG_TAG, "inserting " + cityName + ", with coord: " + lat + ", " + lon);

    String[] projection = { LocationEntry._ID }; // whichever column doesn't matter, but don't need to return all
    String[] selectionArgs = { locationSetting };
    String selection = LocationEntry.COLUMN_LOCATION_SETTING + " = ? ";
    // Check to see if location setting exists in db
    Cursor cursor = mContext.getContentResolver().query(LocationEntry.CONTENT_URI, projection, selection,
            selectionArgs, null);//  www .jav  a 2 s .com

    long locationRowId;

    if (cursor.moveToFirst()) {
        Log.v(LOG_TAG, "Found it in the database!");
        int locationIdIndex = cursor.getColumnIndex(LocationEntry._ID);
        locationRowId = cursor.getLong(locationIdIndex);
    } else {
        Log.v(LOG_TAG, "Didn't find it in the database, inserting now!");

        ContentValues locationValues = new ContentValues();
        locationValues.put(LocationEntry.COLUMN_LOCATION_SETTING, locationSetting);
        locationValues.put(LocationEntry.COLUMN_CITY_NAME, cityName);
        locationValues.put(LocationEntry.COLUMN_COORD_LAT, lat);
        locationValues.put(LocationEntry.COLUMN_COORD_LONG, lon);

        Uri locationUri = mContext.getContentResolver().insert(LocationEntry.CONTENT_URI, locationValues);
        locationRowId = ContentUris.parseId(locationUri);
    }
    cursor.close();

    return locationRowId;
}

From source file:com.example.spatidar.sunshine.FetchWeatherTask.java

/**
 * Helper method to handle insertion of a new location in the weather database.
 *
 * @param locationSetting The location string used to request updates from the server.
 * @param cityName A human-readable city name, e.g "Mountain View"
 * @param lat the latitude of the city//from   w  w  w  . j  a  v  a 2s .c om
 * @param lon the longitude of the city
 * @return the row ID of the added location.
 */
long addLocation(String locationSetting, String cityName, double lat, double lon) {
    long locationId = -1;

    // Query if locationSetting entry exists in the table
    Cursor cur = mContext.getContentResolver().query(WeatherContract.LocationEntry.CONTENT_URI, null,
            WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + "= ?", new String[] { locationSetting },
            null);

    if (cur.moveToFirst()) {
        int idx = cur.getColumnIndex(WeatherContract.LocationEntry._ID);
        locationId = cur.getLong(idx);
    } else {
        // Insert
        ContentValues values = new ContentValues();
        values.put(WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING, locationSetting);
        values.put(WeatherContract.LocationEntry.COLUMN_CITY_NAME, cityName);
        values.put(WeatherContract.LocationEntry.COLUMN_COORD_LAT, lat);
        values.put(WeatherContract.LocationEntry.COLUMN_COORD_LONG, lon);

        Uri uri = mContext.getContentResolver().insert(WeatherContract.LocationEntry.CONTENT_URI, values);

        locationId = ContentUris.parseId(uri);
    }
    cur.close();

    return locationId;
}

From source file:idea.ruan.oksun.FetchWeatherTask.java

/**
 * Helper method to handle insertion of a new location in the weather database.
 *
 * @param locationSetting The location string used to request updates from the server.
 * @param cityName A human-readable city name, e.g "Mountain View"
 * @param lat the latitude of the city/*from   w w w  . j av a  2s  .  c om*/
 * @param lon the longitude of the city
 * @return the row ID of the added location.
 */
long addLocation(String locationSetting, String cityName, double lat, double lon) {

    ContentResolver contentResolver = mContext.getContentResolver();

    Uri locationTableUri = WeatherContract.LocationEntry.CONTENT_URI;

    long locationId;
    Cursor c = contentResolver.query(locationTableUri, new String[] { WeatherContract.LocationEntry._ID },
            WeatherContract.LocationEntry.COLUMN_CITY_NAME + " = ?", new String[] { cityName }, null);
    if (c.moveToFirst()) {

        int i = c.getColumnIndex(WeatherContract.LocationEntry._ID);
        locationId = c.getLong(i);

    } else {

        ContentValues cv = new ContentValues();

        cv.put(WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING, locationSetting);
        cv.put(WeatherContract.LocationEntry.COLUMN_CITY_NAME, cityName);
        cv.put(WeatherContract.LocationEntry.COLUMN_COORD_LAT, lat);
        cv.put(WeatherContract.LocationEntry.COLUMN_COORD_LONG, lon);

        locationId = ContentUris.parseId(contentResolver.insert(locationTableUri, cv));

    }

    c.close();

    return locationId;
}

From source file:com.girnarsoft.android.shunshine.FetchWeatherTask.java

/**
 * Helper method to handle insertion of a new location in the weather database.
 *
 * @param locationSetting The location string used to request updates from the server.
 * @param cityName A human-readable city name, e.g "Mountain View"
 * @param lat the latitude of the city/*from w  ww.ja  v  a 2  s.  com*/
 * @param lon the longitude of the city
 * @return the row ID of the added location.
 */
public long addLocation(String locationSetting, String cityName, double lat, double lon) {

    Cursor cursor = mContext.getContentResolver().query(WeatherContract.LocationEntry.CONTENT_URI, null,
            WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + "=?", new String[] { locationSetting },
            null);

    long location = 0;

    if (cursor.getCount() > 0) {
        cursor.moveToFirst();
        location = cursor.getLong(cursor.getColumnIndex(WeatherContract.LocationEntry._ID));
    } else {
        ContentValues values = new ContentValues();
        values.put(WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING, locationSetting);
        values.put(WeatherContract.LocationEntry.COLUMN_CITY_NAME, cityName);
        values.put(WeatherContract.LocationEntry.COLUMN_COORD_LAT, lat);
        values.put(WeatherContract.LocationEntry.COLUMN_COORD_LONG, lon);

        Uri uri = mContext.getContentResolver().insert(WeatherContract.LocationEntry.CONTENT_URI, values);

        location = ContentUris.parseId(uri);
    }

    return location;
}

From source file:com.android.browser.BookmarksPageCallbacks.java

private void displayRemoveBookmarkDialog(BrowserBookmarksAdapter adapter, int position) {
    // Put up a dialog asking if the user really wants to
    // delete the bookmark
    Cursor cursor = adapter.getItem(position);
    long id = cursor.getLong(BookmarksLoader.COLUMN_INDEX_ID);
    String title = cursor.getString(BookmarksLoader.COLUMN_INDEX_TITLE);
    Context context = getActivity();
    BookmarkUtils.displayRemoveBookmarkDialog(id, title, context, null);
}

From source file:com.jaspersoft.android.jaspermobile.activities.profile.fragment.ServersFragment.java

@Override
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
    if (columnIndex == cursor.getColumnIndex(ServerProfilesTable._ID)) {
        ImageView imageView = (ImageView) view;
        if (mServerProfile == null) {
            imageView.setImageResource(R.drawable.ic_composed_server);
        } else {/* www  .j a  va2  s. c  o  m*/
            long entryId = cursor.getLong(cursor.getColumnIndex(ServerProfilesTable._ID));

            imageView.setImageResource((mServerProfileId == entryId) ? R.drawable.ic_composed_active_server
                    : R.drawable.ic_composed_server);
        }
        return true;
    }
    if (columnIndex == cursor.getColumnIndex(ServerProfilesTable.ALIAS)) {
        TextView textView = (TextView) view;
        String alias = cursor.getString(columnIndex);
        if (mServerProfile == null) {
            textView.setText(alias);
        } else {
            long entryId = cursor.getLong(cursor.getColumnIndex(ServerProfilesTable._ID));
            boolean isItemActive = (mServerProfileId == entryId);
            textView.setText(isItemActive ? getString(R.string.sp_active_item, alias) : alias);
        }
        return true;
    }
    return false;
}

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

@Override
protected Boolean doInBackground(Long... noteIds) {
    // First, send the note user asked for:
    Boolean result = true;//from www .jav  a 2s .c o  m
    if (noteIds.length != 0) {
        result = uploadOneNote(noteIds[0]);
    }

    // Then, automatically try and send previously-completed notes
    // that were not sent successfully.
    Vector<Long> unsentNotes = new Vector<Long>();

    mDb.openReadOnly();
    Cursor cur = mDb.fetchUnsentNotes();
    if (cur != null && cur.getCount() > 0) {
        // pd.setMessage("Sent. You have previously unsent notes; submitting those now.");
        while (!cur.isAfterLast()) {
            unsentNotes.add(Long.valueOf(cur.getLong(0)));
            cur.moveToNext();
        }
        cur.close();
    }
    mDb.close();

    for (Long note : unsentNotes) {
        result &= uploadOneNote(note);
    }
    return result;
}

From source file:at.bitfire.davdroid.resource.LocalGroup.java

/**
 * Lists all members of this group.//  w  ww  .  java2s .c  o m
 * @return list of all members' raw contact IDs
 * @throws ContactsStorageException on contact provider errors
 */
protected long[] getMembers() throws ContactsStorageException {
    assertID();
    List<Long> members = new LinkedList<>();
    try {
        @Cleanup
        Cursor cursor = addressBook.provider.query(
                addressBook.syncAdapterURI(ContactsContract.Data.CONTENT_URI),
                new String[] { Data.RAW_CONTACT_ID },
                GroupMembership.MIMETYPE + "=? AND " + GroupMembership.GROUP_ROW_ID + "=?",
                new String[] { GroupMembership.CONTENT_ITEM_TYPE, String.valueOf(id) }, null);
        while (cursor != null && cursor.moveToNext())
            members.add(cursor.getLong(0));
    } catch (RemoteException e) {
        throw new ContactsStorageException("Couldn't list group members", e);
    }
    return ArrayUtils.toPrimitive(members.toArray(new Long[members.size()]));
}

From source file:net.olejon.mdapp.BarcodeScannerActivity.java

@Override
public void handleResult(Result result) {
    mTools.showToast(getString(R.string.barcode_scanner_wait), 0);

    String barcode = result.getText();

    RequestQueue requestQueue = Volley.newRequestQueue(mContext);

    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
            getString(R.string.project_website_uri) + "api/1/barcode/?search=" + barcode,
            new Response.Listener<JSONObject>() {
                @Override/*from  www .j  a v a 2s . c om*/
                public void onResponse(JSONObject response) {
                    try {
                        String medicationName = response.getString("name");

                        if (medicationName.equals("")) {
                            mTools.showToast(getString(R.string.barcode_scanner_no_results), 1);

                            finish();
                        } else {
                            SQLiteDatabase sqLiteDatabase = new SlDataSQLiteHelper(mContext)
                                    .getReadableDatabase();

                            String[] queryColumns = { SlDataSQLiteHelper.MEDICATIONS_COLUMN_ID };
                            Cursor cursor = sqLiteDatabase.query(SlDataSQLiteHelper.TABLE_MEDICATIONS,
                                    queryColumns,
                                    SlDataSQLiteHelper.MEDICATIONS_COLUMN_NAME + " LIKE "
                                            + mTools.sqe("%" + medicationName + "%") + " COLLATE NOCASE",
                                    null, null, null, null);

                            if (cursor.moveToFirst()) {
                                long id = cursor.getLong(
                                        cursor.getColumnIndexOrThrow(SlDataSQLiteHelper.MEDICATIONS_COLUMN_ID));

                                Intent intent = new Intent(mContext, MedicationActivity.class);

                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                                    if (mTools.getDefaultSharedPreferencesBoolean(
                                            "MEDICATION_MULTIPLE_DOCUMENTS"))
                                        intent.setFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK
                                                | Intent.FLAG_ACTIVITY_NEW_DOCUMENT);
                                }

                                intent.putExtra("id", id);
                                startActivity(intent);
                            }

                            cursor.close();
                            sqLiteDatabase.close();

                            finish();
                        }
                    } catch (Exception e) {
                        mTools.showToast(getString(R.string.barcode_scanner_no_results), 1);

                        Log.e("BarcodeScannerActivity", Log.getStackTraceString(e));

                        finish();
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.e("FelleskatalogenService", error.toString());
                }
            });

    jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

    requestQueue.add(jsonObjectRequest);
}

From source file:mobisocial.bento.anyshare.util.DBHelper.java

public long getLatestTimestamp(String feedName) {

    long tstamp = 0;
    String[] projection = { ItemObject.TIMESTAMP };
    String selection = "feedname = ?";
    String[] selectionArgs = { feedName };
    String tables = ItemObject.TABLE;
    String sortOrder = ItemObject.TIMESTAMP + " DESC";
    String limits = "0,1";

    Cursor c = getReadableDatabase().query(tables, projection, selection, selectionArgs, null, null, sortOrder,
            limits);// w  ww  .  j ava2s  . com
    if (c != null && c.moveToFirst()) {
        tstamp = c.getLong(0);
    }
    return tstamp;
}