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:de.yaacc.upnp.server.YaaccHttpService.java

/**
 * Lookup content in the mediastore//from  w  ww.jav  a  2 s. co  m
 *
 * @param contentId the id of the content
 * @return the content description
 */
private ContentHolder lookupContent(String contentId) {
    ContentHolder result = null;
    if (contentId == null) {
        return null;
    }
    Log.d(getClass().getName(), "System media store lookup: " + contentId);
    String[] projection = { MediaStore.Files.FileColumns._ID, MediaStore.Files.FileColumns.MIME_TYPE,
            MediaStore.Files.FileColumns.DATA };
    String selection = MediaStore.Files.FileColumns._ID + "=?";
    String[] selectionArgs = { contentId };
    Cursor mFilesCursor = getContext().getContentResolver().query(MediaStore.Files.getContentUri("external"),
            projection, selection, selectionArgs, null);

    if (mFilesCursor != null) {
        mFilesCursor.moveToFirst();
        while (!mFilesCursor.isAfterLast()) {
            String dataUri = mFilesCursor
                    .getString(mFilesCursor.getColumnIndex(MediaStore.Files.FileColumns.DATA));

            String mimeTypeStr = mFilesCursor
                    .getString(mFilesCursor.getColumnIndex(MediaStore.Files.FileColumns.MIME_TYPE));
            MimeType mimeType = MimeType.valueOf("*/*");
            if (mimeTypeStr != null) {
                mimeType = MimeType.valueOf(mimeTypeStr);
            }
            Log.d(getClass().getName(), "Content found: " + mimeType + " Uri: " + dataUri);
            result = new ContentHolder(mimeType, dataUri);
            mFilesCursor.moveToNext();
        }
    } else {
        Log.d(getClass().getName(), "System media store is empty.");
    }
    mFilesCursor.close();
    return result;
}

From source file:com.example.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  w w . ja v  a 2 s . 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) {
    // 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
    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 columnIndex = locationCursor.getColumnIndex(WeatherContract.LocationEntry._ID);
        locationId = locationCursor.getLong(columnIndex);
    } 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 insertedUri = mContext.getContentResolver().insert(WeatherContract.LocationEntry.CONTENT_URI,
                values);

        // 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.aafr.alfonso.sunshine.app.service.SunshineService.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 2 s. co  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 locationId;

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

    // First, check if the location with this city name exists in the db
    Cursor locationCursor = this.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 = this.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);
    }

    // Always close our cursor
    if (null != locationCursor)
        locationCursor.close();

    // Wait, that worked?  Yes!
    return locationId;
}

From source file:com.esri.arcgisruntime.sample.editfeatureattachments.EditAttachmentActivity.java

/**
 * Upload the selected image from the gallery as an attachment to the selected feature
 *
 * @param requestCode RESULT_LOAD_IMAGE request code to identify the requesting activity
 * @param resultCode  activity result code
 * @param data        Uri of the selected image
 *//* ww  w . j  a v  a2 s .  c o  m*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
        Uri selectedImage = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };

        Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
        if (cursor != null && cursor.moveToFirst()) {
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();

            // covert file to bytes to pass to ArcGISFeature
            byte[] imageByte = new byte[0];
            try {
                File imageFile = new File(picturePath);
                imageByte = FileUtils.readFileToByteArray(imageFile);
            } catch (IOException e) {
                e.printStackTrace();
            }

            final String attachmentName = getApplication().getString(R.string.attachment) + "_"
                    + System.currentTimeMillis() + ".png";

            progressDialog.setTitle(getApplication().getString(R.string.apply_edit_message));
            progressDialog.setMessage(getApplication().getString(R.string.wait));

            progressDialog.show();

            ListenableFuture<Attachment> addResult = mSelectedArcGISFeature.addAttachmentAsync(imageByte,
                    "image/png", attachmentName);

            addResult.addDoneListener(new Runnable() {
                @Override
                public void run() {
                    final ListenableFuture<Void> tableResult = mServiceFeatureTable
                            .updateFeatureAsync(mSelectedArcGISFeature);
                    tableResult.addDoneListener(new Runnable() {
                        @Override
                        public void run() {
                            applyServerEdits();
                        }
                    });
                }
            });
        }
    }

}

From source file:com.polyvi.xface.extension.messaging.XMessagingExt.java

/**
 * ?message?//from   w  w w  . j a v a2  s.  c  o m
 */
private JSONObject getMessageFromCursor(Cursor cursor) throws JSONException {
    // ??
    String msgId = cursor.getString(cursor.getColumnIndex("_id"));
    String subject = cursor.getString(cursor.getColumnIndex("subject"));
    String smsBody = cursor.getString(cursor.getColumnIndex("body"));
    long date = cursor.getLong(cursor.getColumnIndex("date"));
    boolean isRead = cursor.getInt(cursor.getColumnIndex("read")) == 0 ? false : true;
    String destAddress = cursor.getString(cursor.getColumnIndex("address"));
    JSONObject message = new JSONObject();
    message.put("messageId", msgId);
    message.put("subject", subject);
    message.put("body", smsBody);
    message.put("destinationAddresses", destAddress);
    message.put("messageType", MESSAGE_TYPE_SMS);
    message.put("date", date);
    message.put("isRead", isRead);
    return message;
}

From source file:com.nonninz.robomodel.RoboManager.java

private long getLastId() throws InstanceNotFoundException {
    final SQLiteDatabase db = mDatabaseManager.openOrCreateDatabase(getDatabaseName());

    final String columns[] = new String[] { BaseColumns._ID };
    Cursor query;
    /*// w w  w. j  a va  2  s .c om
     * Try the query. If the Table doesn't exist, fix the DB and re-run the query.
     */
    try {
        query = db.query(getTableName(), columns, null, null, null, null, null);
    } catch (final SQLiteException e) {
        prepareTable(db);
        query = db.query(getTableName(), columns, null, null, null, null, null);
    }

    if (query.moveToLast()) {
        final int columnIndex = query.getColumnIndex(BaseColumns._ID);
        return query.getLong(columnIndex);
    } else {
        throw new InstanceNotFoundException("table " + getTableName() + " is empty");
    }
}

From source file:com.redhorse.quickstart.AppConfig.java

private void loadApps() {
    Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
    mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);

    mAllApps = getPackageManager().queryIntentActivities(mainIntent, 0);
    mApps = new ArrayList<ResolveInfo>();
    mApps2 = new ArrayList<ResolveInfo>();
    Cursor c = dbStart.getAllItems();
    Iterator it1 = mAllApps.iterator();
    while (it1.hasNext()) {
        boolean found = false;
        ResolveInfo info = (ResolveInfo) it1.next();
        if (c.moveToFirst()) {
            do {/*  www. j  a  va  2 s  .  co  m*/
                int idColumn = c.getColumnIndex(dbStart.KEY_ROWID);
                int pkgnameColumn = c.getColumnIndex(dbStart.KEY_PKGNAME);
                int appnameColumn = c.getColumnIndex(dbStart.KEY_APPNAME);
                int contentColumn = c.getColumnIndex(dbStart.KEY_CONTENT);
                if (c.getString(pkgnameColumn).equals(info.activityInfo.packageName)
                        && c.getString(appnameColumn).equalsIgnoreCase(info.activityInfo.name)) {
                    found = true;
                    break;
                }
            } while (c.moveToNext());
        }
        if (!found)
            if (!info.activityInfo.packageName.equalsIgnoreCase("com.redhorse.quickstart"))
                mApps.add(info);
    }
    if (c.moveToFirst()) {
        do {
            int idColumn = c.getColumnIndex(dbStart.KEY_ROWID);
            int pkgnameColumn = c.getColumnIndex(dbStart.KEY_PKGNAME);
            int appnameColumn = c.getColumnIndex(dbStart.KEY_APPNAME);
            int contentColumn = c.getColumnIndex(dbStart.KEY_CONTENT);
            it1 = mAllApps.iterator();
            boolean found = false;
            ResolveInfo info = null;
            while (it1.hasNext()) {
                info = (ResolveInfo) it1.next();
                if (c.getString(pkgnameColumn).equals(info.activityInfo.packageName)
                        && c.getString(appnameColumn).equalsIgnoreCase(info.activityInfo.name)) {
                    found = true;
                    break;
                }
            }
            if (found)
                if (!info.activityInfo.packageName.equalsIgnoreCase("com.redhorse.quickstart"))
                    mApps2.add(info);
        } while (c.moveToNext());
    }
    c.close();
}

From source file:app.com.example.android.sunshine.FetchWeatherTask.java

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
    long locationId;
    SQLiteDatabase db = new WeatherDbHelper(this.mContext).getWritableDatabase();
    Cursor locationCursor = mContext.getContentResolver().query(WeatherContract.LocationEntry.CONTENT_URI,
            new String[] { WeatherContract.LocationEntry._ID },
            WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " =? ", new String[] { locationSetting },
            null);//from   w w w . j  ava2  s  . co  m
    if (locationCursor.moveToFirst()) {
        int locationIndex = locationCursor.getColumnIndex(WeatherContract.LocationEntry._ID);
        locationId = locationCursor.getLong(locationIndex);
    } else {
        ContentValues contentValues = new ContentValues();
        contentValues.put(WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING, locationSetting);
        contentValues.put(WeatherContract.LocationEntry.COLUMN_CITY_NAME, cityName);
        contentValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LAT, lat);
        contentValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LONG, lon);
        Uri insertedUri = mContext.getContentResolver().insert(WeatherContract.LocationEntry.CONTENT_URI,
                contentValues);
        locationId = ContentUris.parseId(insertedUri);
    }
    locationCursor.close();
    return locationId;
}

From source file:com.example.conor.dotaapp.FetchMatchTask.java

/**
 * Helper method to handle insertion of a new location in the weather database.
 *
 * @param steamAccountId Steam account id of the player.
 * @param heroId id of the player's hero
 * @param playerSlot the position of the player on the team
 * @return the row ID of the added location.
 *//*  w  w  w. j  a  v a  2  s .c o  m*/
long addPlayer(String steamAccountId, int heroId, int playerSlot) {
    long steamId;

    // First, check if the location with this city name exists in the db
    Cursor playerCursor = mContext.getContentResolver().query(MatchContract.PlayerEntry.CONTENT_URI,
            new String[] { MatchContract.PlayerEntry._ID },
            MatchContract.PlayerEntry.COLUMN_ACCOUNT_ID + " = ?", new String[] { steamAccountId }, null);

    if (playerCursor.moveToFirst()) {
        int steamIdIndex = playerCursor.getColumnIndex(MatchContract.PlayerEntry._ID);
        steamId = playerCursor.getLong(steamIdIndex);
    } 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 playerValues = 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.
        playerValues.put(MatchContract.PlayerEntry.COLUMN_ACCOUNT_ID, steamAccountId);
        playerValues.put(MatchContract.PlayerEntry.COLUMN_HERO_ID, heroId);
        playerValues.put(MatchContract.PlayerEntry.COLUMN_P_SLOT, playerSlot);

        // Finally, insert location data into the database.
        Uri insertedUri = mContext.getContentResolver().insert(MatchContract.PlayerEntry.CONTENT_URI,
                playerValues);

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

    playerCursor.close();
    return steamId;
}

From source file:edu.gatech.ppl.cycleatlanta.TripUploader.java

private JSONObject getCoordsJSON(long tripId) throws JSONException {
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    mDb.openReadOnly();/*from   w  ww.  j a  v a2  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:
    JSONObject tripCoords = new JSONObject();
    while (!tripCoordsCursor.isAfterLast()) {
        JSONObject coord = new JSONObject();

        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.getDouble(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("r"), coord);
        tripCoordsCursor.moveToNext();
    }
    tripCoordsCursor.close();
    mDb.close();
    return tripCoords;
}