Example usage for android.content ContentUris parseId

List of usage examples for android.content ContentUris parseId

Introduction

In this page you can find the example usage for android.content ContentUris parseId.

Prototype

public static long parseId(Uri contentUri) 

Source Link

Document

Converts the last path segment to a long.

Usage

From source file:org.blanco.lacuenta.fragments.SplitsFragment.java

public String saveResultToDb(Context ctx) {
    Split res = clickListener.getResult();
    if (res != null) {
        Uri uri = Split.insert(res, ctx);
        StringBuilder msg = new StringBuilder(getString(R.string.record));
        msg.append(" ").append(ContentUris.parseId(uri)).append(" ").append(getString(R.string.created));
        return msg.toString();
    } else/*from w  w  w  . j av  a  2  s. com*/
        return getString(R.string.no_calculus_done_yet_msg);
}

From source file:com.glandorf1.joe.wsprnetviewer.app.sync.WsprNetViewerSyncAdapter.java

/**
 * Helper method to handle insertion of a new gridsquare in the wspr database.
 *
 * @param gridsquareSetting The gridsquare 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 gridsquare.
 *//* ww w .j a  v a 2s.  com*/
public long addGridsquare(Context context, String gridsquareSetting, String cityName, String countryName,
        double lat, double lon) {

    // First, check if the gridsquare with this city name exists in the db
    Cursor cursor = context.getContentResolver().query(WsprNetContract.GridSquareEntry.CONTENT_URI,
            new String[] { WsprNetContract.GridSquareEntry._ID },
            WsprNetContract.GridSquareEntry.COLUMN_GRIDSQUARE_SETTING + " = ?",
            new String[] { gridsquareSetting }, null);

    if (cursor.moveToFirst()) {
        int gridsquareIdIndex = cursor.getColumnIndex(WsprNetContract.GridSquareEntry._ID);
        return cursor.getLong(gridsquareIdIndex);
    } else {
        ContentValues gridsquareValues = new ContentValues();
        gridsquareValues.put(WsprNetContract.GridSquareEntry.COLUMN_GRIDSQUARE_SETTING, gridsquareSetting);
        gridsquareValues.put(WsprNetContract.GridSquareEntry.COLUMN_CITY_NAME, cityName);
        gridsquareValues.put(WsprNetContract.GridSquareEntry.COLUMN_COUNTRY_NAME, countryName);
        gridsquareValues.put(WsprNetContract.GridSquareEntry.COLUMN_COORD_LAT, lat);
        gridsquareValues.put(WsprNetContract.GridSquareEntry.COLUMN_COORD_LONG, lon);

        Uri gridsquareInsertUri = context.getContentResolver()
                .insert(WsprNetContract.GridSquareEntry.CONTENT_URI, gridsquareValues);

        return ContentUris.parseId(gridsquareInsertUri);
    }
}

From source file:com.confidentsoftware.themebuilder.FlickrParser.java

private int addImagesFromJson(long wordId, String text, JSONObject queryResult) throws JSONException {
    JSONArray photos = queryResult.getJSONArray("photo");
    int numImages = 0;
    for (int i = 0; i < photos.length(); i++) {
        JSONObject photo = null;//from www  .  j  av a 2 s. co m
        try {
            photo = photos.getJSONObject(i);
        } catch (JSONException e) {
            continue;
        }
        try {
            if (isPhotoOk(photo)) {
                String url = photo.getString(PHOTO_URL);
                String title = photo.getString("title");
                if (title.length() > MAX_TITLE_LENGTH) {
                    title = title.substring(0, MAX_TITLE_LENGTH - 3) + "...";
                }
                String id = photo.getString("id");
                Log.d(TAG, "Image: " + id);
                Uri imageUri = Images.findImage(mCr, Sites.CONTENT_URI_FLICKR, id);
                if (imageUri != null) {
                    Log.d(TAG, "Found existing image: " + imageUri);
                    // Just insert the mapping
                    Uri mappingUri = Dictionary.Words.CONTENT_URI.buildUpon().appendPath(String.valueOf(wordId))
                            .appendPath(Dictionary.PATH_IMAGES).appendPath(imageUri.getLastPathSegment())
                            .build();
                    Cursor c = mCr.query(mappingUri, PROJECTION_ID, null, null, null);
                    try {
                        if (!c.moveToNext()) {
                            mCr.insert(mappingUri, null);
                        }
                    } finally {
                        c.close();
                    }
                } else {
                    ContentValues values = new ContentValues();
                    values.put(Images.URL, url);
                    values.put(Images.SITE, ContentUris.parseId(Sites.CONTENT_URI_FLICKR));
                    values.put(Images.SITE_UNIQUE_NAME, id);
                    values.put(Images.WIDTH, photo.getInt(PHOTO_WIDTH));
                    values.put(Images.HEIGHT, photo.getInt(PHOTO_HEIGHT));
                    values.put(Images.THUMB_URL, photo.getString(THUMB_URL));
                    values.put(Images.NUM_FAVORITES, getNumFavorites(id));
                    imageUri = mCr.insert(Dictionary.BASE_CONTENT_URI.buildUpon()
                            .appendPath(Dictionary.PATH_WORDS).appendPath(String.valueOf(wordId))
                            .appendPath(Dictionary.PATH_IMAGES).build(), values);
                    //
                    // String ownerName = photo.getString("owner");
                    // Author author = findAuthor(ownerName);
                    // if (author == null) {
                    // author = buildAuthor(ownerName);
                    // }
                    // TODO set license
                    // image.setLicense(License.getLicenseByFlickrId(photo
                    // .getInt("license")));
                    // dbHelper.getImageDao().create(image);
                }
                // dbHelper.getWordImageDao().create(
                // new WordImage(word, image));
                numImages++;
            }
        } catch (JSONException e) {
            // Catch here so that we continue through the loop
            Log.w(TAG, "Error parsing photo: " + photo, e);
        }
    }
    return numImages;
}

From source file:tom.udacity.sample.sunrise.WeatherDataParser.java

private long addLocation(String locationSettings, String cityName, double lat, double lon) {
    Log.v(TAG, "inserting " + cityName + ", with coord: " + lat + ", " + lon);

    Cursor cursor = mContext.getContentResolver().query(WeatherContract.LocationEntry.CONTENT_URI,
            new String[] { WeatherContract.LocationEntry._ID },
            WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ?", new String[] { locationSettings },
            null);/*ww w . j av  a2  s  .  c o m*/

    try {
        if (cursor != null && cursor.moveToFirst()) {
            Log.v(TAG, "Found in database");
            int locationIndex = cursor.getColumnIndex(WeatherContract.LocationEntry._ID);
            return cursor.getLong(locationIndex);
        } else {
            ContentValues contentValues = new ContentValues();
            contentValues.put(WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING, locationSettings);
            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 locationUri = mContext.getContentResolver().insert(WeatherContract.LocationEntry.CONTENT_URI,
                    contentValues);
            return ContentUris.parseId(locationUri);
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

From source file:com.csipsimple.backup.SipProfileJson.java

private static boolean restoreSipProfile(JSONObject jsonObj, ContentResolver cr) {
    // Restore accounts
    Columns cols;// w ww  .  jav a  2s.  c o m
    ContentValues cv;

    cols = getSipProfileColumns(false);
    cv = cols.jsonToContentValues(jsonObj);

    long profileId = cv.getAsLong(SipProfile.FIELD_ID);
    if (profileId >= 0) {
        Uri insertedUri = cr.insert(SipProfile.ACCOUNT_URI, cv);
        profileId = ContentUris.parseId(insertedUri);
    }
    // TODO : else restore call handler in private db

    // Restore filters
    cols = new Columns(Filter.FULL_PROJ, Filter.FULL_PROJ_TYPES);
    try {
        JSONArray filtersObj = jsonObj.getJSONArray(FILTER_KEY);
        Log.d(THIS_FILE, "We have filters for " + profileId + " > " + filtersObj.length());
        for (int i = 0; i < filtersObj.length(); i++) {
            JSONObject filterObj = filtersObj.getJSONObject(i);
            // Log.d(THIS_FILE, "restoring "+filterObj.toString(4));
            cv = cols.jsonToContentValues(filterObj);
            cv.put(Filter.FIELD_ACCOUNT, profileId);
            cr.insert(SipManager.FILTER_URI, cv);
        }
    } catch (JSONException e) {
        Log.e(THIS_FILE, "Error while restoring filters", e);
    }

    return false;
}

From source file:org.kontalk.ui.ComposeMessage.java

private AbstractComposeFragment getComposeFragment(Bundle savedInstanceState) {
    Bundle args = processIntent(savedInstanceState);
    if (args != null) {
        AbstractComposeFragment f = null;
        Uri threadUri = args.getParcelable("data");
        String action = args.getString("action");
        if (ACTION_VIEW_CONVERSATION.equals(action)) {
            long threadId = ContentUris.parseId(threadUri);
            Conversation conv = Conversation.loadFromId(this, threadId);
            if (conv != null) {
                f = conv.isGroupChat() ? new GroupMessageFragment() : new ComposeMessageFragment();
            }/*from  ww w .j  a  v a  2s . co  m*/
        } else if (ACTION_VIEW_USERID.equals(action)) {
            String userId = threadUri.getLastPathSegment();
            Conversation conv = Conversation.loadFromUserId(this, userId);
            f = conv != null && conv.isGroupChat() ? new GroupMessageFragment() : new ComposeMessageFragment();
        } else {
            // default to a single user chat
            f = new ComposeMessageFragment();
        }

        if (f != null)
            f.setArguments(args);
        return f;
    }

    return null;
}

From source file:com.mio.jrdv.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 w  ww.ja v a  2  s. com
 * @param lon the longitude of the city
 * @return the row ID of the added location.
 */

//este metodo lo he tenido que hace public para poder accederlo desde el TEstFetchWeatherTask!!

public 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
    // return 0;
    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);
    // WeatherContract.LocationEntry.CONTENT_URI:
    //  ES content://com.mio.jrdv.sunshine.app/location

    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:net.sourcewalker.garanbot.api.ItemService.java

public int create(Item itemData) throws ClientException {
    try {/*  ww w  .  j  a va2 s  .  co m*/
        if (itemData.getServerId() != Item.UNKNOWN_ID) {
            throw new ClientException("Can't create Item which already has an ID!");
        }
        String jsonData = itemData.json().toString();
        HttpResponse response = client.put("/item", jsonData);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
            Header locationHeader = response.getFirstHeader("Location");
            Uri itemUri = Uri.parse(locationHeader.getValue());
            return (int) ContentUris.parseId(itemUri);
        } else {
            throw new ClientException("Got HTTP status: " + response.getStatusLine().toString());
        }
    } catch (IOException e) {
        throw new ClientException("IO error: " + e.getMessage(), e);
    } catch (NumberFormatException e) {
        throw new ClientException("Error parsing new item id: " + e.getMessage(), e);
    }
}

From source file:com.dabay6.android.apps.carlog.ui.vehicle.fragments.VehicleEditFragment.java

/**
 *
 */// w w  w.j a va  2s .  c o m
@Override
protected ContentValues buildContentValues() {
    final ContentResolver resolver = getActivity().getContentResolver();
    final StringBuilder vehicleName = new StringBuilder();

    vehicleName.append(ViewUtils.getText(name));

    if (vehicle == null) {
        vehicle = new VehicleDTO();
    }
    if (TextUtils.isEmpty(vehicleName)) {
        if (!ViewUtils.isEmpty(year)) {
            vehicleName.insert(0, " ");
            vehicleName.insert(0, ViewUtils.getText(year));
        }
        vehicleName.append(ViewUtils.getText(make)).append(" ").append(ViewUtils.getText(model));
    }

    vehicle.setIsActive(true);
    vehicle.setLicensePlate(ViewUtils.getText(licensePlate));
    vehicle.setName(vehicleName.toString());
    vehicle.setVin(ViewUtils.getText(vin));

    if (modelAdapter.getMakeId() == null) {
        final MakeDTO makeDTO = new MakeDTO();

        makeDTO.setMakeName(ViewUtils.getText(make));

        modelAdapter.setMakeId(
                ContentUris.parseId(resolver.insert(Make.CONTENT_URI, MakeDTO.buildContentValues(makeDTO))));
    }

    vehicle.setMakeId(modelAdapter.getMakeId());

    if (modelId == null) {
        final ModelDTO modelDTO = new ModelDTO();

        modelDTO.setMakeId(modelAdapter.getMakeId());
        modelDTO.setModelName(ViewUtils.getText(model));

        modelId = ContentUris
                .parseId(resolver.insert(Model.CONTENT_URI, ModelDTO.buildContentValues(modelDTO)));
    }
    vehicle.setModelId(modelId);

    if (!ViewUtils.isEmpty(year)) {
        vehicle.setYear(Integer.valueOf(ViewUtils.getText(year)));
    }

    return VehicleDTO.buildContentValues(vehicle);
}

From source file:com.getmarco.weatherstationviewer.gcm.StationGcmListenerService.java

/**
 * Helper method to handle insertion of a station in the database if it doesn't already exist.
 *
 * @param stationTag the station// w  w  w .j  ava  2 s.c om
 * @return the row ID of the station (new or existing)
 */
long addStation(String stationTag) {
    long stationId;

    // First, check if a station with this tag exists in the db
    Cursor stationCursor = getContentResolver().query(StationContract.StationEntry.CONTENT_URI,
            new String[] { StationContract.StationEntry._ID }, StationContract.StationEntry.COLUMN_TAG + " = ?",
            new String[] { stationTag }, null);

    if (stationCursor.moveToFirst()) {
        int stationIdIndex = stationCursor.getColumnIndex(StationContract.StationEntry._ID);
        stationId = stationCursor.getLong(stationIdIndex);
    } else {
        ContentValues locationValues = new ContentValues();
        locationValues.put(StationContract.StationEntry.COLUMN_TAG, stationTag);
        locationValues.put(StationContract.StationEntry.COLUMN_NAME, stationTag);
        locationValues.put(StationContract.StationEntry.COLUMN_TEMP_HIGH, 0.0);
        locationValues.put(StationContract.StationEntry.COLUMN_TEMP_LOW, 0.0);
        locationValues.put(StationContract.StationEntry.COLUMN_HUMIDITY_HIGH, 0.0);
        locationValues.put(StationContract.StationEntry.COLUMN_HUMIDITY_LOW, 0.0);

        // Finally, insert location data into the database.
        Uri insertedUri = getContentResolver().insert(StationContract.StationEntry.CONTENT_URI, locationValues);

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

    stationCursor.close();
    return stationId;
}