Example usage for android.database Cursor getColumnIndex

List of usage examples for android.database Cursor getColumnIndex

Introduction

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

Prototype

int getColumnIndex(String columnName);

Source Link

Document

Returns the zero-based index for the given column name, or -1 if the column doesn't exist.

Usage

From source file:com.kwang.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/* w w w .  j  a v  a 2 s.  c o m*/
 * @param lon the longitude of the city
 * @return the row ID of the added location.
 */
private long addLocation(String locationSetting, String cityName, double lat, double lon) {

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

    // First, check if the location with this city name exists in the db
    Cursor cursor = mContext.getContentResolver().query(LocationEntry.CONTENT_URI,
            new String[] { LocationEntry._ID }, LocationEntry.COLUMN_LOCATION_SETTING + " = ?",
            new String[] { locationSetting }, null);

    if (cursor.moveToFirst()) {
        Log.v(LOG_TAG, "Found it in the database!");
        int locationIdIndex = cursor.getColumnIndex(LocationEntry._ID);
        return 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 locationInsertUri = mContext.getContentResolver().insert(LocationEntry.CONTENT_URI, locationValues);

        return ContentUris.parseId(locationInsertUri);
    }
}

From source file:com.danjarvis.documentcontract.DocumentContract.java

/**
 * Gets the contract details for the provided content URI.
 *
 * @return Contract serialized to a JSONObject
 *///w w w. j  av  a  2s  .co m
private void getContract(JSONObject args, CallbackContext callback) {
    try {
        Uri uri;
        Cursor cursor;
        JSONObject response = new JSONObject();

        uri = getUri(args);
        if (null == uri || !(uri.getScheme().equals(ContentResolver.SCHEME_CONTENT))) {
            callback.error(INVALID_URI_ERROR);
            return;
        }

        cursor = cordova.getActivity().getContentResolver().query(uri, getColumns(args), null, null, null);
        if (null != cursor && cursor.moveToFirst()) {
            for (String col : cursor.getColumnNames())
                response.put(col, cursor.getString(cursor.getColumnIndex(col)));
        }
        cursor.close();
        callback.success(response);
    } catch (JSONException je) {
        callback.error(je.getMessage());
    }
}

From source file:com.example.asaldanha.sunshine.app.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  a2  s . c  o m
 * @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) {

    long locationID;

    // Students: First, check if the location with this city name exists in the db
    // If it exists, return the current ID
    // Otherwise, insert it using the content resolver and the base URI

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

    if (locationCursor.moveToFirst()) {
        int locationIndex = locationCursor.getColumnIndex(WeatherContract.LocationEntry._ID);
        locationID = locationCursor.getLong(locationIndex);
    } else {

        //Create a new set of content values
        ContentValues locationValues = new ContentValues();

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

        Uri insertURI = mContext.getContentResolver().insert(WeatherContract.LocationEntry.CONTENT_URI,
                locationValues);
        locationID = ContentUris.parseId(insertURI);
    }
    return locationID;
}

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

@SuppressLint("SimpleDateFormat")
private Vector<String> getTripData(long tripId) {
    Vector<String> tripData = new Vector<String>();
    mDb.openReadOnly();/*from   w  ww  . j  a v a2s  .co  m*/
    Cursor tripCursor = mDb.fetchTrip(tripId);

    String note = tripCursor.getString(tripCursor.getColumnIndex(DbAdapter.K_TRIP_NOTE));
    String purpose = tripCursor.getString(tripCursor.getColumnIndex(DbAdapter.K_TRIP_PURP));
    Double startTime = tripCursor.getDouble(tripCursor.getColumnIndex(DbAdapter.K_TRIP_START));
    Double endTime = tripCursor.getDouble(tripCursor.getColumnIndex(DbAdapter.K_TRIP_END));
    tripCursor.close();
    mDb.close();

    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    tripData.add(note);
    tripData.add(purpose);
    tripData.add(df.format(startTime));
    tripData.add(df.format(endTime));

    return tripData;
}

From source file:ch.ethz.twimight.net.tds.TDSRequestMessage.java

/**
 * creates JSONObject to push Statistics to the TDS
 * /*from w  ww  .  j a  va 2  s  .  c o  m*/
 * @param
 * @return JSON Object
 * @throws JSONException
 */
public void createStatisticObject(Cursor stats, long follCount) throws JSONException {

    if (stats != null) {
        statisticObject = new JSONObject();
        JSONArray statisticArray = new JSONArray();

        while (!stats.isAfterLast()) {

            JSONObject row = new JSONObject();
            row.put("latitude", Double
                    .toString(stats.getDouble(stats.getColumnIndex(StatisticsDBHelper.KEY_LOCATION_LAT))));
            row.put("longitude", Double
                    .toString(stats.getDouble(stats.getColumnIndex(StatisticsDBHelper.KEY_LOCATION_LNG))));
            row.put("accuracy", Integer
                    .toString(stats.getInt(stats.getColumnIndex(StatisticsDBHelper.KEY_LOCATION_ACCURACY))));
            row.put("provider",
                    stats.getString(stats.getColumnIndex(StatisticsDBHelper.KEY_LOCATION_PROVIDER)));
            row.put("timestamp",
                    Long.toString(stats.getLong(stats.getColumnIndex(StatisticsDBHelper.KEY_TIMESTAMP))));
            row.put("network", stats.getString(stats.getColumnIndex(StatisticsDBHelper.KEY_NETWORK)));
            row.put("event", stats.getString(stats.getColumnIndex(StatisticsDBHelper.KEY_EVENT)));
            row.put("link", stats.getString(stats.getColumnIndex(StatisticsDBHelper.KEY_LINK)));
            row.put("isDisaster",
                    Integer.toString(stats.getInt(stats.getColumnIndex(StatisticsDBHelper.KEY_ISDISASTER))));
            row.put("followers_count", follCount);
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
            row.put("dis_mode_used",
                    Preferences.getBoolean(context, R.string.pref_key_disastermode_has_been_used, false));

            statisticArray.put(row);
            stats.moveToNext();
        }
        stats.close();

        statisticObject.put("content", statisticArray);

    }
}

From source file:com.nicolacimmino.expensestracker.tracker.data_sync.ExpenseDataSyncAdapter.java

public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider,
        SyncResult syncResult) {/* www.  j av  a2  s.  co m*/

    // Get expenses that are not yet synced with the server.
    Cursor expenses = getContext().getContentResolver().query(
            ExpensesDataContentProvider.Contract.Expense.CONTENT_URI,
            ExpensesDataContentProvider.Contract.Expense.COLUMN_NAME_ALL,
            ExpensesDataContentProvider.Contract.Expense.COLUMN_NAME_SYNC + "=?", new String[] { "0" }, null);

    while (expenses.moveToNext()) {
        HttpURLConnection connection = null;
        try {
            JSONObject expense = new JSONObject();
            expense.put(ExpensesApiContract.Expense.NOTES, expenses.getString(expenses
                    .getColumnIndex(ExpensesDataContentProvider.Contract.Expense.COLUMN_NAME_DESCRIPTION)));
            expense.put(ExpensesApiContract.Expense.CURRENCY, expenses.getString(expenses
                    .getColumnIndex(ExpensesDataContentProvider.Contract.Expense.COLUMN_NAME_CURRENCY)));
            expense.put(ExpensesApiContract.Expense.AMOUNT, expenses.getString(
                    expenses.getColumnIndex(ExpensesDataContentProvider.Contract.Expense.COLUMN_NAME_AMOUNT)));
            expense.put(ExpensesApiContract.Expense.DESTINATION, expenses.getString(expenses
                    .getColumnIndex(ExpensesDataContentProvider.Contract.Expense.COLUMN_NAME_DESTINATION)));
            expense.put(ExpensesApiContract.Expense.SOURCE, expenses.getString(
                    expenses.getColumnIndex(ExpensesDataContentProvider.Contract.Expense.COLUMN_NAME_SOURCE)));
            expense.put(ExpensesApiContract.Expense.TIMESTAMP, expenses.getString(expenses
                    .getColumnIndex(ExpensesDataContentProvider.Contract.Expense.COLUMN_NAME_TIMESTAMP)));
            expense.put(ExpensesApiContract.Expense.REPORTER_GCM_REG_ID, GcmRegistration.getRegistration_id());

            ExpensesApiNewExpenseRequest request = new ExpensesApiNewExpenseRequest(expense);
            if (request.performRequest()) {
                syncResult.stats.numEntries++;
                ContentValues values = new ContentValues();
                values.put(ExpensesDataContentProvider.Contract.Expense.COLUMN_NAME_SYNC, "1");
                getContext().getContentResolver().update(
                        ExpensesDataContentProvider.Contract.Expense.CONTENT_URI, values,
                        ExpensesDataContentProvider.Contract.Expense.COLUMN_NAME_ID + "=?",
                        new String[] { expenses.getString(expenses.getColumnIndex(
                                ExpensesDataContentProvider.Contract.Expense.COLUMN_NAME_ID)) });
            } else {
                syncResult.stats.numIoExceptions++;
            }
        } catch (JSONException e) {
            Log.e(TAG, "Error building json doc: " + e.toString());
            syncResult.stats.numIoExceptions++;
            return;
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }
    expenses.close();

    fetchExpensesFromServer();

    Log.i(TAG, "Sync done");
}

From source file:com.example.android.miniweather.app.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  www  .j ava 2s .c  o m*/
 * @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) {
    // Students: First, check if the location with this city name exists in the db
    // If it exists, return the current ID
    // Otherwise, insert it using the content resolver and the base URI

    ContentResolver contentResolver = mContext.getContentResolver();
    Cursor cursor;
    long locationID;

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

    if (cursor.moveToFirst()) {
        int locationIDIndex = cursor.getColumnIndex(WeatherContract.LocationEntry._ID);
        locationID = cursor.getLong(locationIDIndex);
    } else {
        ContentValues newLocation = new ContentValues();
        Uri insertedUri;

        newLocation.put(WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING, locationSetting);
        newLocation.put(WeatherContract.LocationEntry.COLUMN_CITY_NAME, cityName);
        newLocation.put(WeatherContract.LocationEntry.COLUMN_COORD_LAT, lat);
        newLocation.put(WeatherContract.LocationEntry.COLUMN_COORD_LONG, lon);
        insertedUri = contentResolver.insert(WeatherContract.LocationEntry.CONTENT_URI, newLocation);

        locationID = ContentUris.parseId(insertedUri);

    }

    cursor.close();
    return locationID;
}

From source file:com.iyedb.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
 * @param lon             the longitude of the city
 * @return the row ID of the added location.
 *//*  w  ww.jav a 2 s .  c o  m*/
private long insertLocationInDatabase(String locationSetting, String cityName, double lat, double lon) {

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

    // First, check if the location with this city name exists in the db
    Cursor cursor = mContext.getContentResolver().query(LocationEntry.CONTENT_URI,
            new String[] { LocationEntry._ID }, LocationEntry.COLUMN_LOCATION_SETTING + " = ?",
            new String[] { locationSetting }, null);

    if (cursor.moveToFirst()) {
        Log.v(LOG_TAG, "Found it in the database!");
        int locationIdIndex = cursor.getColumnIndex(LocationEntry._ID);
        return 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 locationInsertUri = mContext.getContentResolver().insert(LocationEntry.CONTENT_URI, locationValues);

        return ContentUris.parseId(locationInsertUri);
    }
}

From source file:com.example.len.sunshinelessons1.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  . j a  v  a2  s .  co m
 * @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;

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

    if (locationCursor.moveToFirst()) {
        int locationIdIndex = locationCursor.getColumnIndex(WeatherContract.LocationEntry._ID);
        locationId = locationCursor.getLong(locationIdIndex);
    } else {
        // Now that the content provider is set up, inserting rows of data is pretty simple.
        // First create a ContentValues object to hold the data you want to insert.
        ContentValues locationValues = new ContentValues();

        // Then add the data, along with the corresponding name of the data type,
        // so the content provider knows what kind of value is being inserted.
        locationValues.put(WeatherContract.LocationEntry.COLUMN_CITY_NAME, cityName);
        locationValues.put(WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING, locationSetting);
        locationValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LAT, lat);
        locationValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LONG, lon);

        // Finally, insert location data into the database.
        Uri insertedUri = mContext.getContentResolver().insert(WeatherContract.LocationEntry.CONTENT_URI,
                locationValues);

        // The resulting URI contains the ID for the row.  Extract the locationId from the Uri.
        locationId = ContentUris.parseId(insertedUri);
    }

    locationCursor.close();
    // Wait, that worked?  Yes!
    return locationId;
}