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:utils.database.sqlite.data.AFieldData.java

/**
 * /*w  w  w  .  ja va  2s.  c o m*/
 * Create the object from cursor db.
 * 
 * @param t
 *            the table.
 * @param cursor
 */
public AFieldData(ITables t, Cursor cursor) {
    this.tab = t;
    IColumns[] values = t.getColumns();
    if (cursor != null) {
        for (IColumns c : values) {
            String name = ((Enum) c).name();
            if (c.getType().equals(ConstantsDB.INTEGER)) {

                integerValue.put(c, cursor.getInt(cursor.getColumnIndex(name)));

            } else if (c.getType().equals(ConstantsDB.TEXT)) {
                stringValue.put(c, cursor.getString(cursor.getColumnIndex(name)));
            }

            else if (c.getType().equals(ConstantsDB.REAL)) {
                doubleValue.put(c, cursor.getDouble(cursor.getColumnIndex(name)));
            }
        }
    }
}

From source file:com.ubuntuone.android.files.provider.MetaUtilities.java

public static ArrayList<U1Node> getPhotoNodesFromDirectory(String directoryResourcePath) {
    String[] projection = Nodes.getDefaultProjection();
    String selection = Nodes.NODE_PARENT_PATH + "=? AND " + Nodes.NODE_MIME + "=?";
    String[] selectionArgs = new String[] { directoryResourcePath, "image/jpeg" };

    Cursor c = sResolver.query(Nodes.CONTENT_URI, projection, selection, selectionArgs, null);

    ArrayList<U1Node> photoNodes = null;
    if (c != null) {
        photoNodes = new ArrayList<U1Node>();
        try {//from w  w  w.j  a  v  a  2  s .  c  o  m
            if (c.moveToFirst()) {
                do {
                    String resourcePath;
                    String key;
                    U1NodeKind kind;
                    Boolean isLive = true;
                    String path;
                    String parentPath;
                    String volumePath;
                    Date whenCreated;
                    Date whenChanged;
                    Long generation;
                    Long generationCreated;
                    String contentPath;

                    resourcePath = c.getString(c.getColumnIndex(Nodes.NODE_RESOURCE_PATH));
                    key = c.getString(c.getColumnIndex(Nodes.NODE_KEY));
                    kind = U1NodeKind
                            .valueOf(c.getString(c.getColumnIndex(Nodes.NODE_KIND)).toUpperCase(Locale.US));
                    isLive = c.getInt(c.getColumnIndex(Nodes.NODE_IS_LIVE)) != 0;
                    path = c.getString(c.getColumnIndex(Nodes.NODE_PATH));
                    parentPath = c.getString(c.getColumnIndex(Nodes.NODE_PARENT_PATH));
                    volumePath = c.getString(c.getColumnIndex(Nodes.NODE_VOLUME_PATH));
                    whenCreated = new Date(c.getLong(c.getColumnIndex(Nodes.NODE_WHEN_CREATED)));
                    whenChanged = new Date(c.getLong(c.getColumnIndex(Nodes.NODE_WHEN_CHANGED)));
                    generation = c.getLong(c.getColumnIndex(Nodes.NODE_GENERATION));
                    generationCreated = c.getLong(c.getColumnIndex(Nodes.NODE_GENERATION_CREATED));
                    contentPath = c.getString(c.getColumnIndex(Nodes.NODE_CONTENT_PATH));

                    U1Node node = new U1Node(resourcePath, kind, isLive, path, parentPath, volumePath, key,
                            whenCreated, whenChanged, generation, generationCreated, contentPath);
                    photoNodes.add(node);
                } while (c.moveToNext());
            }
        } finally {
            c.close();
        }
    }
    return photoNodes;
}

From source file:edu.auburn.ppl.cyclecolumbus.TripUploader.java

/******************************************************************************************
 * Generates and uploads KCal, CO2 savings, Avg Savings from biking vs riding, and distance.
 ******************************************************************************************
 * @param cursor Uses this to access SQLite database
 ******************************************************************************************/
private void setKcalCo2Savings(Cursor cursor) {

    // Set co2/*from  w  w w .j  a  v  a 2  s  .  c  o  m*/
    Double CO2 = cursor.getFloat(cursor.getColumnIndex("distance")) * 0.0006212 * 0.93;
    DecimalFormat df = new DecimalFormat("0.#");
    co2 = df.format(CO2);

    // Set kcal
    Double calory = cursor.getFloat(cursor.getColumnIndex("distance")) * 0.0006212 * 49 - 1.69;
    if (calory <= 0) {
        kcal = "0";
    } else {
        kcal = df.format(calory);
    }

    // Set Average Savings
    float savings = cursor.getFloat(cursor.getColumnIndex("distance")) * 0.0006212f;
    Double dSavings = savings * .592;
    Log.d("KENNY", "Distance: " + cursor.getFloat(cursor.getColumnIndex("distance")));
    DecimalFormat df2 = new DecimalFormat("$#,###,##0.00");
    avgCost = df2.format(dSavings);

    // Set Distance
    float dist = cursor.getFloat(cursor.getColumnIndex("distance")) * 0.0006212f;
    DecimalFormat dfDistance = new DecimalFormat("0.0#");
    distance = String.valueOf(dfDistance.format(dist));
}

From source file:com.blandware.android.atleap.test.RobospiceTestCase.java

public void test_book_by_id() throws Exception {
    Book.BooksResult result = makeRobospiceRequest(BOOKS_FILENAME, new BooksAuthorsRobospiceRequest());

    Cursor cursor = getContext().getContentResolver().query(
            TestContract.Book.CONTENT_URI.buildUpon().appendPath("1382763").build(), //uri
            null, //projection
            null, //selection
            null, //selectionArgs
            null //sort order
    );//from  w ww.ja  v a2  s .  c o  m

    assertTrue(cursor != null);
    assertTrue(cursor.getCount() == 1);

    cursor.moveToFirst();

    assertTrue(cursor.getString(cursor.getColumnIndex(TestContract.Book.TITLE)) != null);
    assertTrue(cursor.getString(cursor.getColumnIndex(TestContract.Book.TITLE)).equals("Super book"));
}

From source file:com.nextgis.maplibui.formcontrol.Checkbox.java

@Override
public void init(JSONObject element, List<Field> fields, Bundle savedState, Cursor featureCursor,
        SharedPreferences preferences) throws JSONException {

    JSONObject attributes = element.getJSONObject(JSON_ATTRIBUTES_KEY);
    mFieldName = attributes.getString(JSON_FIELD_NAME_KEY);
    mIsShowLast = ControlHelper.isSaveLastValue(attributes);

    Boolean value = null;/*  www. j  a v  a  2s .  co m*/
    if (ControlHelper.hasKey(savedState, mFieldName))
        value = savedState.getBoolean(ControlHelper.getSavedStateKey(mFieldName));
    else if (null != featureCursor) {
        int column = featureCursor.getColumnIndex(mFieldName);

        if (column >= 0)
            value = featureCursor.getInt(column) != 0;
    } else {
        value = attributes.getBoolean(JSON_INIT_VALUE_KEY);

        if (mIsShowLast)
            value = preferences.getBoolean(mFieldName, value);
    }

    if (value == null)
        value = false;

    setChecked(value);
    setText(attributes.getString(JSON_TEXT_KEY));
    setEnabled(ControlHelper.isEnabled(fields, mFieldName));
}

From source file:com.barcamppenang2014.tabfragment.ProfileFragment.java

License:asdf

public String check() {
    // Log.d("yc", "at check()");
    String isCreated = "false";

    MyDatabase database = new MyDatabase(getActivity());
    SQLiteDatabase sqliteDatabase = database.getReadableDatabase();
    Log.d("debug", "database.getReadableDatabase()");
    String sql = "SELECT ISPFOFILECREATED FROM USERPROFILE;";
    Cursor retrieved = sqliteDatabase.rawQuery(sql, null);
    Log.d("debug", "rawQuery");

    if (retrieved.moveToFirst()) {
        isCreated = retrieved.getString(retrieved.getColumnIndex("ISPFOFILECREATED"));
    }/*from  w  w  w .  j a va 2  s  .c o m*/

    Log.d("debug", "checking isProfileCreated " + isCreated);
    retrieved.close();
    database.close();
    sqliteDatabase.close();
    return isCreated;
}

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

private JSONObject getNoteJSON(long noteId) throws JSONException {
    try {/*  w  ww .ja  va2s  .  c o  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:li.barter.fragments.EditProfileFragment.java

@Override
public void onQueryComplete(final int token, final Object cookie, final Cursor cursor) {
    if (token == QueryTokens.LOAD_LOCATION_FROM_PROFILE_EDIT_PAGE) {

        if (cursor.moveToFirst()) {
            final String mPrefPlaceName = cursor.getString(cursor.getColumnIndex(DatabaseColumns.NAME));
            final String mPrefPlaceAddress = cursor.getString(cursor.getColumnIndex(DatabaseColumns.ADDRESS));

            if (!TextUtils.isEmpty(mPrefPlaceName)) {
                final String preferredLocation = getString(R.string.format_address_underline, mPrefPlaceName,
                        (TextUtils.isEmpty(mPrefPlaceAddress) ? "" : mPrefPlaceAddress));
                mPreferredLocationTextView.setText(preferredLocation);
            }//from w ww . j  a  v  a  2s.  com

        }

        cursor.close();

    }
}

From source file:de.yaacc.upnp.server.YaaccHttpService.java

/**
 * Lookup content in the mediastore/* w ww.j a v  a2 s  .c  om*/
 *
 * @param albumId the id of the album
 * @return the content description
 */
private ContentHolder lookupAlbumArt(String albumId) {

    ContentHolder result = new ContentHolder(MimeType.valueOf("image/png"), getDefaultIcon());
    if (albumId == null) {
        return null;
    }
    Log.d(getClass().getName(), "System media store lookup album: " + albumId);
    String[] projection = { MediaStore.Audio.Albums._ID,
            // FIXME what is the right mime type?
            // MediaStore.Audio.Albums.MIME_TYPE,
            MediaStore.Audio.Albums.ALBUM_ART };
    String selection = MediaStore.Audio.Albums._ID + "=?";
    String[] selectionArgs = { albumId };
    Cursor cursor = getContext().getContentResolver().query(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
            projection, selection, selectionArgs, null);

    if (cursor != null) {
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            String dataUri = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ART));

            // String mimeTypeStr = null;
            // FIXME mime type resolving cursor
            // .getString(cursor
            // .getColumnIndex(MediaStore.Files.FileColumns.MIME_TYPE));

            MimeType mimeType = MimeType.valueOf("image/png");
            // if (mimeTypeStr != null) {
            // mimeType = MimeType.valueOf(mimeTypeStr);
            // }
            if (dataUri != null) {
                Log.d(getClass().getName(), "Content found: " + mimeType + " Uri: " + dataUri);
                result = new ContentHolder(mimeType, dataUri);
            }
            cursor.moveToNext();
        }
    } else {
        Log.d(getClass().getName(), "System media store is empty.");
    }
    cursor.close();
    return result;
}

From source file:com.josenaves.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 ww  w .ja va2s. com*/
 * @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) {

    // First, check if the location with this city name exists in the db
    Cursor cursor = mContext.getContentResolver().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);
        return cursor.getLong(locationIdIndex);
    } else {
        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_LAT, lat);
        locationValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LONG, lon);

        Uri locationInsertUri = mContext.getContentResolver().insert(WeatherContract.LocationEntry.CONTENT_URI,
                locationValues);

        return ContentUris.parseId(locationInsertUri);
    }
}