Example usage for android.content ContentValues put

List of usage examples for android.content ContentValues put

Introduction

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

Prototype

public void put(String key, byte[] value) 

Source Link

Document

Adds a value to the set.

Usage

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

/**
 * Extract POI data from a {@link JSONArray} of points of interest and add it to the POI table.
 *
 * @param data/*from www.  ja va  2  s  .c o m*/
 */
public void loadPois(JSONArray data) throws JSONException {

    SQLiteDatabase db = this.getWritableDatabase();

    // empty the POI table to remove all existing data
    db.delete(TourContract.PoiEntry.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 point of interest in array
    for (int i = 0; i < DataStore.getAllCoupons().size(); i++) {
        Coupon coupon = DataStore.getAllCoupons().get(i);
        //Extract POI properties
        final String storeName = coupon.getStoreName();
        String details = coupon.getTitle();
        details = details.replace("<h1>", "").replace("</h1>", "");

        final Double lat = coupon.getLatitude();
        final Double lng = coupon.getLongitude();
        /* 
        /final String type = poi.getString("type");
         final String description = poi.getString("description");
         final String pictureUrl = poi.getString("pictureUrl");
         final String pictureAttr = poi.getString("pictureAttr");
                
         // Location
         JSONObject location = poi.getJSONObject("location");
         final double lat = location.getDouble("lat");
         final double lng = location.getDouble("lng");
         */
        // Create content values object for insert
        ContentValues cv = new ContentValues();
        cv.put(TourContract.PoiEntry.COLUMN_NAME_TITLE, storeName);
        cv.put(TourContract.PoiEntry.COLUMN_NAME_TYPE, "LANDMARK");
        cv.put(TourContract.PoiEntry.COLUMN_NAME_DESCRIPTION, details);
        cv.put(TourContract.PoiEntry.COLUMN_NAME_LOCATION_LAT, lat);
        cv.put(TourContract.PoiEntry.COLUMN_NAME_LOCATION_LNG, lng);

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

    // All insert statement have been submitted, mark transaction as successful
    db.setTransactionSuccessful();

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

}

From source file:company.test.Test.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    switch (id) {
    case R.id.add_item:
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Add a task");
        builder.setMessage("What do you want to do?");
        final EditText inputField = new EditText(this);
        builder.setView(inputField);/*from  w w w .  ja  va  2  s .  c  om*/
        builder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                String task = inputField.getText().toString();
                Log.d("MainActivity", task);

                SQLiteDatabase db = helper.getWritableDatabase();
                ContentValues values = new ContentValues();

                values.clear();
                values.put(ItemContract.Columns.ITEM, task);

                db.insertWithOnConflict(ItemContract.TABLE, null, values, SQLiteDatabase.CONFLICT_IGNORE);

                activity.updateUI();
            }
        });

        builder.setNegativeButton("Cancel", null);

        builder.create().show();
        return true;
    case R.id.action_settings:
        Log.d("MainActivity", "Settings");
        return true;
    default:
        return false;
    }
}

From source file:com.android.providers.contacts.ContactsSyncAdapter.java

protected static void updateProviderWithGroupEntry(String account, Long syncLocalId, GroupEntry entry,
        ContentProvider provider) throws ParseException {
    ContentValues values = new ContentValues();
    values.put(Groups.NAME, entry.getTitle());
    values.put(Groups.NOTES, entry.getContent());
    values.put(Groups.SYSTEM_ID, entry.getSystemGroup());
    values.put(Groups._SYNC_ACCOUNT, account);
    values.put(Groups._SYNC_ID, lastItemFromUri(entry.getId()));
    values.put(Groups._SYNC_DIRTY, 0);//from www .j  a  v  a 2 s  .c  o m
    values.put(Groups._SYNC_LOCAL_ID, syncLocalId);
    final String editUri = entry.getEditUri();
    final String syncVersion = editUri == null ? null : lastItemFromUri(editUri);
    values.put(Groups._SYNC_TIME, syncVersion);
    values.put(Groups._SYNC_VERSION, syncVersion);
    provider.insert(Groups.CONTENT_URI, values);
}

From source file:gov.wa.wsdot.android.wsdot.service.HighwayAlertsSyncService.java

@SuppressLint("SimpleDateFormat")
@Override//from ww  w .ja  v  a 2s .c om
protected void onHandleIntent(Intent intent) {
    ContentResolver resolver = getContentResolver();
    Cursor cursor = null;
    long now = System.currentTimeMillis();
    boolean shouldUpdate = true;
    String responseString = "";
    DateFormat dateFormat = new SimpleDateFormat("MMMM d, yyyy h:mm a");

    /** 
     * Check the cache table for the last time data was downloaded. If we are within
     * the allowed time period, don't sync, otherwise get fresh data from the server.
     */
    try {
        cursor = resolver.query(Caches.CONTENT_URI, projection, Caches.CACHE_TABLE_NAME + " LIKE ?",
                new String[] { "highway_alerts" }, null);

        if (cursor != null && cursor.moveToFirst()) {
            long lastUpdated = cursor.getLong(0);
            //long deltaMinutes = (now - lastUpdated) / DateUtils.MINUTE_IN_MILLIS;
            //Log.d(DEBUG_TAG, "Delta since last update is " + deltaMinutes + " min");
            shouldUpdate = (Math.abs(now - lastUpdated) > (5 * DateUtils.MINUTE_IN_MILLIS));
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }

    // Tapping the refresh button will force a data refresh.
    boolean forceUpdate = intent.getBooleanExtra("forceUpdate", false);

    if (shouldUpdate || forceUpdate) {

        try {
            URL url = new URL(HIGHWAY_ALERTS_URL);
            URLConnection urlConn = url.openConnection();

            BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
            String jsonFile = "";
            String line;

            while ((line = in.readLine()) != null) {
                jsonFile += line;
            }

            in.close();

            JSONObject obj = new JSONObject(jsonFile);
            JSONObject result = obj.getJSONObject("alerts");
            JSONArray items = result.getJSONArray("items");
            List<ContentValues> alerts = new ArrayList<ContentValues>();

            int numItems = items.length();
            for (int j = 0; j < numItems; j++) {
                JSONObject item = items.getJSONObject(j);
                JSONObject startRoadwayLocation = item.getJSONObject("StartRoadwayLocation");
                ContentValues alertData = new ContentValues();

                alertData.put(HighwayAlerts.HIGHWAY_ALERT_ID, item.getString("AlertID"));
                alertData.put(HighwayAlerts.HIGHWAY_ALERT_HEADLINE, item.getString("HeadlineDescription"));
                alertData.put(HighwayAlerts.HIGHWAY_ALERT_CATEGORY, item.getString("EventCategory"));
                alertData.put(HighwayAlerts.HIGHWAY_ALERT_PRIORITY, item.getString("Priority"));
                alertData.put(HighwayAlerts.HIGHWAY_ALERT_LATITUDE, startRoadwayLocation.getString("Latitude"));
                alertData.put(HighwayAlerts.HIGHWAY_ALERT_LONGITUDE,
                        startRoadwayLocation.getString("Longitude"));
                alertData.put(HighwayAlerts.HIGHWAY_ALERT_ROAD_NAME,
                        startRoadwayLocation.getString("RoadName"));
                alertData.put(HighwayAlerts.HIGHWAY_ALERT_LAST_UPDATED, dateFormat
                        .format(new Date(Long.parseLong(item.getString("LastUpdatedTime").substring(6, 19)))));

                alerts.add(alertData);
            }

            // Purge existing highway alerts covered by incoming data
            resolver.delete(HighwayAlerts.CONTENT_URI, null, null);
            // Bulk insert all the new highway alerts
            resolver.bulkInsert(HighwayAlerts.CONTENT_URI, alerts.toArray(new ContentValues[alerts.size()]));
            // Update the cache table with the time we did the update
            ContentValues values = new ContentValues();
            values.put(Caches.CACHE_LAST_UPDATED, System.currentTimeMillis());
            resolver.update(Caches.CONTENT_URI, values, Caches.CACHE_TABLE_NAME + " LIKE ?",
                    new String[] { "highway_alerts" });

            responseString = "OK";
        } catch (Exception e) {
            Log.e(DEBUG_TAG, "Error: " + e.getMessage());
            responseString = e.getMessage();
        }
    } else {
        responseString = "NOP";
    }

    Intent broadcastIntent = new Intent();
    broadcastIntent.setAction("gov.wa.wsdot.android.wsdot.intent.action.HIGHWAY_ALERTS_RESPONSE");
    broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
    broadcastIntent.putExtra("responseString", responseString);
    sendBroadcast(broadcastIntent);
}

From source file:com.google.android.net.GoogleHttpClient.java

/** Execute a request without applying and rewrite rules. */
public HttpResponse executeWithoutRewriting(HttpUriRequest request, HttpContext context) throws IOException {
    String code = "Error";
    long start = SystemClock.elapsedRealtime();
    try {/*from   ww  w. j a v  a  2 s.co  m*/
        HttpResponse response = mClient.execute(request, context);
        code = Integer.toString(response.getStatusLine().getStatusCode());
        return response;
    } catch (IOException e) {
        code = "IOException";
        throw e;
    } finally {
        // Record some statistics to the checkin service about the outcome.
        // Note that this is only describing execute(), not body download.
        try {
            long elapsed = SystemClock.elapsedRealtime() - start;
            ContentValues values = new ContentValues();
            values.put(Checkin.Stats.TAG, Checkin.Stats.Tag.HTTP_STATUS + ":" + mUserAgent + ":" + code);
            values.put(Checkin.Stats.COUNT, 1);
            values.put(Checkin.Stats.SUM, elapsed / 1000.0);
            mResolver.insert(Checkin.Stats.CONTENT_URI, values);
        } catch (Exception e) {
            Log.e(TAG, "Error recording stats", e);
        }
    }
}

From source file:com.mobeelizer.mobile.android.types.FileFieldTypeHelper.java

@Override
protected void setNullValueFromEntityToDatabase(final ContentValues values, final MobeelizerFieldAccessor field,
        final Map<String, String> options, final MobeelizerErrorsBuilder errors) {
    values.put(field.getName() + _GUID, (String) null);
    values.put(field.getName() + _NAME, (String) null);
}

From source file:com.mobeelizer.mobile.android.types.FileFieldTypeHelper.java

@Override
protected void setNullValueFromMapToDatabase(final ContentValues values, final MobeelizerFieldAccessor field,
        final Map<String, String> options, final MobeelizerErrorsBuilder errors) {
    values.put(field.getName() + _GUID, (String) null);
    values.put(field.getName() + _NAME, (String) null);
}

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

/**
 * Called when message is received./*ww w.  j av  a  2  s.  c  o m*/
 *
 * @param from SenderID of the sender.
 * @param data Data bundle containing message data as key/value pairs.
 *             For Set of keys use data.keySet().
 */
// [START receive_message]
@Override
public void onMessageReceived(String from, Bundle data) {
    String message = data.getString("message");
    Log.d(LOG_TAG, "From: " + from);
    Log.d(LOG_TAG, "Message: " + message);

    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    boolean enableTempNotifications = sharedPreferences
            .getBoolean(getString(R.string.pref_enable_temp_notifications_key), Boolean.parseBoolean("true"));
    boolean enableHumidityNotifications = sharedPreferences.getBoolean(
            getString(R.string.pref_enable_humidity_notifications_key), Boolean.parseBoolean("true"));
    boolean notifyUser = false;

    String tag = null;
    double temp = 0;
    double humidity = 0;
    double latitude = 0;
    double longitude = 0;
    String dateString = null;
    StringBuilder msg = new StringBuilder();
    try {
        JSONObject json = new JSONObject(message);
        if (!json.isNull(STATION_TAG)) {
            tag = json.getString(STATION_TAG);
            msg.append(tag);
        } else
            throw new IllegalArgumentException("station tag is required");

        if (!json.isNull(CONDITION_DATE))
            dateString = json.getString(CONDITION_DATE);
        else
            throw new IllegalArgumentException("date is required");

        if (msg.length() > 0)
            msg.append(" -");

        if (!json.isNull(CONDITION_TEMP)) {
            notifyUser |= enableTempNotifications;
            temp = json.getDouble(CONDITION_TEMP);
            msg.append(" temp: " + getString(R.string.format_temperature, temp));
        }
        if (!json.isNull(CONDITION_HUMIDITY)) {
            notifyUser |= enableHumidityNotifications;
            humidity = json.getDouble(CONDITION_HUMIDITY);
            msg.append(" humidity: " + getString(R.string.format_humidity, humidity));
        }
        if (!json.isNull(CONDITION_LAT)) {
            latitude = json.getDouble(CONDITION_LAT);
        }
        if (!json.isNull(CONDITION_LONG)) {
            longitude = json.getDouble(CONDITION_LONG);
        }
    } catch (JSONException e) {
        Log.e(LOG_TAG, "error parsing GCM message JSON", e);
    }

    long stationId = addStation(tag);
    Date date = Utility.parseDateDb(dateString);
    ContentValues conditionValues = new ContentValues();
    conditionValues.put(StationContract.ConditionEntry.COLUMN_STATION_KEY, stationId);
    conditionValues.put(StationContract.ConditionEntry.COLUMN_TEMP, temp);
    conditionValues.put(StationContract.ConditionEntry.COLUMN_HUMIDITY, humidity);
    conditionValues.put(StationContract.ConditionEntry.COLUMN_LATITUDE, latitude);
    conditionValues.put(StationContract.ConditionEntry.COLUMN_LONGITUDE, longitude);
    conditionValues.put(StationContract.ConditionEntry.COLUMN_DATE, date != null ? date.getTime() : 0);
    getContentResolver().insert(StationContract.ConditionEntry.CONTENT_URI, conditionValues);

    /**
     * show a notification indicating to the user that a message was received.
     */
    if (notifyUser)
        sendNotification(msg.toString());
}

From source file:com.easemob.chatuidemo.adapter.NewFriendsMsgAdapter.java

/**
 * ???/*www .  j  av  a 2 s . c  om*/
 *
 * @param button
 * @param username
 */
public void acceptInvitation(final Button button, final InviteMessage msg) {
    final ProgressDialog pd = new ProgressDialog(context);
    String str1 = context.getResources().getString(R.string.Are_agree_with);
    final String str2 = context.getResources().getString(R.string.Has_agreed_to);
    final String str3 = context.getResources().getString(R.string.Agree_with_failure);
    pd.setMessage(str1);
    pd.setCanceledOnTouchOutside(false);
    pd.show();

    RequestQueue requestQueue = Volley.newRequestQueue(context);

    requestQueue.start();

    requestQueue.add(new AutoLoginRequest(context, Request.Method.POST, Model.PathLoad,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    pd.dismiss();
                    button.setText(str2);
                    msg.setStatus(InviteMesageStatus.AGREED);
                    // db
                    ContentValues values = new ContentValues();
                    values.put(InviteMessgeDao.COLUMN_NAME_STATUS, msg.getStatus().ordinal());
                    messgeDao.updateMessage(msg.getId(), values);
                    button.setBackgroundDrawable(null);
                    button.setEnabled(false);

                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(context, str3 + error.getMessage(), 1).show();

                }
            }) {
        @Override
        protected void setParams(Map<String, String> params) {
            if (msg.getGroupId() == null) {//???
                params.put("sys", "msg");
                params.put("ctrl", "msger");
                params.put("action", "add_friend");
                params.put("friend_name", msg.getFrom());
            } else //??
            {
                params.put("sys", "msg");
                params.put("ctrl", "msger");
                params.put("action", "agree_group");
                params.put("stranger", msg.getFrom());
                params.put("group_sn", msg.getGroupId());
            }

        }
    });
}

From source file:gov.nasa.arc.geocam.geocam.CameraPreviewActivity.java

private void saveWithAnnotation() {
    try {/* w w  w . java  2s . co  m*/
        mImageData.put("tag", mImageTag);
        mImageData.put("note", mImageNote);
        Log.d(GeoCamMobile.DEBUG_ID, "Saving image with data: " + mImageData.toString());
    } catch (JSONException e) {
        Log.d(GeoCamMobile.DEBUG_ID, "Error while adding annotation to image");
    }

    ContentValues values = new ContentValues();
    values.put(MediaStore.Images.Media.DESCRIPTION, mImageData.toString());
    getContentResolver().update(mImageUri, values, null, null);
    Log.d(GeoCamMobile.DEBUG_ID, "Updating " + mImageUri.toString() + " with values " + values.toString());

    // Add image URI to upload queue
    try {
        mService.addToUploadQueue(mImageUri.toString());
    } catch (RemoteException e) {
        Log.d(GeoCamMobile.DEBUG_ID,
                "Error talking to upload service while adding uri: " + mImageUri.toString() + " - " + e);
    }

    this.finish();
}