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.example.rafa.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// w w w.  j  a  va2  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) {
    long locationId;

    // 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);
    }

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

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

public void test_book_by_id_with_args() 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
            TestContract.Book.PUBLISHER_TITLE + "=?", //selection
            new String[] { "Wow publisher" }, //selectionArgs
            null //sort order
    );//  w  w  w . j a va2 s  . co 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.seneca.android.senfitbeta.DbHelper.java

public ArrayList<Exercise> getExercises() {
    Log.d("SELECT EXDB", "Getinging exercise");

    String fetchdata = "select * from " + EXERCISE_TABLE + " ORDER BY " + NAMETYPE + " ASC";

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(fetchdata, null);
    cursor.moveToFirst();/*www .  j  av  a  2s .c o m*/

    if (cursor == null) {
        Log.d("exiting", "NOTHING");
    }

    ArrayList<Exercise> temp = new ArrayList<Exercise>();

    cursor.moveToFirst();
    do {
        Exercise ex = new Exercise();
        ex.setId(cursor.getInt(cursor.getColumnIndex(EXERCISE_ID)));
        ex.setLicense_author(cursor.getString(cursor.getColumnIndex(AUTHOR)));
        ex.setDescription(cursor.getString(cursor.getColumnIndex(DESCRIPTION)));
        ex.setName(cursor.getString(cursor.getColumnIndex(NAMETYPE)));
        ex.setName_original(cursor.getString(cursor.getColumnIndex(ORIGNALNAME)));
        ex.setCreation_date(cursor.getString(cursor.getColumnIndex(CREATIONDATE)));
        ex.setCategory(cursor.getString(cursor.getColumnIndex(CATEGORY)));

        temp.add(ex);
    } while (cursor.moveToNext());

    cursor.close();
    getReadableDatabase().close();
    return temp;

}

From source file:com.example.cmput301.model.DatabaseManager.java

/**
 * Gets a task (if exists) from the "local" table of the database.
 *
 * @param id ID of task to search for//  ww w .j  a  v  a 2s  .  com
 * @return Task found, if nothing found returns null.
 * @throws JSONException 
 */
public Task getLocalTask(String id) {
    try {
        Cursor c = db.rawQuery(
                "SELECT * FROM " + StringRes.LOCAL_TASK_TABLE_NAME + " WHERE " + StringRes.COL_ID + "=?",
                new String[] { id, });
        if (c == null || c.getCount() == 0) {
            return null;
        } else {
            c.moveToFirst();
            String string = c.getString(c.getColumnIndex(StringRes.COL_CONTENT));

            return toTask(getJsonTask(string));
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return null;

}

From source file:com.example.cmput301.model.DatabaseManager.java

/**
 * Gets a task (if exists) from the "remote" table of the database.
 *
 * @param id ID of task to search for/*from   www  .  j  a v a2s .c  o  m*/
 * @return Task found, if nothing found returns null.
 * @throws JSONException 
 */
public Task getRemoteTask(String id) {
    try {
        Cursor c = db.rawQuery(
                "SELECT * FROM " + StringRes.REMOTE_TASK_TABLE_NAME + " WHERE " + StringRes.COL_ID + "=?",
                new String[] { id, });
        c.moveToFirst();
        if (c == null || c.getCount() == 0) {
            return null;
        } else {
            String taskContent = c.getString(c.getColumnIndex(StringRes.COL_CONTENT));
            JSONObject jsonTask = toJsonTask(taskContent);
            return toTask(jsonTask);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:br.com.dgimenes.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 ww  .  j  av  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) {
    long locationId;

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

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

public long[] getSelectedModelIds(String selection, String[] selectionArgs, String groupBy, String having,
        String orderBy) {//from  w  w w. ja v  a2 s  .  c o m
    final SQLiteDatabase db = mDatabaseManager.openOrCreateDatabase(getDatabaseName());

    final String columns[] = new String[] { BaseColumns._ID };
    Cursor query;

    /*
     * Try the query. If the Table doesn't exist, fix the DB and re-run the query.
     */
    try {
        query = db.query(getTableName(), columns, selection, selectionArgs, groupBy, having, orderBy);
    } catch (final SQLiteException e) {
        prepareTable(db);
        query = db.query(getTableName(), columns, selection, selectionArgs, groupBy, having, orderBy);
    }

    final int columnIndex = query.getColumnIndex(BaseColumns._ID);
    final long result[] = new long[query.getCount()];
    for (query.moveToFirst(); !query.isAfterLast(); query.moveToNext()) {
        result[query.getPosition()] = query.getLong(columnIndex);
    }

    return result;
}

From source file:com.ternup.caddisfly.fragment.ResultFragment.java

private void displayResult() {

    String[] projection = { TestTable.TABLE_TEST + "." + TestTable.COLUMN_ID,
            TestTable.TABLE_TEST + "." + TestTable.COLUMN_DATE, TestTable.COLUMN_RESULT, TestTable.COLUMN_TYPE,
            TestTable.COLUMN_FOLDER, LocationTable.COLUMN_NAME, LocationTable.COLUMN_STREET,
            LocationTable.COLUMN_TOWN, LocationTable.COLUMN_CITY, LocationTable.COLUMN_STATE,
            LocationTable.COLUMN_COUNTRY, LocationTable.COLUMN_STREET, LocationTable.COLUMN_SOURCE };

    Log.d("Result", mId + " test");

    Uri uri = ContentUris.withAppendedId(TestContentProvider.CONTENT_URI, mId);
    Cursor cursor = mContext.getContentResolver().query(uri, projection, null, null, null);
    cursor.moveToFirst();//ww  w .  j  a v a 2 s . c  o m

    mAddressText.setText(cursor.getString(cursor.getColumnIndex(LocationTable.COLUMN_NAME)) + ", "
            + cursor.getString(cursor.getColumnIndex(LocationTable.COLUMN_STREET)));

    mAddress2Text.setText(cursor.getString(cursor.getColumnIndex(LocationTable.COLUMN_TOWN)) + ", "
            + cursor.getString(cursor.getColumnIndex(LocationTable.COLUMN_CITY)));

    mAddress3Text.setText(cursor.getString(cursor.getColumnIndex(LocationTable.COLUMN_STATE)) + ", "
            + cursor.getString(cursor.getColumnIndex(LocationTable.COLUMN_COUNTRY)));

    if (mAddress2Text.getText().equals(", ")) {
        mAddress2Text.setVisibility(View.GONE);
    } else {
        mAddress2Text.setVisibility(View.VISIBLE);
    }
    if (mAddress3Text.getText().equals(", ")) {
        mAddress3Text.setVisibility(View.GONE);
    } else {
        mAddress3Text.setVisibility(View.VISIBLE);
    }
    String[] sourceArray = getResources().getStringArray(R.array.source_types);
    int sourceType = cursor.getInt(cursor.getColumnIndex(LocationTable.COLUMN_SOURCE));
    if (sourceType > -1) {
        mSourceText.setText(sourceArray[sourceType]);
        mSourceText.setVisibility(View.VISIBLE);
    } else {
        mSourceText.setVisibility(View.GONE);
    }
    Date date = new Date(cursor.getLong(cursor.getColumnIndex(TestTable.COLUMN_DATE)));
    SimpleDateFormat df = new SimpleDateFormat("EEE, dd MMM yyyy");
    DateFormat tf = android.text.format.DateFormat.getTimeFormat(getActivity()); // Gets system TF

    String dateString = df.format(date.getTime()) + ", " + tf.format(date.getTime());

    mTestType = DataHelper.getTestTitle(getActivity(),
            cursor.getInt(cursor.getColumnIndex(TestTable.COLUMN_TYPE)));
    mTestTypeId = cursor.getInt(cursor.getColumnIndex(TestTable.COLUMN_TYPE));

    mTitleView.setText(mTestType);
    mDateView.setText(dateString);

    Double resultPpm = cursor.getDouble(cursor.getColumnIndex(TestTable.COLUMN_RESULT));

    if (mTestTypeId == Globals.PH_INDEX) {
        mPpmText.setText("");
    } else {
        mPpmText.setText(R.string.ppm);
    }

    if (resultPpm < 0) {
        mResultTextView.setText("0.0");
        //mResultIcon.setVisibility(View.GONE);
        mPpmText.setVisibility(View.GONE);
    } else {
        mResultTextView.setText(String.format("%.2f", resultPpm));

        Context context = getActivity().getApplicationContext();

        int resourceAttribute;

        if (resultPpm <= Globals.FLUORIDE_MAX_DRINK) {
            resourceAttribute = R.attr.drink;
        } else if (resultPpm <= Globals.FLUORIDE_MAX_COOK) {
            resourceAttribute = R.attr.cook;
        } else if (resultPpm <= Globals.FLUORIDE_MAX_BATHE) {
            resourceAttribute = R.attr.bath;
        } else {
            resourceAttribute = R.attr.wash;
        }

        TypedArray a = context.getTheme().obtainStyledAttributes(
                ((MainApp) context.getApplicationContext()).CurrentTheme, new int[] { resourceAttribute });
        int attributeResourceId = a.getResourceId(0, 0);
        //mResultIcon.setImageResource(attributeResourceId);

        //mResultIcon.setVisibility(View.VISIBLE);
        mPpmText.setVisibility(View.VISIBLE);
    }

    cursor.close();
}

From source file:com.luxtech_eg.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//www .  ja v  a2s.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(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_LATITUDEE, lat);
        locationValues.put(WeatherContract.LocationEntry.COLUMN_LONGITUDE, 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;
}

From source file:com.example.home.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  www .j  a v a  2  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
    // If it exists, return the current ID
    // Otherwise, insert it using the content resolver and the base URI
    long locationId;
    // First, check if the location with this city name exists in the db
    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;
}