Example usage for android.database SQLException SQLException

List of usage examples for android.database SQLException SQLException

Introduction

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

Prototype

public SQLException(String error) 

Source Link

Usage

From source file:com.ohso.omgubuntu.MainActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    if (Build.VERSION.SDK_INT > 11)
        enableStrictMode();/*  w ww. j a  va  2s. c  o  m*/
    super.onCreate(savedInstanceState);
    Fragment articlesFragment = new ArticlesFragment();
    Fragment categoriesFragment = new CategoriesFragment();
    Fragment starredFragment = new StarredFragment();
    Fragment settingsFragment = new SettingsFragment();
    Fragment feedbackFragment = new FeedbackFragment();
    Fragment aboutFragment = new AboutFragment();
    fragments.put("sidebar_home", articlesFragment);
    fragments.put("sidebar_categories", categoriesFragment);
    fragments.put("sidebar_starred", starredFragment);
    fragments.put("sidebar_settings", settingsFragment);
    fragments.put("sidebar_feedback", feedbackFragment);
    fragments.put("sidebar_about", aboutFragment);

    articleFragmentContainer = (RelativeLayout) findViewById(R.id.fragment_articles_container);
    setTitle(R.string.app_name);
    OMGUbuntuDatabaseHelper db = new OMGUbuntuDatabaseHelper(this);
    try {
        db.getWritableDatabase();
        db.close();
    } catch (SQLException e) {
        throw new SQLException("Couldn't get db " + e.toString());
    }

    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    sidebar.setActiveFragment("sidebar_home");
    fragmentTransaction.replace(R.id.fragment_articles_container, articlesFragment);
    fragmentTransaction.commit();

    if (getSharedPreferences(OMGUbuntuApplication.PREFS_FILE, 0)
            .getBoolean(SettingsFragment.NOTIFICATIONS_ENABLED, true)) {
        NotificationAlarmGenerator.generateAlarm(this);
    }

    // Debug lines to force notifications for testing
    // if (!NotificationService.isNotificationAlarmActive()) {
    //     NotificationAlarmGenerator.generateAlarm(getApplicationContext());
    // }
    // Intent testIntent = new Intent(this, NotificationService.class);
    // startService(testIntent);
}

From source file:org.liberty.android.fantastischmemopro.DatabaseHelper.java

public DatabaseHelper(Context context, String path, String name) {
    super(context, name, null, 1);

    dbPath = path;/*from   ww w. j  a  v  a 2 s.  c om*/
    dbName = name;
    File dbfile = new File(dbPath + "/" + dbName);
    mContext = context;
    /* So if the database does not exist, it will create a new one */
    openDatabase();
    if (!checkDatabase()) {
        throw new SQLException("Database check failed.");
    }
}

From source file:com.manning.androidhacks.hack043.provider.MySQLContentProvider.java

@Override
protected Uri insertInTransaction(Uri uri, ContentValues values) {
    String table = null;/*from  w w w .ja v  a2 s. c o  m*/

    switch (sUriMatcher.match(uri)) {
    case ITEM:
        table = TABLE_NAME;
        break;
    default:
        new RuntimeException("Invalid URI for inserting: " + uri);
    }

    long rowId = mDb.insert(table, null, values);

    if (rowId > 0) {
        Uri noteUri = ContentUris.withAppendedId(uri, rowId);
        return noteUri;
    }

    throw new SQLException("Failed to insert row into " + uri);
}

From source file:com.gsma.rcs.ri.utils.RcsContactUtil.java

private String getDisplayNameFromAddressBook(ContactId contact) {
    /* First try to get it from cache */
    String displayName = mDisplayNameAndroidCache.get(contact);
    if (displayName != null) {
        return displayName;
    }//from  w w  w.  jav  a 2s.  c  o  m
    /* Not found in cache: query the Android address book */
    Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
            Uri.encode(contact.toString()));
    Cursor cursor = null;
    try {
        cursor = mResolver.query(uri, PROJ_DISPLAY_NAME, null, null, null);
        if (cursor == null) {
            throw new SQLException("Cannot query display name for contact=" + contact);
        }
        if (!cursor.moveToFirst()) {
            return null;
        }
        displayName = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.PhoneLookup.DISPLAY_NAME));
        /* Insert in cache */
        mDisplayNameAndroidCache.put(contact, displayName);
        return displayName;

    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

From source file:org.opendatakit.common.android.provider.impl.InstanceProviderImpl.java

@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
    List<String> segments = uri.getPathSegments();

    if (segments.size() < 2 || segments.size() > 3) {
        throw new SQLException("Unknown URI (too many segments!) " + uri);
    }/*from www .  j  av a  2s. com*/

    String appName = segments.get(0);
    ODKFileUtils.verifyExternalStorageAvailability();
    ODKFileUtils.assertDirectoryStructure(appName);
    String tableId = segments.get(1);
    String instanceName = null;
    // _ID in UPLOADS_TABLE_NAME
    String instanceId = (segments.size() == 3 ? segments.get(2) : null);

    SQLiteDatabase db = null;
    String fullQuery;
    String filterArgs[];
    Cursor c = null;

    String dbTableName;
    List<ColumnDefinition> orderedDefns;

    StringBuilder b = new StringBuilder();

    try {
        db = DatabaseFactory.get().getDatabase(getContext(), appName);
        db.beginTransaction();

        boolean success = false;
        try {
            success = ODKDatabaseUtils.get().hasTableId(db, tableId);
        } catch (Exception e) {
            e.printStackTrace();
            throw new SQLException("Unknown URI (exception testing for tableId) " + uri);
        }
        if (!success) {
            throw new SQLException("Unknown URI (missing data table for tableId) " + uri);
        }

        dbTableName = "\"" + tableId + "\"";

        try {
            c = db.query(DatabaseConstants.KEY_VALUE_STORE_ACTIVE_TABLE_NAME,
                    new String[] { KeyValueStoreColumns.VALUE },
                    KeyValueStoreColumns.TABLE_ID + "=? AND " + KeyValueStoreColumns.PARTITION + "=? AND "
                            + KeyValueStoreColumns.ASPECT + "=? AND " + KeyValueStoreColumns.KEY + "=?",
                    new String[] { tableId, KeyValueStoreConstants.PARTITION_TABLE,
                            KeyValueStoreConstants.ASPECT_DEFAULT, KeyValueStoreConstants.XML_INSTANCE_NAME },
                    null, null, null);

            if (c.getCount() == 1) {
                c.moveToFirst();
                int idxInstanceName = c.getColumnIndex(KeyValueStoreColumns.VALUE);
                instanceName = c.getString(idxInstanceName);
            }
        } finally {
            c.close();
        }

        // ARGH! we must ensure that we have records in our UPLOADS_TABLE_NAME
        // for every distinct instance in the data table.
        b.setLength(0);
        //@formatter:off
        b.append("INSERT INTO ").append(DatabaseConstants.UPLOADS_TABLE_NAME).append("(")
                .append(InstanceColumns.DATA_INSTANCE_ID).append(",")
                .append(InstanceColumns.DATA_TABLE_TABLE_ID).append(") ").append("SELECT ")
                .append(InstanceColumns.DATA_INSTANCE_ID).append(",")
                .append(InstanceColumns.DATA_TABLE_TABLE_ID).append(" FROM (").append("SELECT DISTINCT ")
                .append(DATA_TABLE_ID_COLUMN).append(" as ").append(InstanceColumns.DATA_INSTANCE_ID)
                .append(",").append("? as ").append(InstanceColumns.DATA_TABLE_TABLE_ID).append(" FROM ")
                .append(dbTableName).append(" EXCEPT SELECT DISTINCT ").append(InstanceColumns.DATA_INSTANCE_ID)
                .append(",").append(InstanceColumns.DATA_TABLE_TABLE_ID).append(" FROM ")
                .append(DatabaseConstants.UPLOADS_TABLE_NAME).append(")");
        //@formatter:on

        // TODO: should we collapse across FORM_ID or leave it this way?
        String[] args = { tableId };
        db.execSQL(b.toString(), args);

        // Can't get away with dataTable.* because of collision with _ID column
        // get map of (elementKey -> ColumnDefinition)
        try {
            orderedDefns = TableUtil.get().getColumnDefinitions(db, appName, tableId);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            throw new SQLException("Unable to retrieve column definitions for tableId " + tableId);
        }

        db.setTransactionSuccessful();
    } finally {
        if (db != null) {
            db.endTransaction();
            db.close();
        }
    }

    ////////////////////////////////////////////////////////////////
    // OK we have the info we need -- now build the query we want...

    // We can now join through and access the data table rows

    b.setLength(0);
    // @formatter:off
    b.append("SELECT ");
    b.append(DatabaseConstants.UPLOADS_TABLE_NAME).append(".").append(InstanceColumns._ID).append(" as ")
            .append(InstanceColumns._ID).append(",").append(DatabaseConstants.UPLOADS_TABLE_NAME).append(".")
            .append(InstanceColumns.DATA_INSTANCE_ID).append(" as ").append(InstanceColumns.DATA_INSTANCE_ID)
            .append(",").append(DatabaseConstants.UPLOADS_TABLE_NAME).append(".")
            .append(InstanceColumns.SUBMISSION_INSTANCE_ID).append(" as ")
            .append(InstanceColumns.SUBMISSION_INSTANCE_ID).append(",");
    // add the dataTable metadata except for _ID (which conflicts with InstanceColumns._ID)
    b.append(dbTableName).append(".").append(DataTableColumns.ROW_ETAG).append(" as ")
            .append(DataTableColumns.ROW_ETAG).append(",").append(dbTableName).append(".")
            .append(DataTableColumns.SYNC_STATE).append(" as ").append(DataTableColumns.SYNC_STATE).append(",")
            .append(dbTableName).append(".").append(DataTableColumns.CONFLICT_TYPE).append(" as ")
            .append(DataTableColumns.CONFLICT_TYPE).append(",").append(dbTableName).append(".")
            .append(DataTableColumns.FILTER_TYPE).append(" as ").append(DataTableColumns.FILTER_TYPE)
            .append(",").append(dbTableName).append(".").append(DataTableColumns.FILTER_VALUE).append(" as ")
            .append(DataTableColumns.FILTER_VALUE).append(",").append(dbTableName).append(".")
            .append(DataTableColumns.FORM_ID).append(" as ").append(DataTableColumns.FORM_ID).append(",")
            .append(dbTableName).append(".").append(DataTableColumns.LOCALE).append(" as ")
            .append(DataTableColumns.LOCALE).append(",").append(dbTableName).append(".")
            .append(DataTableColumns.SAVEPOINT_TYPE).append(" as ").append(DataTableColumns.SAVEPOINT_TYPE)
            .append(",").append(dbTableName).append(".").append(DataTableColumns.SAVEPOINT_TIMESTAMP)
            .append(" as ").append(DataTableColumns.SAVEPOINT_TIMESTAMP).append(",").append(dbTableName)
            .append(".").append(DataTableColumns.SAVEPOINT_CREATOR).append(" as ")
            .append(DataTableColumns.SAVEPOINT_CREATOR).append(",");
    // add the user-specified data fields in this dataTable
    for (ColumnDefinition cd : orderedDefns) {
        if (cd.isUnitOfRetention()) {
            b.append(dbTableName).append(".").append(cd.getElementKey()).append(" as ")
                    .append(cd.getElementKey()).append(",");
        }
    }
    b.append("CASE WHEN ").append(DATA_TABLE_SAVEPOINT_TIMESTAMP_COLUMN).append(" IS NULL THEN null")
            .append(" WHEN ").append(InstanceColumns.XML_PUBLISH_TIMESTAMP).append(" IS NULL THEN null")
            .append(" WHEN ").append(DATA_TABLE_SAVEPOINT_TIMESTAMP_COLUMN).append(" > ")
            .append(InstanceColumns.XML_PUBLISH_TIMESTAMP).append(" THEN null").append(" ELSE ")
            .append(InstanceColumns.XML_PUBLISH_TIMESTAMP).append(" END as ")
            .append(InstanceColumns.XML_PUBLISH_TIMESTAMP).append(",");
    b.append("CASE WHEN ").append(DATA_TABLE_SAVEPOINT_TIMESTAMP_COLUMN).append(" IS NULL THEN null")
            .append(" WHEN ").append(InstanceColumns.XML_PUBLISH_TIMESTAMP).append(" IS NULL THEN null")
            .append(" WHEN ").append(DATA_TABLE_SAVEPOINT_TIMESTAMP_COLUMN).append(" > ")
            .append(InstanceColumns.XML_PUBLISH_TIMESTAMP).append(" THEN null").append(" ELSE ")
            .append(InstanceColumns.XML_PUBLISH_STATUS).append(" END as ")
            .append(InstanceColumns.XML_PUBLISH_STATUS).append(",");
    b.append("CASE WHEN ").append(DATA_TABLE_SAVEPOINT_TIMESTAMP_COLUMN).append(" IS NULL THEN null")
            .append(" WHEN ").append(InstanceColumns.XML_PUBLISH_TIMESTAMP).append(" IS NULL THEN null")
            .append(" WHEN ").append(DATA_TABLE_SAVEPOINT_TIMESTAMP_COLUMN).append(" > ")
            .append(InstanceColumns.XML_PUBLISH_TIMESTAMP).append(" THEN null").append(" ELSE ")
            .append(InstanceColumns.DISPLAY_SUBTEXT).append(" END as ").append(InstanceColumns.DISPLAY_SUBTEXT)
            .append(",");
    if (instanceName == null) {
        b.append(DataTableColumns.SAVEPOINT_TIMESTAMP);
    } else {
        b.append(instanceName);
    }
    b.append(" as ").append(InstanceColumns.DISPLAY_NAME);
    b.append(" FROM ");
    b.append("( SELECT * FROM ").append(dbTableName).append(" AS T WHERE T.")
            .append(DATA_TABLE_SAVEPOINT_TIMESTAMP_COLUMN).append("=(SELECT MAX(V.")
            .append(DATA_TABLE_SAVEPOINT_TIMESTAMP_COLUMN).append(") FROM ").append(dbTableName)
            .append(" AS V WHERE V.").append(DATA_TABLE_ID_COLUMN).append("=T.").append(DATA_TABLE_ID_COLUMN)
            .append(" AND V.").append(DATA_TABLE_SAVEPOINT_TYPE_COLUMN).append(" IS NOT NULL").append(")")
            .append(") as ").append(dbTableName);
    b.append(" JOIN ").append(DatabaseConstants.UPLOADS_TABLE_NAME).append(" ON ").append(dbTableName)
            .append(".").append(DATA_TABLE_ID_COLUMN).append("=").append(DatabaseConstants.UPLOADS_TABLE_NAME)
            .append(".").append(InstanceColumns.DATA_INSTANCE_ID).append(" AND ").append("? =")
            .append(DatabaseConstants.UPLOADS_TABLE_NAME).append(".")
            .append(InstanceColumns.DATA_TABLE_TABLE_ID);
    b.append(" WHERE ").append(DATA_TABLE_SAVEPOINT_TYPE_COLUMN).append("=?");
    // @formatter:on

    if (instanceId != null) {
        b.append(" AND ").append(DatabaseConstants.UPLOADS_TABLE_NAME).append(".").append(InstanceColumns._ID)
                .append("=?");
        String tempArgs[] = { tableId, InstanceColumns.STATUS_COMPLETE, instanceId };
        filterArgs = tempArgs;
    } else {
        String tempArgs[] = { tableId, InstanceColumns.STATUS_COMPLETE };
        filterArgs = tempArgs;
    }

    if (selection != null) {
        b.append(" AND (").append(selection).append(")");
    }

    if (selectionArgs != null) {
        String[] tempArgs = new String[filterArgs.length + selectionArgs.length];
        for (int i = 0; i < filterArgs.length; ++i) {
            tempArgs[i] = filterArgs[i];
        }
        for (int i = 0; i < selectionArgs.length; ++i) {
            tempArgs[filterArgs.length + i] = selectionArgs[i];
        }
        filterArgs = tempArgs;
    }

    if (sortOrder != null) {
        b.append(" ORDER BY ").append(sortOrder);
    }

    fullQuery = b.toString();

    db = null;
    boolean success = false;
    try {
        db = DatabaseFactory.get().getDatabase(getContext(), appName);
        c = db.rawQuery(fullQuery, filterArgs);
        // Tell the cursor what uri to watch, so it knows when its source data
        // changes
        c.setNotificationUri(getContext().getContentResolver(), uri);
        success = true;
        return c;
    } finally {
        if (db != null && !success) {
            // leave database open for cursor...
            db.close();
        }
    }
}

From source file:com.gsma.rcs.ri.messaging.geoloc.DisplayGeoloc.java

private static Geoloc getLastGeoloc(Context ctx, ContactId contact) {
    Cursor cursor = null;/*from ww w . j av a2  s .  c o  m*/
    String where = Message.CONTACT + "='" + contact.toString() + "' AND " + Message.MIME_TYPE + "='"
            + Message.MimeType.GEOLOC_MESSAGE + "' AND " + Message.DIRECTION + " = "
            + Direction.INCOMING.toInt();
    try {
        cursor = ctx.getContentResolver().query(Message.CONTENT_URI, QUERY_PROJECTION, where, null,
                QUERY_SORT_ORDER);
        if (cursor == null) {
            throw new SQLException("Cannot query last geoloc for contact " + contact);
        }
        if (!cursor.moveToNext()) {
            return null;
        }
        String content = cursor.getString(cursor.getColumnIndexOrThrow(Message.CONTENT));
        return new Geoloc(content);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

From source file:org.opendatakit.sensors.manager.WorkerThread.java

private void parseSensorDataAndInsertIntoTable(ODKSensor aSensor, String strTableDef, Bundle dataBundle) {
    JSONObject jsonTableDef = null;/*from  w ww . ja  v  a2 s .  co m*/
    ContentValues tablesValues = new ContentValues();

    SQLiteDatabase db = null;
    try {
        db = DatabaseFactory.get().getDatabase(serviceContext, aSensor.getAppNameForDatabase());

        jsonTableDef = new JSONObject(strTableDef);

        String tableId = jsonTableDef.getJSONObject(ODKJsonNames.jsonTableStr)
                .getString(ODKJsonNames.jsonTableIdStr);

        if (tableId == null) {
            return;
        }

        boolean success;

        success = false;
        try {
            success = ODKDatabaseUtils.get().hasTableId(db, tableId);
        } catch (Exception e) {
            e.printStackTrace();
            throw new SQLException("Exception testing for tableId " + tableId);
        }
        if (!success) {
            sensorManager.parseDriverTableDefintionAndCreateTable(aSensor.getSensorID(),
                    aSensor.getAppNameForDatabase(), db);
        }

        success = false;
        try {
            success = ODKDatabaseUtils.get().hasTableId(db, tableId);
        } catch (Exception e) {
            e.printStackTrace();
            throw new SQLException("Exception testing for tableId " + tableId);
        }
        if (!success) {
            throw new SQLException("Unable to create tableId " + tableId);
        }

        ArrayList<ColumnDefinition> orderedDefs = TableUtil.get().getColumnDefinitions(db,
                aSensor.getAppNameForDatabase(), tableId);

        // Create the columns for the driver table
        for (ColumnDefinition col : orderedDefs) {
            if (!col.isUnitOfRetention()) {
                continue;
            }

            String colName = col.getElementKey();
            ElementType type = col.getType();

            if (colName.equals(DataSeries.SENSOR_ID)) {

                // special treatment
                tablesValues.put(colName, aSensor.getSensorID());

            } else if (type.getDataType() == ElementDataType.bool) {

                Boolean boolColData = dataBundle.containsKey(colName) ? dataBundle.getBoolean(colName) : null;
                Integer colData = (boolColData == null) ? null : (boolColData ? 1 : 0);
                tablesValues.put(colName, colData);

            } else if (type.getDataType() == ElementDataType.integer) {

                Integer colData = dataBundle.containsKey(colName) ? dataBundle.getInt(colName) : null;
                tablesValues.put(colName, colData);

            } else if (type.getDataType() == ElementDataType.number) {

                Double colData = dataBundle.containsKey(colName) ? dataBundle.getDouble(colName) : null;
                tablesValues.put(colName, colData);

            } else {
                // everything else is a string value coming across the wire...
                String colData = dataBundle.containsKey(colName) ? dataBundle.getString(colName) : null;
                tablesValues.put(colName, colData);
            }
        }

        if (tablesValues.size() > 0) {
            Log.i(TAG, "Writing db values for sensor:" + aSensor.getSensorID());
            String rowId = tablesValues.containsKey(DataTableColumns.ID)
                    ? tablesValues.getAsString(DataTableColumns.ID)
                    : null;
            if (rowId == null) {
                rowId = ODKDataUtils.genUUID();
            }
            ODKDatabaseUtils.get().insertDataIntoExistingDBTableWithId(db, tableId, orderedDefs, tablesValues,
                    rowId);
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (db != null) {
            db.close();
        }
    }
}

From source file:com.silentcorp.autotracker.db.VehicleDB.java

/**
 * Read a vehicle from the DB given its ID
 * //  ww  w.jav a 2s .  c o  m
 * @param contentResolver content resolver
 * @param id vehicle ID
 * @param vehicle object to fill, if NULL, new created and returned
 * @return full vehicle object
 * @throws SQLException
 */
public static VehicleBean readVehicle(Context context, long id, VehicleBean vehicle) throws SQLException {
    Uri uri = Uri.parse(DBContentProvider.VEHICLES_URI + "/" + id);
    // Read all columns for the record
    ContentResolver contentResolver = context.getContentResolver();
    Cursor cursor = contentResolver.query(uri, null, null, null, null);
    if (cursor == null || cursor.getCount() == 0) {
        throw new SQLException("Unable to find vehicle with ID: " + id + " Corrupt DB?");
    }
    // more then one vehicle
    if (cursor.getCount() > 1) {
        throw new SQLException("More then one vehicle with ID: " + id + " Corrupt DB?");
    }

    cursor.moveToFirst();

    if (vehicle == null) {
        vehicle = new VehicleBean();
    }

    vehicle.setId(id);
    vehicle.setName(Utils.readString(cursor, COL_NAME, TABLE_VEHICLE));
    vehicle.setColor(Utils.readInt(cursor, COL_COLOR, TABLE_VEHICLE));
    vehicle.setMake(Utils.readString(cursor, COL_MAKE, TABLE_VEHICLE));
    vehicle.setModel(Utils.readString(cursor, COL_MODEL, TABLE_VEHICLE));
    vehicle.setYear(Utils.readWhole(cursor, COL_YEAR, TABLE_VEHICLE));
    vehicle.setLicensePlate(Utils.readString(cursor, COL_LICENSE_PLATE, TABLE_VEHICLE));
    vehicle.setPrimaryFuel(Utils.readString(cursor, COL_PRIMARY_FUEL, TABLE_VEHICLE));
    vehicle.setSecondaryFuel(Utils.readString(cursor, COL_SECONDARY_FUEL, TABLE_VEHICLE));
    vehicle.setPurchaseDate(Utils.readLong(cursor, COL_PURCHASE_DATE, TABLE_VEHICLE));
    vehicle.setPurchasePrice(Utils.readDouble(cursor, COL_PURCHASE_PRICE, TABLE_VEHICLE));
    vehicle.setPurchaseOdometer(Utils.readWhole(cursor, COL_PURCHASE_ODOMETER, TABLE_VEHICLE));
    vehicle.setPurchaseNote(Utils.readString(cursor, COL_PURCHASE_NOTE, TABLE_VEHICLE));
    vehicle.setIsSold(Utils.readBoolean(cursor, COL_SELL_FLAG, TABLE_VEHICLE));
    vehicle.setSellDate(Utils.readLong(cursor, COL_SELL_DATE, TABLE_VEHICLE));
    vehicle.setSellPrice(Utils.readDouble(cursor, COL_SELL_PRICE, TABLE_VEHICLE));
    vehicle.setSellOdometer(Utils.readWhole(cursor, COL_SELL_ODOMETER, TABLE_VEHICLE));
    vehicle.setSellNote(Utils.readString(cursor, COL_SELL_NOTE, TABLE_VEHICLE));

    cursor.close();

    return vehicle;
}

From source file:com.gsma.rcs.ri.messaging.geoloc.DisplayGeoloc.java

private static Geoloc getMyLastGeoloc(Context ctx) {
    Cursor cursor = null;/*w  w  w  .j  av a 2s  .com*/
    try {
        cursor = ctx.getContentResolver().query(Message.CONTENT_URI, QUERY_PROJECTION, QUERY_WHERE_CLAUSE, null,
                QUERY_SORT_ORDER);
        if (cursor == null) {
            throw new SQLException("Cannot query my last geoloc");
        }
        if (!cursor.moveToNext()) {
            return null;
        }
        String content = cursor.getString(cursor.getColumnIndexOrThrow(Message.CONTENT));
        return new Geoloc(content);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

From source file:com.manning.androidhacks.hack043.provider.BatchNumbersContentProvider.java

@Override
public Uri insert(Uri uri, ContentValues initialValues) {
    ContentValues values;/*from www .j  av  a2  s  .  c o  m*/
    if (initialValues != null) {
        values = new ContentValues(initialValues);
    } else {
        values = new ContentValues();
    }
    String table = null;
    String nullableCol = null;

    switch (sUriMatcher.match(uri)) {
    case ITEM:
        table = TABLE_NAME;
        break;
    default:
        new RuntimeException("Invalid URI for inserting: " + uri);
    }

    SQLiteDatabase db = dbHelper.getWritableDatabase();
    long rowId = db.insert(table, nullableCol, values);

    if (rowId > 0) {
        Uri noteUri = ContentUris.withAppendedId(uri, rowId);
        getContext().getContentResolver().notifyChange(noteUri, null);
        return noteUri;
    }

    throw new SQLException("Failed to insert row into " + uri);
}