Example usage for android.content ContentValues ContentValues

List of usage examples for android.content ContentValues ContentValues

Introduction

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

Prototype

public ContentValues() 

Source Link

Document

Creates an empty set of values using the default initial size

Usage

From source file:net.naonedbus.manager.impl.FavoriManager.java

/**
 * getContentValues for ArretItem//from   w  w  w. java2  s . c  o m
 * 
 * @param item
 * @return a ContentValue filled with ArretItem values, for a FavoriTable
 *         structure
 */
private ContentValues getContentValues(final Arret item) {
    final ContentValues values = new ContentValues();
    values.put(FavoriTable._ID, item.getId());
    values.put(FavoriTable.CODE_LIGNE, item.getCodeLigne());
    values.put(FavoriTable.CODE_SENS, item.getCodeSens());
    values.put(FavoriTable.CODE_ARRET, item.getCodeArret());
    return values;
}

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

/**
 * Take the String representing the complete forecast in JSON Format and
 * pull out the data we need to construct the Strings needed for the wireframes.
 *
 * Fortunately parsing is easy:  constructor takes the JSON string and converts it
 * into an Object hierarchy for us.//from  w w w  . j  a  v  a 2s.  c  o  m
 */
private void getWeatherDataFromJson(String forecastJsonStr, int numDays, String locationSetting)
        throws JSONException {

    // These are the names of the JSON objects that need to be extracted.

    // Location information
    final String OWM_CITY = "city";
    final String OWM_CITY_NAME = "name";
    final String OWM_COORD = "coord";
    final String OWM_COORD_LAT = "lat";
    final String OWM_COORD_LONG = "lon";

    // Weather information.  Each day's forecast info is an element of the "list" array.
    final String OWM_LIST = "list";

    final String OWM_DATETIME = "dt";
    final String OWM_PRESSURE = "pressure";
    final String OWM_HUMIDITY = "humidity";
    final String OWM_WINDSPEED = "speed";
    final String OWM_WIND_DIRECTION = "deg";

    // All temperatures are children of the "temp" object.
    final String OWM_TEMPERATURE = "temp";
    final String OWM_MAX = "max";
    final String OWM_MIN = "min";

    final String OWM_WEATHER = "weather";
    final String OWM_DESCRIPTION = "main";
    final String OWM_WEATHER_ID = "id";

    JSONObject forecastJson = new JSONObject(forecastJsonStr);
    JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);

    JSONObject cityJson = forecastJson.getJSONObject(OWM_CITY);
    String cityName = cityJson.getString(OWM_CITY_NAME);
    JSONObject coordJSON = cityJson.getJSONObject(OWM_COORD);
    double cityLatitude = coordJSON.getDouble(OWM_COORD_LAT);
    double cityLongitude = coordJSON.getDouble(OWM_COORD_LONG);

    Log.v(LOG_TAG, cityName + ", with coord: " + cityLatitude + " " + cityLongitude);

    // Insert the location into the database.
    long locationID = addLocation(locationSetting, cityName, cityLatitude, cityLongitude);

    // Get and insert the new weather information into the database
    Vector<ContentValues> cVVector = new Vector<ContentValues>(weatherArray.length());

    for (int i = 0; i < weatherArray.length(); i++) {
        // These are the values that will be collected.

        long dateTime;
        double pressure;
        int humidity;
        double windSpeed;
        double windDirection;

        double high;
        double low;

        String description;
        int weatherId;

        // Get the JSON object representing the day
        JSONObject dayForecast = weatherArray.getJSONObject(i);

        // The date/time is returned as a long.  We need to convert that
        // into something human-readable, since most people won't read "1400356800" as
        // "this saturday".
        dateTime = dayForecast.getLong(OWM_DATETIME);

        pressure = dayForecast.getDouble(OWM_PRESSURE);
        humidity = dayForecast.getInt(OWM_HUMIDITY);
        windSpeed = dayForecast.getDouble(OWM_WINDSPEED);
        windDirection = dayForecast.getDouble(OWM_WIND_DIRECTION);

        // Description is in a child array called "weather", which is 1 element long.
        // That element also contains a weather code.
        JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
        description = weatherObject.getString(OWM_DESCRIPTION);
        weatherId = weatherObject.getInt(OWM_WEATHER_ID);

        // Temperatures are in a child object called "temp".  Try not to name variables
        // "temp" when working with temperature.  It confuses everybody.
        JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
        high = temperatureObject.getDouble(OWM_MAX);
        low = temperatureObject.getDouble(OWM_MIN);

        ContentValues weatherValues = new ContentValues();

        weatherValues.put(WeatherEntry.COLUMN_LOC_KEY, locationID);
        weatherValues.put(WeatherEntry.COLUMN_DATETEXT,
                WeatherContract.getDbDateString(new Date(dateTime * 1000L)));
        weatherValues.put(WeatherEntry.COLUMN_HUMIDITY, humidity);
        weatherValues.put(WeatherEntry.COLUMN_PRESSURE, pressure);
        weatherValues.put(WeatherEntry.COLUMN_WIND_SPEED, windSpeed);
        weatherValues.put(WeatherEntry.COLUMN_DEGREES, windDirection);
        weatherValues.put(WeatherEntry.COLUMN_MAX_TEMP, high);
        weatherValues.put(WeatherEntry.COLUMN_MIN_TEMP, low);
        weatherValues.put(WeatherEntry.COLUMN_SHORT_DESC, description);
        weatherValues.put(WeatherEntry.COLUMN_WEATHER_ID, weatherId);

        cVVector.add(weatherValues);

        if (cVVector.size() > 0) {
            ContentValues[] cvArray = new ContentValues[cVVector.size()];
            cVVector.toArray(cvArray);
            int rowsInserted = mContext.getContentResolver().bulkInsert(WeatherEntry.CONTENT_URI, cvArray);
            Log.v(LOG_TAG, "inserted " + rowsInserted + " rows of weather data");
        }

        // Use a DEBUG variable to gate whether or not you do this, so you can easily
        // turn it on and off, and so that it's easy to see what you can rip out if
        // you ever want to remove it.
        if (DEBUG) {
            Cursor weatherCursor = mContext.getContentResolver().query(WeatherEntry.CONTENT_URI, null, null,
                    null, null);

            if (weatherCursor.moveToFirst()) {
                ContentValues resultValues = new ContentValues();
                DatabaseUtils.cursorRowToContentValues(weatherCursor, resultValues);
                Log.v(LOG_TAG, "Query succeeded! **********");
                for (String key : resultValues.keySet()) {
                    Log.v(LOG_TAG, key + ": " + resultValues.getAsString(key));
                }
            } else {
                Log.v(LOG_TAG, "Query failed! :( **********");
            }
        }
    }
}

From source file:edu.mit.mobile.android.locast.data.JsonSyncableItem.java

/**
 * Given a JSON item and a sync map, create a ContentValues map to be inserted into the DB.
 *
 * @param context//  w  w w .  j  a v a2s  .c  om
 * @param localItem will be null if item is new to mobile. If it's been sync'd before, will point to local entry.
 * @param item incoming JSON item.
 * @param mySyncMap A mapping between the JSON object and the content values.
 * @return new ContentValues, ready to be inserted into the database.
 * @throws JSONException
 * @throws IOException
 * @throws NetworkProtocolException
 */
public final static ContentValues fromJSON(Context context, Uri localItem, JSONObject item, SyncMap mySyncMap)
        throws JSONException, IOException, NetworkProtocolException {
    final ContentValues cv = new ContentValues();

    for (final String propName : mySyncMap.keySet()) {
        final SyncItem map = mySyncMap.get(propName);
        if (!map.isDirection(SyncItem.SYNC_FROM)) {
            continue;
        }
        if (map.isOptional() && (!item.has(map.remoteKey) || item.isNull(map.remoteKey))) {
            continue;
        }
        final ContentValues cv2 = map.fromJSON(context, localItem, item, propName);
        if (cv2 != null) {
            cv.putAll(cv2);
        }

    }
    return cv;
}

From source file:com.qualisys.parkassist.FetchWeatherTask.java

/**
 * Take the String representing the complete forecast in JSON Format and
 * pull out the data we need to construct the Strings needed for the wireframes.
 * <p/>/*from   w w  w. j  a v  a 2 s .  c o m*/
 * Fortunately parsing is easy:  constructor takes the JSON string and converts it
 * into an Object hierarchy for us.
 */
private String[] getWeatherDataFromJson(String forecastJsonStr, int numDays, String locationSetting)
        throws JSONException {

    // These are the names of the JSON objects that need to be extracted.

    // Location information
    final String OWM_CITY = "city";
    final String OWM_CITY_NAME = "name";
    final String OWM_COORD = "coord";
    final String OWM_COORD_LAT = "lat";
    final String OWM_COORD_LONG = "lon";

    // Weather information.  Each day's forecast info is an element of the "list" array.
    final String OWM_LIST = "list";

    final String OWM_DATETIME = "dt";
    final String OWM_PRESSURE = "pressure";
    final String OWM_HUMIDITY = "humidity";
    final String OWM_WINDSPEED = "speed";
    final String OWM_WIND_DIRECTION = "deg";

    // All temperatures are children of the "temp" object.
    final String OWM_TEMPERATURE = "temp";
    final String OWM_MAX = "max";
    final String OWM_MIN = "min";

    final String OWM_WEATHER = "weather";
    final String OWM_DESCRIPTION = "main";
    final String OWM_WEATHER_ID = "id";

    JSONObject forecastJson = new JSONObject(forecastJsonStr);
    JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);

    JSONObject cityJson = forecastJson.getJSONObject(OWM_CITY);
    String cityName = cityJson.getString(OWM_CITY_NAME);
    JSONObject coordJSON = cityJson.getJSONObject(OWM_COORD);
    double cityLatitude = coordJSON.getLong(OWM_COORD_LAT);
    double cityLongitude = coordJSON.getLong(OWM_COORD_LONG);

    Log.v(LOG_TAG, cityName + ", with coord: " + cityLatitude + " " + cityLongitude);

    // Insert the location into the database.
    long locationID = addLocation(locationSetting, cityName, cityLatitude, cityLongitude);

    Vector<ContentValues> cVVector = new Vector<ContentValues>(weatherArray.length());
    String[] resultStrs = new String[numDays];

    for (int i = 0; i < weatherArray.length(); i++) {
        // These are the values that will be collected.

        long dateTime;
        double pressure;
        int humidity;
        double windSpeed;
        double windDirection;

        double high;
        double low;

        String description;
        int weatherId;

        // Get the JSON object representing the day
        JSONObject dayForecast = weatherArray.getJSONObject(i);

        // The date/time is returned as a long.  We need to convert that
        // into something human-readable, since most people won't read "1400356800" as
        // "this saturday".
        dateTime = dayForecast.getLong(OWM_DATETIME);

        pressure = dayForecast.getDouble(OWM_PRESSURE);
        humidity = dayForecast.getInt(OWM_HUMIDITY);
        windSpeed = dayForecast.getDouble(OWM_WINDSPEED);
        windDirection = dayForecast.getDouble(OWM_WIND_DIRECTION);

        // Description is in a child array called "weather", which is 1 element long.
        // That element also contains a weather code.
        JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
        description = weatherObject.getString(OWM_DESCRIPTION);
        weatherId = weatherObject.getInt(OWM_WEATHER_ID);

        // Temperatures are in a child object called "temp".  Try not to name variables
        // "temp" when working with temperature.  It confuses everybody.
        JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
        high = temperatureObject.getDouble(OWM_MAX);
        low = temperatureObject.getDouble(OWM_MIN);

        ContentValues weatherValues = new ContentValues();
        /*
                    weatherValues.put(WeatherEntry.COLUMN_LOC_KEY, locationID);
                    weatherValues.put(WeatherEntry.COLUMN_DATETEXT, WeatherContract.getDbDateString(new Date(dateTime * 1000L)));
                    weatherValues.put(WeatherEntry.COLUMN_HUMIDITY, humidity);
                    weatherValues.put(WeatherEntry.COLUMN_PRESSURE, pressure);
                    weatherValues.put(WeatherEntry.COLUMN_WIND_SPEED, windSpeed);
                    weatherValues.put(WeatherEntry.COLUMN_DEGREES, windDirection);
                    weatherValues.put(WeatherEntry.COLUMN_MAX_TEMP, high);
                    weatherValues.put(WeatherEntry.COLUMN_MIN_TEMP, low);
                    weatherValues.put(WeatherEntry.COLUMN_SHORT_DESC, description);
                    weatherValues.put(WeatherEntry.COLUMN_WEATHER_ID, weatherId);
        */
        cVVector.add(weatherValues);

        String highAndLow = formatHighLows(high, low);
        String day = getReadableDateString(dateTime);
        resultStrs[i] = day + " - " + description + " - " + highAndLow;
    }

    ContentValues[] contentValuesToBulkInsert = new ContentValues[cVVector.size()];
    cVVector.toArray(contentValuesToBulkInsert);
    /*
    mContext.getContentResolver().bulkInsert(WeatherEntry.CONTENT_URI, contentValuesToBulkInsert);
    */
    return resultStrs;
}

From source file:com.nbos.phonebook.sync.platform.ContactManager.java

public static void addPhoneNumberToExistingContact(Context context,
        com.nbos.phonebook.sync.client.contact.Phone phone, long rawContactId) {
    Log.i(tag, "Adding phone number " + phone.number);
    if (TextUtils.isEmpty(phone.number))
        return;/* ww w.  jav  a2  s.c o m*/
    ContentValues values = new ContentValues();
    values.put(Phone.RAW_CONTACT_ID, rawContactId);
    values.put(Phone.NUMBER, phone.number);
    int type = phone.getIntType();
    values.put(Phone.TYPE, type);
    if (type == Phone.TYPE_CUSTOM)
        values.put(Phone.DATA3, phone.type);
    values.put(Phone.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
    context.getContentResolver().insert(SyncManager.addCallerIsSyncAdapterParameter(Data.CONTENT_URI), values);
}

From source file:com.zegoggles.smssync.CursorToMessage.java

public ContentValues messageToContentValues(final Message message) throws IOException, MessagingException {
    if (message == null)
        throw new MessagingException("message is null");

    final ContentValues values = new ContentValues();
    switch (getDataType(message)) {
    case SMS://  w  w w . jav a 2s  . c  om
        if (message.getBody() == null)
            throw new MessagingException("body is null");

        InputStream is = message.getBody().getInputStream();
        if (is == null) {
            throw new MessagingException("body.getInputStream() is null for " + message.getBody());
        }
        final String body = IOUtils.toString(is);
        final String address = getHeader(message, Headers.ADDRESS);
        values.put(SmsConsts.BODY, body);
        values.put(SmsConsts.ADDRESS, address);
        values.put(SmsConsts.TYPE, getHeader(message, Headers.TYPE));
        values.put(SmsConsts.PROTOCOL, getHeader(message, Headers.PROTOCOL));
        values.put(SmsConsts.SERVICE_CENTER, getHeader(message, Headers.SERVICE_CENTER));
        values.put(SmsConsts.DATE, getHeader(message, Headers.DATE));
        values.put(SmsConsts.STATUS, getHeader(message, Headers.STATUS));
        values.put(SmsConsts.THREAD_ID, threadHelper.getThreadId(mContext, address));
        values.put(SmsConsts.READ,
                PrefStore.getMarkAsReadOnRestore(mContext) ? "1" : getHeader(message, Headers.READ));
        break;
    case CALLLOG:
        values.put(CallLog.Calls.NUMBER, getHeader(message, Headers.ADDRESS));
        values.put(CallLog.Calls.TYPE, Integer.valueOf(getHeader(message, Headers.TYPE)));
        values.put(CallLog.Calls.DATE, getHeader(message, Headers.DATE));
        values.put(CallLog.Calls.DURATION, Long.valueOf(getHeader(message, Headers.DURATION)));
        values.put(CallLog.Calls.NEW, 0);

        PersonRecord record = lookupPerson(getHeader(message, Headers.ADDRESS));
        if (!record.unknown) {
            values.put(CallLog.Calls.CACHED_NAME, record.name);
            values.put(CallLog.Calls.CACHED_NUMBER_TYPE, -2);
        }

        break;
    default:
        throw new MessagingException("don't know how to restore " + getDataType(message));
    }

    return values;
}

From source file:com.example.android.touroflondon.data.TourDbHelper.java

/**
 * Extract Route data from a {@link JSONArray} of save it in the database.
 *
 * @param data//from   w  w  w  . j  ava  2s.co  m
 */
public void loadRoute(JSONArray data) throws JSONException {

    SQLiteDatabase db = this.getWritableDatabase();

    // Empty the route table to remove all existing data
    db.delete(TourContract.RouteEntry.TABLE_NAME, null, null);

    // Need to complete transaction first to clear data
    db.close();

    // Begin the insert transaction
    db = this.getWritableDatabase();
    db.beginTransaction();

    // Loop over each location in array
    for (int i = 0; i < data.length(); i++) {
        // extract data
        JSONObject poi = data.getJSONObject(i);
        final double lat = poi.getDouble("lat");
        final double lng = poi.getDouble("lng");

        // Construct insert statement
        ContentValues cv = new ContentValues();
        cv.put(TourContract.RouteEntry.COLUMN_NAME_LAT, lat);
        cv.put(TourContract.RouteEntry.COLUMN_NAME_LNG, lng);

        // Insert data
        db.insert(TourContract.RouteEntry.TABLE_NAME, null, cv);
    }

    if (db != null) {
        // All insert statement have been submitted, mark transaction as successful
        db.setTransactionSuccessful();
        db.endTransaction();
    }
}

From source file:tk.android.client.activity.Activity_client.java

@Override
public void onClick(View v) {
    switch (v.getId()) {
    case R.id.button_version: {
        try {//from  w w  w . j  a va 2s. co  m
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(PLAY_STORE_URL)));
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
        }
        break;
    }
    case R.id.layout_support: {
        startActivity(new Intent(activity, Activity_user.class)
                .setData(Uri.parse("https://twitter.com/OrangeSphereApp")));
        break;
    }
    case R.id.layout_pro: {
        if (PropertyManager.getInstance().isProUser()) {
            Toast.makeText(activity, "You alreadry Pro User :)", Toast.LENGTH_SHORT).show();
            break;
        }
        String TAG = "EditDialog-Pro";
        final EditDialog dialog = new EditDialog();
        dialog.newInstance(activity);
        dialog.setTitle(R.string.advertisement);
        dialog.setOnFinishEditListener(new OnFinishEditListener() {

            @Override
            public void onFinishEdit(final String text) {
                int length = text.length();
                if (length > 100 || length == 0) {
                    Toast.makeText(activity, R.string.bad_string_length, Toast.LENGTH_SHORT).show();
                    return;
                }
                dialog.dismiss();
                new Thread(new Runnable() {

                    @Override
                    public void run() {
                        try {
                            Twitter twitter = core.getTwitter();
                            if (twitter == null) {
                                throw new Exception();
                            }
                            twitter.updateStatus(text + " " + PLAY_STORE_URL + " #OrangeSphere");
                            PropertyManager.getInstance().toBeProUser();
                            SQLiteManager manager = new SQLiteManager(activity);
                            SQLiteDatabase db = manager.getWritableDatabase();
                            ContentValues values = new ContentValues();
                            values.put("client_name", "OrangeSpherePro");
                            values.put("consumer_key", "b1NEqKgA8CGudo6yhkg");
                            values.put("consumer_secret", "awqnQwi3BXUqkyjlMZHlDIvad3bV3cVO03MxRTV4s");
                            db.insert("client_table", null, values);
                            db.close();
                            new UiHandler() {

                                @Override
                                public void run() {
                                    Toast.makeText(activity, R.string.be_pro_user, Toast.LENGTH_SHORT).show();
                                }

                            }.post();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                }).start();
            }

        });
        dialog.show(getSupportFragmentManager(), TAG);
        break;
    }
    case R.id.layout_license: {
        new LicenseDialog().show(getSupportFragmentManager(), "LicenseDialog");
        break;
    }
    }
}

From source file:org.opendatakit.tables.utils.WebViewUtil.java

/**
 * Turn the map into a {@link ContentValues} object. Returns null if any of
 * the element keys do not exist in the table, or if the value cannot be
 * parsed to the type of the column./*from w w w . j  a v a 2 s  . co m*/
 *
 * @param context
 * @param appName
 * @param tableId
 * @param orderedDefns
 * @param elementKeyToValue
 * @return
 * @throws ServicesAvailabilityException
 */
public static ContentValues getContentValuesFromMap(Context context, String appName, String tableId,
        OrderedColumns orderedDefns, Map<String, String> elementKeyToValue)
        throws ServicesAvailabilityException {
    // Note that we're not currently
    // going to handle complex types or those that map to a json value. We
    // could, but we'd probably have to have a known entity do the conversions
    // for us somehow on the js side, rather than expect the caller to craft up
    // whatever format we've landed on for pictures.
    // This will contain the values we're going to insert into the database.
    ContentValues result = new ContentValues();
    // TODO: respect locale and timezone. Getting this structure from other
    // places it is used.

    DateUtils dataUtil = new DateUtils(Locale.ENGLISH, TimeZone.getDefault());
    for (Map.Entry<String, String> entry : elementKeyToValue.entrySet()) {
        String elementKey = entry.getKey();
        String rawValue = entry.getValue();
        // Get the column so we know what type we need to handle.
        ColumnDefinition columnDefn = orderedDefns.find(elementKey);
        if (columnDefn == null) {
            // uh oh, no column for the given id. problem on the part of the caller
            WebLogger.getLogger(appName).e(TAG,
                    "[addRow] could not find column for element key: " + elementKey);
            return null;
        }
        ElementType columnType = columnDefn.getType();
        boolean parsedSuccessfully = addValueToContentValues(context, appName, tableId, dataUtil, columnDefn,
                rawValue, result);
        if (!parsedSuccessfully) {
            WebLogger.getLogger(appName).e(TAG,
                    "[addRow] could not parse value: " + rawValue + " for column type " + columnType);
            return null;
        }
    }
    return result;
}

From source file:com.openerp.addons.messages.MessageSyncHelper.java

private JSONArray updateMessageStatus(JSONObject msgReplies, BaseDBHelper db) {
    JSONArray updatedIds = new JSONArray();
    try {/*from   w  ww. jav  a2s. co m*/
        for (int j = 0; j < msgReplies.getJSONArray("records").length(); j++) {
            JSONObject objRes = msgReplies.getJSONArray("records").getJSONObject(j);
            String message_id = objRes.getJSONArray("message_id").getString(0);
            String read = (objRes.getString("read").equals("true")) ? "false" : "true";
            String starred = objRes.getString("starred");
            ContentValues values = new ContentValues();
            values.put("starred", starred);
            values.put("to_read", read);
            if (db.write(db, values, Integer.parseInt(message_id), true)) {
                updatedIds.put(Integer.parseInt(message_id));
            }

        }
    } catch (Exception e) {
    }
    return updatedIds;
}