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.ccghe.emocha.model.DBAdapter.java

private static ContentValues getValues(long ts, long size, String md5, boolean delete, boolean download) {
    ContentValues values = new ContentValues();
    values.put("ts", ts);
    values.put("size", size);
    values.put("md5", md5);
    values.put("to_delete", delete ? 1 : 0);
    values.put("to_download", download ? 1 : 0);
    return values;
}

From source file:com.granita.icloudcalsync.resource.LocalCalendar.java

@SuppressLint("InlinedApi")
public static Uri create(Account account, ContentResolver resolver, ServerInfo.ResourceInfo info)
        throws LocalStorageException {
    final ContentProviderClient client = resolver.acquireContentProviderClient(CalendarContract.AUTHORITY);
    if (client == null)
        throw new LocalStorageException("No Calendar Provider found (Calendar app disabled?)");

    ContentValues values = new ContentValues();
    values.put(Calendars.ACCOUNT_NAME, account.name);
    values.put(Calendars.ACCOUNT_TYPE, account.type);
    values.put(Calendars.NAME, info.getURL());
    values.put(Calendars.CALENDAR_DISPLAY_NAME, info.getTitle());
    values.put(Calendars.CALENDAR_COLOR, DAVUtils.CalDAVtoARGBColor(info.getColor()));
    values.put(Calendars.OWNER_ACCOUNT, account.name);
    values.put(Calendars.SYNC_EVENTS, 1);
    values.put(Calendars.VISIBLE, 1);/*from   ww  w  .j av  a 2 s .c  om*/
    values.put(Calendars.ALLOWED_REMINDERS, Reminders.METHOD_ALERT);

    if (info.isReadOnly())
        values.put(Calendars.CALENDAR_ACCESS_LEVEL, Calendars.CAL_ACCESS_READ);
    else {
        values.put(Calendars.CALENDAR_ACCESS_LEVEL, Calendars.CAL_ACCESS_OWNER);
        values.put(Calendars.CAN_ORGANIZER_RESPOND, 1);
        values.put(Calendars.CAN_MODIFY_TIME_ZONE, 1);
    }

    if (android.os.Build.VERSION.SDK_INT >= 15) {
        values.put(Calendars.ALLOWED_AVAILABILITY, Events.AVAILABILITY_BUSY + "," + Events.AVAILABILITY_FREE
                + "," + Events.AVAILABILITY_TENTATIVE);
        values.put(Calendars.ALLOWED_ATTENDEE_TYPES, Attendees.TYPE_NONE + "," + Attendees.TYPE_OPTIONAL + ","
                + Attendees.TYPE_REQUIRED + "," + Attendees.TYPE_RESOURCE);
    }

    if (info.getTimezone() != null)
        values.put(Calendars.CALENDAR_TIME_ZONE, info.getTimezone());

    Log.i(TAG, "Inserting calendar: " + values.toString());
    try {
        return client.insert(calendarsURI(account), values);
    } catch (RemoteException e) {
        throw new LocalStorageException(e);
    }
}

From source file:com.mpower.mintel.android.tasks.DownloadFormsTask.java

@Override
protected HashMap<String, String> doInBackground(ArrayList<FormDetails>... values) {
    ArrayList<FormDetails> toDownload = values[0];

    int total = toDownload.size();
    int count = 1;

    HashMap<String, String> result = new HashMap<String, String>();

    for (int i = 0; i < total; i++) {
        FormDetails fd = toDownload.get(i);
        publishProgress(fd.formName, Integer.valueOf(count).toString(), Integer.valueOf(total).toString());

        String message = "";

        try {/*w ww  .java 2 s  . c  om*/
            // get the xml file
            // if we've downloaded a duplicate, this gives us the file
            File dl = downloadXform(fd.formName, fd.downloadUrl);

            String[] projection = { FormsColumns._ID, FormsColumns.FORM_FILE_PATH };
            String[] selectionArgs = { dl.getAbsolutePath() };
            String selection = FormsColumns.FORM_FILE_PATH + "=?";
            Cursor alreadyExists = MIntel.getInstance().getContentResolver().query(FormsColumns.CONTENT_URI,
                    projection, selection, selectionArgs, null);

            Uri uri = null;
            if (alreadyExists.getCount() <= 0) {
                // doesn't exist, so insert it
                ContentValues v = new ContentValues();
                v.put(FormsColumns.FORM_FILE_PATH, dl.getAbsolutePath());

                HashMap<String, String> formInfo = FileUtils.parseXML(dl);
                v.put(FormsColumns.DISPLAY_NAME, formInfo.get(FileUtils.TITLE));
                v.put(FormsColumns.MODEL_VERSION, formInfo.get(FileUtils.MODEL));
                v.put(FormsColumns.UI_VERSION, formInfo.get(FileUtils.UI));
                v.put(FormsColumns.JR_FORM_ID, formInfo.get(FileUtils.FORMID));
                v.put(FormsColumns.SUBMISSION_URI, formInfo.get(FileUtils.SUBMISSIONURI));
                uri = MIntel.getInstance().getContentResolver().insert(FormsColumns.CONTENT_URI, v);
            } else {
                alreadyExists.moveToFirst();
                uri = Uri.withAppendedPath(FormsColumns.CONTENT_URI,
                        alreadyExists.getString(alreadyExists.getColumnIndex(FormsColumns._ID)));
            }

            if (fd.manifestUrl != null) {
                Cursor c = MIntel.getInstance().getContentResolver().query(uri, null, null, null, null);
                if (c.getCount() > 0) {
                    // should be exactly 1
                    c.moveToFirst();

                    String error = downloadManifestAndMediaFiles(
                            c.getString(c.getColumnIndex(FormsColumns.FORM_MEDIA_PATH)), fd, count, total);
                    if (error != null) {
                        message += error;
                    }
                }
            } else {
                // TODO: manifest was null?
                Log.e(t, "Manifest was null.  PANIC");
            }
        } catch (SocketTimeoutException se) {
            se.printStackTrace();
            message += se.getMessage();
        } catch (Exception e) {
            e.printStackTrace();
            if (e.getCause() != null) {
                message += e.getCause().getMessage();
            } else {
                message += e.getMessage();
            }
        }
        count++;
        if (message.equalsIgnoreCase("")) {
            message = MIntel.getInstance().getString(R.string.success);
        }
        result.put(fd.formName, message);
    }

    return result;
}

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

@SuppressLint("SimpleDateFormat")
@Override// w w  w .ja v a2 s. c o m
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.citrus.sdk.database.DBHandler.java

public int setDefaultOption(String optionName) {
    String whereValues[] = new String[] { optionName };
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues newValues = new ContentValues();

    if (!TextUtils.isEmpty(optionName)) {
        try {/*w w  w.ja va2s  .c o  m*/
            newValues.put(DEFAULT_OPTION, 1);
            return db.update(PAYOPTION_TABLE, newValues, NAME + "=?", whereValues);
        } catch (Exception e) {
            db.close();
            return 0;
        }

    } else {
        try {
            newValues.put(DEFAULT_OPTION, 0);
            return db.update(PAYOPTION_TABLE, newValues, null, null);
        } catch (Exception e) {
            db.close();
            return 0;
        }

    }
}

From source file:at.bitfire.davdroid.resource.LocalCalendar.java

@SuppressLint("InlinedApi")
public static Uri create(Account account, ContentResolver resolver, ServerInfo.ResourceInfo info)
        throws LocalStorageException {
    @Cleanup("release")
    final ContentProviderClient client = resolver.acquireContentProviderClient(CalendarContract.AUTHORITY);
    if (client == null)
        throw new LocalStorageException("No Calendar Provider found (Calendar app disabled?)");

    ContentValues values = new ContentValues();
    values.put(Calendars.ACCOUNT_NAME, account.name);
    values.put(Calendars.ACCOUNT_TYPE, account.type);
    values.put(Calendars.NAME, info.getURL());
    values.put(Calendars.CALENDAR_DISPLAY_NAME, info.getTitle());
    values.put(Calendars.CALENDAR_COLOR, info.getColor() != null ? info.getColor() : DAVUtils.calendarGreen);
    values.put(Calendars.OWNER_ACCOUNT, account.name);
    values.put(Calendars.SYNC_EVENTS, 1);
    values.put(Calendars.VISIBLE, 1);/*  www.j  a  v a2s  . c om*/
    values.put(Calendars.ALLOWED_REMINDERS, Reminders.METHOD_ALERT);

    if (info.isReadOnly())
        values.put(Calendars.CALENDAR_ACCESS_LEVEL, Calendars.CAL_ACCESS_READ);
    else {
        values.put(Calendars.CALENDAR_ACCESS_LEVEL, Calendars.CAL_ACCESS_OWNER);
        values.put(Calendars.CAN_ORGANIZER_RESPOND, 1);
        values.put(Calendars.CAN_MODIFY_TIME_ZONE, 1);
    }

    if (android.os.Build.VERSION.SDK_INT >= 15) {
        values.put(Calendars.ALLOWED_AVAILABILITY, Events.AVAILABILITY_BUSY + "," + Events.AVAILABILITY_FREE
                + "," + Events.AVAILABILITY_TENTATIVE);
        values.put(Calendars.ALLOWED_ATTENDEE_TYPES, Attendees.TYPE_NONE + "," + Attendees.TYPE_OPTIONAL + ","
                + Attendees.TYPE_REQUIRED + "," + Attendees.TYPE_RESOURCE);
    }

    if (info.getTimezone() != null)
        values.put(Calendars.CALENDAR_TIME_ZONE, DateUtils.findAndroidTimezoneID(info.getTimezone()));

    Log.i(TAG, "Inserting calendar: " + values.toString());
    try {
        return client.insert(calendarsURI(account), values);
    } catch (RemoteException e) {
        throw new LocalStorageException(e);
    }
}

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

@Override
protected void onHandleIntent(Intent intent) {
    ContentResolver resolver = getContentResolver();
    Cursor cursor = null;/*from w  ww. j a va2 s  .co  m*/
    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, new String[] { Caches.CACHE_LAST_UPDATED },
                Caches.CACHE_TABLE_NAME + " LIKE ?", new String[] { "ferries_schedules" }, 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) > (30 * DateUtils.MINUTE_IN_MILLIS));
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }

    // Ability to force a refresh of camera data.
    boolean forceUpdate = intent.getBooleanExtra("forceUpdate", false);

    if (shouldUpdate || forceUpdate) {
        List<Integer> starred = new ArrayList<Integer>();

        starred = getStarred();

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

            BufferedInputStream bis = new BufferedInputStream(urlConn.getInputStream());
            GZIPInputStream gzin = new GZIPInputStream(bis);
            InputStreamReader is = new InputStreamReader(gzin);
            BufferedReader in = new BufferedReader(is);

            String jsonFile = "";
            String line;

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

            JSONArray items = new JSONArray(jsonFile);
            List<ContentValues> schedules = new ArrayList<ContentValues>();

            int numItems = items.length();
            for (int i = 0; i < numItems; i++) {
                JSONObject item = items.getJSONObject(i);
                ContentValues schedule = new ContentValues();
                schedule.put(FerriesSchedules.FERRIES_SCHEDULE_ID, item.getInt("RouteID"));
                schedule.put(FerriesSchedules.FERRIES_SCHEDULE_TITLE, item.getString("Description"));
                schedule.put(FerriesSchedules.FERRIES_SCHEDULE_DATE, item.getString("Date"));
                schedule.put(FerriesSchedules.FERRIES_SCHEDULE_ALERT, item.getString("RouteAlert"));
                schedule.put(FerriesSchedules.FERRIES_SCHEDULE_UPDATED, dateFormat
                        .format(new Date(Long.parseLong(item.getString("CacheDate").substring(6, 19)))));

                if (starred.contains(item.getInt("RouteID"))) {
                    schedule.put(FerriesSchedules.FERRIES_SCHEDULE_IS_STARRED, 1);
                }

                schedules.add(schedule);
            }

            // Purge existing travel times covered by incoming data
            resolver.delete(FerriesSchedules.CONTENT_URI, null, null);
            // Bulk insert all the new travel times
            resolver.bulkInsert(FerriesSchedules.CONTENT_URI,
                    schedules.toArray(new ContentValues[schedules.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 + "=?",
                    new String[] { "ferries_schedules" });

            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.FERRIES_SCHEDULES_RESPONSE");
    broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
    broadcastIntent.putExtra("responseString", responseString);
    sendBroadcast(broadcastIntent);

}

From source file:edu.stanford.mobisocial.dungbeetle.Helpers.java

public static void updateGroupVersion(final Context c, final long groupId, final int version) {
    Uri url = Uri.parse(DungBeetleContentProvider.CONTENT_URI + "/groups");
    ContentValues values = new ContentValues();
    values.put(Group.VERSION, version);
    c.getContentResolver().update(url, values, Group._ID + "=" + groupId, null);
}

From source file:at.bitfire.davdroid.mirakel.resource.LocalCalendar.java

@SuppressLint("InlinedApi")
public static void create(Account account, ContentResolver resolver, ServerInfo.ResourceInfo info)
        throws LocalStorageException {
    ContentProviderClient client = resolver.acquireContentProviderClient(CalendarContract.AUTHORITY);
    if (client == null)
        throw new LocalStorageException("No Calendar Provider found (Calendar app disabled?)");

    int color = 0xFFC3EA6E; // fallback: "DAVdroid green"
    if (info.getColor() != null) {
        Pattern p = Pattern.compile("#(\\p{XDigit}{6})(\\p{XDigit}{2})?");
        Matcher m = p.matcher(info.getColor());
        if (m.find()) {
            int color_rgb = Integer.parseInt(m.group(1), 16);
            int color_alpha = m.group(2) != null ? (Integer.parseInt(m.group(2), 16) & 0xFF) : 0xFF;
            color = (color_alpha << 24) | color_rgb;
        }// www  . jav a2 s .  c  o m
    }

    ContentValues values = new ContentValues();
    values.put(Calendars.ACCOUNT_NAME, account.name);
    values.put(Calendars.ACCOUNT_TYPE, account.type);
    values.put(Calendars.NAME, info.getURL());
    values.put(Calendars.CALENDAR_DISPLAY_NAME, info.getTitle());
    values.put(Calendars.CALENDAR_COLOR, color);
    values.put(Calendars.OWNER_ACCOUNT, account.name);
    values.put(Calendars.SYNC_EVENTS, 1);
    values.put(Calendars.VISIBLE, 1);
    values.put(Calendars.ALLOWED_REMINDERS, Reminders.METHOD_ALERT);

    if (info.isReadOnly())
        values.put(Calendars.CALENDAR_ACCESS_LEVEL, Calendars.CAL_ACCESS_READ);
    else {
        values.put(Calendars.CALENDAR_ACCESS_LEVEL, Calendars.CAL_ACCESS_OWNER);
        values.put(Calendars.CAN_ORGANIZER_RESPOND, 1);
        values.put(Calendars.CAN_MODIFY_TIME_ZONE, 1);
    }

    if (android.os.Build.VERSION.SDK_INT >= 15) {
        values.put(Calendars.ALLOWED_AVAILABILITY, Events.AVAILABILITY_BUSY + "," + Events.AVAILABILITY_FREE
                + "," + Events.AVAILABILITY_TENTATIVE);
        values.put(Calendars.ALLOWED_ATTENDEE_TYPES, Attendees.TYPE_NONE + "," + Attendees.TYPE_OPTIONAL + ","
                + Attendees.TYPE_REQUIRED + "," + Attendees.TYPE_RESOURCE);
    }

    if (info.getTimezone() != null)
        values.put(Calendars.CALENDAR_TIME_ZONE, info.getTimezone());

    Log.i(TAG, "Inserting calendar: " + values.toString() + " -> " + calendarsURI(account).toString());
    try {
        client.insert(calendarsURI(account), values);
    } catch (RemoteException e) {
        throw new LocalStorageException(e);
    }
}

From source file:org.noorganization.instalistsynch.controller.local.dba.impl.SqliteGroupAccessDbControllerTest.java

License:asdf

public void testGetGroupAuthAccess() throws Exception {
    Date currentDate = new Date();
    SQLiteDatabase db = mDbHelper.getWritableDatabase();

    ContentValues cv = new ContentValues();
    cv.put(GroupAccess.COLUMN.GROUP_ID, 1);
    cv.put(GroupAccess.COLUMN.INTERRUPTED, false);
    cv.put(GroupAccess.COLUMN.SYNCHRONIZE, true);
    cv.put(GroupAccess.COLUMN.LAST_UPDATE_FROM_SERVER, ISO8601Utils.format(currentDate));
    cv.put(GroupAccess.COLUMN.LAST_TOKEN_REQUEST, ISO8601Utils.format(currentDate));
    cv.put(GroupAccess.COLUMN.TOKEN, "fdskhbvvkddscddueFSNDFSAdnandk3229df-dFSJDKMds.");

    assertTrue(db.insert(GroupAccess.TABLE_NAME, null, cv) >= 0);

    GroupAccess groupAccess = mGroupAuthAccessDbController.getGroupAuthAccess(1);
    assertNotNull(groupAccess);//from   w w w . jav a2s .  co  m
    assertEquals(1, groupAccess.getGroupId());
    assertEquals(false, groupAccess.wasInterrupted());
    assertEquals(true, groupAccess.isSynchronize());
    assertEquals(ISO8601Utils.format(currentDate), ISO8601Utils.format(groupAccess.getLastUpdateFromServer()));
    assertEquals(ISO8601Utils.format(currentDate), ISO8601Utils.format(groupAccess.getLastTokenRequest()));
    assertEquals("fdskhbvvkddscddueFSNDFSAdnandk3229df-dFSJDKMds.", groupAccess.getToken());
}