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:com.hufeiya.SignIn.persistence.TopekaDatabaseHelper.java

private void fillCategoriesAndQuizzes(SQLiteDatabase db) throws JSONException, IOException {
    ContentValues values = new ContentValues(); // reduce, reuse
    JSONArray jsonArray = new JSONArray(readCategoriesFromResources());
    JSONObject category;/*from w  w w  .j  a  v  a 2s  .  c om*/
    Log.d("category", "json size is " + jsonArray.length());
    for (int i = 0; i < jsonArray.length(); i++) {
        category = jsonArray.getJSONObject(i);
        final String categoryId = category.getString(JsonAttributes.ID);
        Log.d("category", categoryId);
        fillCategory(db, values, category, categoryId);
    }
}

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

@Override
protected void onHandleIntent(Intent intent) {
    ContentResolver resolver = getContentResolver();
    Cursor cursor = null;//from  w  ww .j  a  v a  2s .c o m
    long now = System.currentTimeMillis();
    boolean shouldUpdate = true;
    String responseString = "";

    /** 
     * 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[] { "mountain_passes" }, 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) > (15 * 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();
        buildWeatherPhrases();

        try {
            URL url = new URL(MOUNTAIN_PASS_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 mDateUpdated = "";
            String jsonFile = "";
            String line;
            while ((line = in.readLine()) != null)
                jsonFile += line;
            in.close();

            JSONObject obj = new JSONObject(jsonFile);
            JSONObject result = obj.getJSONObject("GetMountainPassConditionsResult");
            JSONArray passConditions = result.getJSONArray("PassCondition");
            String weatherCondition;
            Integer weather_image;
            Integer forecast_weather_image;
            List<ContentValues> passes = new ArrayList<ContentValues>();

            int numConditions = passConditions.length();
            for (int j = 0; j < numConditions; j++) {
                JSONObject pass = passConditions.getJSONObject(j);
                ContentValues passData = new ContentValues();
                weatherCondition = pass.getString("WeatherCondition");
                weather_image = getWeatherImage(weatherPhrases, weatherCondition);

                String tempDate = pass.getString("DateUpdated");

                try {
                    tempDate = tempDate.replace("[", "");
                    tempDate = tempDate.replace("]", "");

                    String[] a = tempDate.split(",");
                    StringBuilder sb = new StringBuilder();
                    for (int m = 0; m < 5; m++) {
                        sb.append(a[m]);
                        sb.append(",");
                    }
                    tempDate = sb.toString().trim();
                    tempDate = tempDate.substring(0, tempDate.length() - 1);
                    Date date = parseDateFormat.parse(tempDate);
                    mDateUpdated = displayDateFormat.format(date);
                } catch (Exception e) {
                    Log.e(DEBUG_TAG, "Error parsing date: " + tempDate, e);
                    mDateUpdated = "N/A";
                }

                JSONArray forecasts = pass.getJSONArray("Forecast");
                JSONArray forecastItems = new JSONArray();

                int numForecasts = forecasts.length();
                for (int l = 0; l < numForecasts; l++) {
                    JSONObject forecast = forecasts.getJSONObject(l);

                    if (isNight(forecast.getString("Day"))) {
                        forecast_weather_image = getWeatherImage(weatherPhrasesNight,
                                forecast.getString("ForecastText"));
                    } else {
                        forecast_weather_image = getWeatherImage(weatherPhrases,
                                forecast.getString("ForecastText"));
                    }

                    forecast.put("weather_icon", forecast_weather_image);

                    if (l == 0) {
                        if (weatherCondition.equals("")) {
                            weatherCondition = forecast.getString("ForecastText").split("\\.")[0] + ".";
                            weather_image = forecast_weather_image;
                        }
                    }

                    forecastItems.put(forecast);
                }

                passData.put(MountainPasses.MOUNTAIN_PASS_ID, pass.getString("MountainPassId"));
                passData.put(MountainPasses.MOUNTAIN_PASS_NAME, pass.getString("MountainPassName"));
                passData.put(MountainPasses.MOUNTAIN_PASS_WEATHER_ICON, weather_image);
                passData.put(MountainPasses.MOUNTAIN_PASS_FORECAST, forecastItems.toString());
                passData.put(MountainPasses.MOUNTAIN_PASS_WEATHER_CONDITION, weatherCondition);
                passData.put(MountainPasses.MOUNTAIN_PASS_DATE_UPDATED, mDateUpdated);
                passData.put(MountainPasses.MOUNTAIN_PASS_CAMERA, pass.getString("Cameras"));
                passData.put(MountainPasses.MOUNTAIN_PASS_ELEVATION, pass.getString("ElevationInFeet"));
                passData.put(MountainPasses.MOUNTAIN_PASS_TRAVEL_ADVISORY_ACTIVE,
                        pass.getString("TravelAdvisoryActive"));
                passData.put(MountainPasses.MOUNTAIN_PASS_ROAD_CONDITION, pass.getString("RoadCondition"));
                passData.put(MountainPasses.MOUNTAIN_PASS_TEMPERATURE,
                        pass.getString("TemperatureInFahrenheit"));
                JSONObject restrictionOne = pass.getJSONObject("RestrictionOne");
                passData.put(MountainPasses.MOUNTAIN_PASS_RESTRICTION_ONE,
                        restrictionOne.getString("RestrictionText"));
                passData.put(MountainPasses.MOUNTAIN_PASS_RESTRICTION_ONE_DIRECTION,
                        restrictionOne.getString("TravelDirection"));
                JSONObject restrictionTwo = pass.getJSONObject("RestrictionTwo");
                passData.put(MountainPasses.MOUNTAIN_PASS_RESTRICTION_TWO,
                        restrictionTwo.getString("RestrictionText"));
                passData.put(MountainPasses.MOUNTAIN_PASS_RESTRICTION_TWO_DIRECTION,
                        restrictionTwo.getString("TravelDirection"));

                if (starred.contains(Integer.parseInt(pass.getString("MountainPassId")))) {
                    passData.put(MountainPasses.MOUNTAIN_PASS_IS_STARRED, 1);
                }

                passes.add(passData);

            }

            // Purge existing mountain passes covered by incoming data
            resolver.delete(MountainPasses.CONTENT_URI, null, null);
            // Bulk insert all the new mountain passes
            resolver.bulkInsert(MountainPasses.CONTENT_URI, passes.toArray(new ContentValues[passes.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[] { "mountain_passes" });

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

From source file:com.maass.android.imgur_uploader.ImgurUpload.java

private void handleResponse() {
    Log.i(this.getClass().getName(), "in handleResponse()");
    // close progress notification
    mNotificationManager.cancel(NOTIFICATION_ID);

    String notificationMessage = getString(R.string.upload_success);

    // notification intent with result
    final Intent notificationIntent = new Intent(getBaseContext(), ImageDetails.class);

    if (mImgurResponse == null) {
        notificationMessage = getString(R.string.connection_failed);
    } else if (mImgurResponse.get("error") != null) {
        notificationMessage = getString(R.string.unknown_error) + mImgurResponse.get("error");
    } else {/*from w ww.  j av  a 2  s  . co  m*/
        // create thumbnail
        if (mImgurResponse.get("image_hash").length() > 0) {
            createThumbnail(imageLocation);
        }

        // store result in database
        final HistoryDatabase histData = new HistoryDatabase(getBaseContext());
        final SQLiteDatabase data = histData.getWritableDatabase();

        final HashMap<String, String> dataToSave = new HashMap<String, String>();
        dataToSave.put("delete_hash", mImgurResponse.get("delete_hash"));
        dataToSave.put("image_url", mImgurResponse.get("original"));
        final Uri imageUri = Uri
                .parse(getFilesDir() + "/" + mImgurResponse.get("image_hash") + THUMBNAIL_POSTFIX);
        dataToSave.put("local_thumbnail", imageUri.toString());
        dataToSave.put("upload_time", "" + System.currentTimeMillis());

        for (final Map.Entry<String, String> entry : dataToSave.entrySet()) {
            final ContentValues content = new ContentValues();
            content.put("hash", mImgurResponse.get("image_hash"));
            content.put("key", entry.getKey());
            content.put("value", entry.getValue());
            data.insert("imgur_history", null, content);
        }

        //set intent to go to image details
        notificationIntent.putExtra("hash", mImgurResponse.get("image_hash"));
        notificationIntent.putExtra("image_url", mImgurResponse.get("original"));
        notificationIntent.putExtra("delete_hash", mImgurResponse.get("delete_hash"));
        notificationIntent.putExtra("local_thumbnail", imageUri.toString());

        data.close();
        histData.close();

        // if the main activity is already open then refresh the gridview
        sendBroadcast(new Intent(BROADCAST_ACTION));
    }

    //assemble notification
    final Notification notification = new Notification(R.drawable.icon, notificationMessage,
            System.currentTimeMillis());
    notification.setLatestEventInfo(this, getString(R.string.app_name), notificationMessage, PendingIntent
            .getActivity(getBaseContext(), 0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT));
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    mNotificationManager.notify(NOTIFICATION_ID, notification);

}

From source file:com.creationgroundmedia.popularmovies.sync.MovieSyncAdapter.java

private int deleteOldEntriesFromDb() {
    final String NOT_FAVE_SELECTION = MoviesContract.MovieEntry.COLUMN_FAVORITE + " != 1";
    final String NOT_FRESH_AND_NOT_FAVE_SELECTION = MoviesContract.MovieEntry.COLUMN_FRESH + " != 1 AND "
            + NOT_FAVE_SELECTION;//  w  w  w. j a v  a2 s .c  om
    int rows;
    // Get rid of anything not FRESH and not FAVORITE
    rows = mContext.getContentResolver().delete(MoviesContract.MovieEntry.CONTENT_URI,
            NOT_FRESH_AND_NOT_FAVE_SELECTION, null);
    //        Log.d(LOG_TAG, "deleted " + rows + " \'" + NOT_FRESH_AND_NOT_FAVE_SELECTION + "\'");
    ContentValues values = new ContentValues();

    // Set everything to no longer FRESH
    values.put(MoviesContract.MovieEntry.COLUMN_FRESH, "0");
    rows = mContext.getContentResolver().update(MoviesContract.MovieEntry.CONTENT_URI, values,
            NOT_FAVE_SELECTION, null);
    //        Log.d(LOG_TAG, "updated \'" + NOT_FAVE_SELECTION + "\' " + rows + " to NOT_FRESH");
    return rows;
}

From source file:com.ubikod.urbantag.model.TagManager.java

/**
 * Insert tag on db/*  www.ja v a2  s.  co  m*/
 * @param t
 */
private void dbInsert(Tag t) {
    this.open();
    ContentValues values = new ContentValues();
    values.put(DatabaseHelper.TAG_COL_ID, t.getId());
    values.put(DatabaseHelper.TAG_COL_NAME, t.getValue());
    values.put(DatabaseHelper.TAG_COL_COLOR, t.getColor());
    values.put(DatabaseHelper.TAG_COL_NOTIFY, t.isSelected() ? 1 : 0);

    mDB.insert(DatabaseHelper.TABLE_TAGS, DatabaseHelper.TAG_COL_ID, values);
    this.close();
}

From source file:de.tudarmstadt.dvs.myhealthassistant.myhealthhub.services.transformationmanager.database.LocalTransformationDBMS.java

public boolean addDateOfTraffic(String date, int trafficId) {

    ContentValues values = new ContentValues();
    values.put(LocalTransformationDB.COLUMN_TRAFFIC_ID, trafficId);
    values.put(LocalTransformationDB.COLUMN_DATE_TEXT, date);
    long insertId = database.insert(LocalTransformationDB.TABLE_DATE_TO_TRAFFIC, null, values);
    if (insertId == -1) {
        Log.e(TAG, "addTraffic failed at:[" + date + "]");
    }//from w w  w. jav a  2 s.c  o m
    return insertId != -1;
}

From source file:fr.shywim.antoinedaniel.sync.AppState.java

/**
 * Load AppState from a JSONObject.// w  ww . j a va2  s  .c o m
 *
 * @param data json to import.
 */
void importFromJSON(JSONObject data, Context context, GoogleApiClient apiClient) {
    Gson gson = new Gson();
    try {
        ContentValues cv = new ContentValues();

        Set<String> widgetSounds = gson.fromJson(data.getJSONArray(WIDGET_SOUNDS).toString(),
                this.widgetSounds.getClass());
        for (String soundName : widgetSounds) {
            synchronized (LOCK) {
                this.widgetSounds.add(soundName);
            }
            Uri uri = Uri.withAppendedPath(ProviderConstants.SOUND_NAME_URI, soundName);
            cv.clear();
            cv.put(ProviderContract.SoundEntry.COLUMN_WIDGET, 1);
            context.getContentResolver().update(uri, cv, null, null);
        }

        Set<String> favSounds = gson.fromJson(data.getJSONArray(FAVORITES_SOUNDS).toString(),
                this.favSounds.getClass());
        for (String soundName : favSounds) {
            synchronized (LOCK) {
                this.favSounds.add(soundName);
            }
            Uri uri = Uri.withAppendedPath(ProviderConstants.SOUND_NAME_URI, soundName);
            cv.clear();
            cv.put(ProviderContract.SoundEntry.COLUMN_FAVORITE, 1);
            context.getContentResolver().update(uri, cv, null, null);
        }

        Map<String, String> bestScores = gson.fromJson(data.getJSONObject(BEST_SCORES).toString(),
                this.bestScores.getClass());
        for (Map.Entry<String, String> entry : bestScores.entrySet()) {
            long newLong = Long.parseLong(entry.getValue());
            synchronized (LOCK) {
                if (this.bestScores.containsKey(entry.getKey())
                        && Long.parseLong(this.bestScores.get(entry.getKey())) <= newLong)
                    this.bestScores.put(entry.getKey(), entry.getValue());
            }
            if (apiClient != null) {
                Games.Leaderboards.submitScore(apiClient, entry.getKey(), newLong);
            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

From source file:edu.nd.darts.cimon.database.CimonDatabaseAdapter.java

/**
 * Insert new metric into Metrics table, or replace if the id already exist.
 * /*from  w w  w  . j  ava  2  s .c o  m*/
 * @param id        id which identifies individual metric to insert
 * @param group     id of metric group this metric belongs to
 * @param metric    name of metric
 * @param units     units of metric values
 * @param max       maximum potential value
 * @return    rowid of inserted row, -1 on failure
 * 
 * @see MetricsTable
 */
public synchronized long insertOrReplaceMetrics(int id, int group, String metric, String units, float max) {
    if (DebugLog.DEBUG)
        Log.d(TAG, "CimonDatabaseAdapter.insertOrReplaceMetrics - insert into Metrics table: metric-" + metric);
    ContentValues values = new ContentValues();
    values.put(MetricsTable.COLUMN_ID, id);
    values.put(MetricsTable.COLUMN_INFO_ID, group);
    values.put(MetricsTable.COLUMN_METRIC, metric);
    values.put(MetricsTable.COLUMN_UNITS, units);
    values.put(MetricsTable.COLUMN_MAX, max);

    long rowid = database.replace(MetricsTable.TABLE_METRICS, null, values);
    if (rowid >= 0) {
        Uri uri = Uri.withAppendedPath(CimonContentProvider.METRICS_URI, String.valueOf(id));
        context.getContentResolver().notifyChange(uri, null);
    }
    return rowid;
}

From source file:net.ccghe.emocha.model.DBAdapter.java

public static boolean markForDeletion(boolean state) {
    ContentValues values = new ContentValues();
    values.put("to_delete", state ? 1 : 0);
    return sDB.update(TABLE_DOWNLOADS, values, null, null) > 0;
}

From source file:com.dwdesign.tweetings.fragment.SearchTweetsFragment.java

@Override
public boolean onOptionsItemSelected(final MenuItem item) {
    switch (item.getItemId()) {
    case MENU_SAVE: {
        final TweetingsApplication application = getApplication();
        application.getServiceInterface().createSavedSearch(mAccountId, mQuery);
        break;// ww w . jav a  2  s.  c  om
    }
    case MENU_DELETE: {
        final TweetingsApplication application = getApplication();
        application.getServiceInterface().destroySavedSearch(mAccountId, mSearchId);
        break;
    }
    case MENU_ADD_TAB: {
        CustomTabsAdapter mAdapter;
        mAdapter = new CustomTabsAdapter(getActivity());
        ContentResolver mResolver;
        mResolver = getContentResolver();
        final String tabName = mQuery;
        final String tabType = AUTHORITY_SEARCH_TWEETS;
        final String tabIcon = "search";
        final long account_id = mAccountId;
        final String tabArguments = "{\"account_id\":" + account_id + ",\"query\":" + JSONObject.quote(mQuery)
                + "}";
        final ContentValues values = new ContentValues();
        values.put(Tabs.ARGUMENTS, tabArguments);
        values.put(Tabs.NAME, tabName);
        values.put(Tabs.POSITION, mAdapter.getCount());
        values.put(Tabs.TYPE, tabType);
        values.put(Tabs.ICON, tabIcon);
        mResolver.insert(Tabs.CONTENT_URI, values);
        Toast.makeText(this.getActivity(), R.string.search_tab_added, Toast.LENGTH_SHORT).show();
        break;
    }
    }
    return super.onOptionsItemSelected(item);
}