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:me.vancexu.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   ww w.  ja va  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) {

    long rowId;

    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);
        rowId = cursor.getLong(locationIdIndex);
        cursor.close();
        return rowId;
    } else {
        Log.v(LOG_TAG, "Didn't find it in the database, inserting now!");
        cursor.close();
        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.prey.json.actions.ContactsList.java

@TargetApi(Build.VERSION_CODES.ECLAIR)
public HttpDataService run(Context ctx, List<ActionResult> lista, JSONObject parameters) {
    HttpDataService data = new HttpDataService("contacts_list");
    HashMap<String, String> parametersMap = new HashMap<String, String>();
    Cursor cursor = null;
    try {//www. ja  v  a  2 s.  co  m
        final String[] projection = null;
        final String selection = null;
        final String[] selectionArgs = null;
        final String sortOrder = null;
        Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
        cursor = ctx.getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
        int i = 0;
        if (cursor != null) {
            while (cursor.moveToNext()) {
                String phone = "";
                String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                try {
                    phone = cursor
                            .getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                } catch (Exception e) {

                }
                if (!"".equals(phone)) {
                    parametersMap.put(i + "][phone", phone);
                    parametersMap.put(i + "][name", name);
                    i++;
                }

            }
        }
    } catch (Exception ex) {
        PreyLogger.e("Error:" + ex.getMessage(), ex);
        PreyWebServices.getInstance().sendNotifyActionResultPreyHttp(ctx,
                UtilJson.makeMapParam("get", "contacts_list", "failed", ex.getMessage()));
    } finally {
        cursor.close();
    }
    data.setList(true);
    data.addDataListAll(parametersMap);
    return data;
}

From source file:com.google.zxing.client.android.history.HistoryManager.java

public JSONArray listarTodosQr() {
    JSONArray listQr = new JSONArray();
    SQLiteOpenHelper helper = new DBHelper(activity);
    SQLiteDatabase db = null;/*ww w  .j a  v  a 2s.  com*/
    db = helper.getWritableDatabase();
    Cursor c = db.rawQuery(
            "SELECT " + DBHelper.TEXT_COL + ", " + DBHelper.TIMESTAMP_COL + " FROM " + DBHelper.TABLE_NAME,
            null);
    if (c != null) {
        c.moveToFirst();
        do {
            String data = c.getString(c.getColumnIndex(DBHelper.TIMESTAMP_COL));
            String incri = c.getString(c.getColumnIndex(DBHelper.TEXT_COL));
            JSONObject inscritos = new JSONObject();
            try {
                inscritos.put("id_inscrito", incri.toString());
                inscritos.put("data_credenciado", data.toString());
                listQr.put(inscritos);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } while (c.moveToNext());
    }
    c.close();
    return listQr;
}

From source file:com.example.riteden.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/* w w  w  .j  ava2  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) {
    // Students: First, check if the location with this city name exists in the db
    //WeatherProvider.query()
    Cursor cur = mContext.getContentResolver().query(WeatherContract.LocationEntry.CONTENT_URI,
            new String[] { WeatherContract.LocationEntry._ID },
            WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ?", new String[] { locationSetting },
            null);
    if (cur.moveToFirst()) {
        return cur.getLong(cur.getColumnIndex(WeatherContract.LocationEntry._ID));
    }

    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 return_rowID = mContext.getContentResolver().insert(WeatherContract.LocationEntry.CONTENT_URI, values);
    // If it exists, return the current ID
    // Otherwise, insert it using the content resolver and the base URI
    return ContentUris.parseId(return_rowID);
}

From source file:com.digipom.manteresting.android.fragment.NailFragment.java

private boolean handleMenuItemSelected(int listItemPosition, int itemId) {
    listItemPosition -= listView.getHeaderViewsCount();

    if (listItemPosition >= 0 && listItemPosition < nailAdapter.getCount()) {
        switch (itemId) {
        case R.id.share:
            try {
                final Cursor cursor = (Cursor) nailAdapter.getItem(listItemPosition);

                if (cursor != null && !cursor.isClosed()) {
                    final int nailId = cursor.getInt(cursor.getColumnIndex(Nails.NAIL_ID));
                    final JSONObject nailJson = new JSONObject(
                            cursor.getString(cursor.getColumnIndex(Nails.NAIL_JSON)));

                    final Uri uri = MANTERESTING_SERVER.buildUpon().appendPath("nail")
                            .appendPath(String.valueOf(nailId)).build();
                    String description = nailJson.getString("description");

                    if (description.length() > 100) {
                        description = description.substring(0, 97) + '';
                    }//from   w w w. j av a2s. c o m

                    final String user = nailJson.getJSONObject("user").getString("username");
                    final String category = nailJson.getJSONObject("workbench").getJSONObject("category")
                            .getString("title");

                    final Intent shareIntent = new Intent(Intent.ACTION_SEND);
                    shareIntent.setType("text/plain");
                    shareIntent.putExtra(Intent.EXTRA_TEXT, description + ' ' + uri.toString());
                    shareIntent.putExtra(Intent.EXTRA_SUBJECT,
                            String.format(getResources().getString(R.string.shareSubject), user, category));
                    try {
                        startActivity(Intent.createChooser(shareIntent, getText(R.string.share)));
                    } catch (ActivityNotFoundException e) {
                        new AlertDialog.Builder(getActivity()).setMessage(R.string.noShareApp).show();
                    }
                }
            } catch (Exception e) {
                if (LoggerConfig.canLog(Log.WARN)) {
                    Log.w(TAG, "Could not share nail at position " + listItemPosition + " with id " + itemId);
                }
            }

            return true;
        default:
            return false;
        }
    } else {
        return false;
    }
}

From source file:org.noorganization.instalistsynch.controller.synch.impl.UnitSynch.java

@Override
public void indexLocal(int _groupId, Date _lastIndexTime) {
    String lastIndexTime = ISO8601Utils.format(_lastIndexTime, false, TimeZone.getTimeZone("GMT+0000"));
    Cursor changeLog = mLocalLogController.getLogsSince(lastIndexTime, eModelType.UNIT);

    while (changeLog.moveToNext()) {
        int actionId = changeLog.getInt(changeLog.getColumnIndex(LogInfo.COLUMN.ACTION));
        eActionType actionType = eActionType.getTypeById(actionId);

        String uuid = changeLog.getString(changeLog.getColumnIndex(LogInfo.COLUMN.ITEM_UUID));
        if (uuid.contentEquals("-"))
            continue;

        List<ModelMapping> existingMappings = mMappingController.get(
                ModelMapping.COLUMN.CLIENT_SIDE_UUID + " = ? AND " + ModelMapping.COLUMN.GROUP_ID + " = ?",
                new String[] { uuid, String.valueOf(_groupId) });
        ModelMapping existingMapping = (existingMappings.size() == 0 ? null : existingMappings.get(0));

        if (actionType == null) {
            Log.w(TAG, "Changelog contains entry without action.");
            continue;
        }/*from  w  w  w.  ja v a  2 s  .c o m*/

        switch (actionType) {
        case INSERT: {
            if (existingMapping == null) {
                ModelMapping newMapping = new ModelMapping(null, _groupId, null, uuid,
                        new Date(Constants.INITIAL_DATE), new Date(), false);
                mMappingController.insert(newMapping);
            }
            break;
        }
        case UPDATE: {
            if (existingMapping == null) {
                Log.e(TAG, "Changelog contains update, but mapping does not exist. " + "Ignoring.");
                continue;
            }
            try {
                Date clientDate = ISO8601Utils.parse(
                        changeLog.getString(changeLog.getColumnIndex(LogInfo.COLUMN.ACTION_DATE)),
                        new ParsePosition(0));
                existingMapping.setLastClientChange(clientDate);
                mMappingController.update(existingMapping);
            } catch (ParseException e) {
                Log.e(TAG, "Change log contains invalid date: " + e.getMessage());
                continue;
            }
            break;
        }
        case DELETE: {
            if (existingMapping == null) {
                Log.e(TAG, "Changelog contains deletion, but mapping does not exist. " + "Ignoring.");
                continue;
            }
            try {
                Date clientDate = ISO8601Utils.parse(
                        changeLog.getString(changeLog.getColumnIndex(LogInfo.COLUMN.ACTION_DATE)),
                        new ParsePosition(0));
                existingMapping.setLastClientChange(clientDate);
                existingMapping.setDeleted(true);
                mMappingController.update(existingMapping);
            } catch (ParseException e) {
                Log.e(TAG, "Change log contains invalid date: " + e.getMessage());
                continue;
            }
            break;
        }
        }
    }
    changeLog.close();
}

From source file:co.mwater.foregroundcameraplugin.ForegroundCameraLauncher.java

/**
 * Used to find out if we are in a situation where the Camera Intent adds to
 * images to the content store. If we are using a FILE_URI and the number of
 * images in the DB increases by 2 we have a duplicate, when using a
 * DATA_URL the number is 1./*from w  ww. j ava 2 s .c  o m*/
 */
private void checkForDuplicateImage() {
    int diff = 2;
    Cursor cursor = queryImgDB();
    int currentNumOfImages = cursor.getCount();

    // delete the duplicate file if the difference is 2 for file URI or 1
    // for Data URL
    if ((currentNumOfImages - numPics) == diff) {
        cursor.moveToLast();
        int id = Integer.valueOf(cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media._ID))) - 1;
        Uri uri = Uri.parse(MediaStore.Images.Media.EXTERNAL_CONTENT_URI + "/" + id);
        this.cordova.getActivity().getContentResolver().delete(uri, null, null);
    }
}

From source file:com.example.mihai.inforoute.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 .j av a 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) {
    long locationId;

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

    if (locationCursor.moveToFirst()) {
        int locationIdIndex = locationCursor.getColumnIndex(RouteContract.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(RouteContract.LocationEntry.COLUMN_CITY_NAME, cityName);
        locationValues.put(RouteContract.LocationEntry.COLUMN_LOCATION_SETTING, locationSetting);
        locationValues.put(RouteContract.LocationEntry.COLUMN_COORD_LAT, lat);
        locationValues.put(RouteContract.LocationEntry.COLUMN_COORD_LONG, lon);

        // Finally, insert location data into the database.
        Uri insertedUri = mContext.getContentResolver().insert(RouteContract.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();
    return locationId;
}

From source file:com.example.fcp.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.
 *///from   w w  w  . j  av a  2s.c o m
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
    Cursor weaCursor = mContext.getContentResolver().query(WeatherContract.LocationEntry.CONTENT_URI, null,
            WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + "= ?", new String[] { locationSetting },
            null);

    // If it exists, return the current ID
    if (weaCursor.moveToFirst()) {
        int locationIdIndex = weaCursor.getColumnIndex(WeatherContract.LocationEntry._ID);
        locationId = weaCursor.getLong(locationIdIndex);
    } else {
        // Otherwise, insert it using the content resolver and the base URI
        ContentValues locValues = new ContentValues();
        locValues.put(WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING, locationSetting);
        locValues.put(WeatherContract.LocationEntry.COLUMN_CITY_NAME, cityName);
        locValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LAT, lat);
        locValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LONG, lon);
        //long rowId = weaProvider.insert(WeatherContract.LocationEntry.CONTENT_URI,locValues);
        Uri retUri = mContext.getContentResolver().insert(WeatherContract.LocationEntry.CONTENT_URI, locValues);
        //locationId = Long.parseLong(retUri.getLastPathSegment());
        locationId = ContentUris.parseId(retUri);
    }
    return locationId;
}

From source file:com.yuntongxun.ecdemo.storage.IMessageSqlManager.java

/**
 * // w ww. j av  a2  s. co  m
 *
 * @return
 */
public static int qureyAllSessionUnreadCount() {
    int count = 0;
    String[] columnsList = { "sum(" + IThreadColumn.UNREAD_COUNT + ")" };
    Cursor cursor = null;
    try {
        cursor = getInstance().sqliteDB().query(DatabaseHelper.TABLES_NAME_IM_SESSION, columnsList, null, null,
                null, null, null);
        if (cursor != null && cursor.getCount() > 0) {
            if (cursor.moveToFirst()) {
                count = cursor.getInt(cursor.getColumnIndex("sum(" + IThreadColumn.UNREAD_COUNT + ")"));
            }
        }
    } catch (Exception e) {
        LogUtil.e(TAG + " " + e.toString());
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
    return count;
}