List of usage examples for android.content ContentValues put
public void put(String key, byte[] value)
From source file:be.ac.ucl.lfsab1509.llncampus.UCLouvain.java
/** * Launch the download of the courses list and store them in the database. * //from w ww. j av a 2 s . c o m * @param context * Application context. * @param username * UCL global user identifier. * @param password * UCL password. * @param end * Runnable to be executed at the end of the download. * @param mHandler * Handler to manage messages and threads. * */ public static void downloadCoursesFromUCLouvain(final LLNCampusActivity context, final String username, final String password, final Runnable end, final Handler mHandler) { Time t = new Time(); t.setToNow(); int year = t.year; // A new academic year begin in September (8th month on 0-based count). if (t.month < 8) { year--; } final int academicYear = year; mHandler.post(new Runnable() { public void run() { final ProgressDialog mProgress = new ProgressDialog(context); mProgress.setCancelable(false); mProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); mProgress.setMax(100); mProgress.setMessage(context.getString(R.string.connection)); mProgress.show(); new Thread(new Runnable() { /** * Set the progress to the value n and show the message nextStep * @param n * The progress value. * @param nextStep * The message to show (indicate the next step to be processed). */ public void progress(final int n, final String nextStep) { mHandler.post(new Runnable() { public void run() { mProgress.setProgress(n); mProgress.setMessage(nextStep); } }); Log.d("UCLouvain", nextStep); } /** * Notify to the user an error. * * @param msg * The message to show to the user. */ public void sendError(String msg) { notify(context.getString(R.string.error) + " :" + msg); mProgress.cancel(); } /** * Notify to the user a message. * * @param msg * The message to show to the user. */ public void notify(final String msg) { mHandler.post(new Runnable() { public void run() { context.notify(msg); } }); } public void run() { progress(0, context.getString(R.string.connection_ucl)); UCLouvain uclouvain = new UCLouvain(username, password); progress(20, context.getString(R.string.fetch_info)); ArrayList<Offer> offers = uclouvain.getOffers(academicYear); if (offers == null || offers.isEmpty()) { sendError(context.getString(R.string.error_academic_year) + academicYear); return; } int i = 40; ArrayList<Course> courses = new ArrayList<Course>(); for (Offer o : offers) { progress(i, context.getString(R.string.get_courses) + o.getOfferName()); ArrayList<Course> offerCourses = uclouvain.getCourses(o); if (offerCourses != null && !offerCourses.isEmpty()) { courses.addAll(offerCourses); } else { Log.e("CoursListEditActivity", "Error : No course for offer [" + o.getOfferCode() + "] " + o.getOfferName()); } i += (int) (30. / offers.size()); } if (courses.isEmpty()) { sendError(context.getString(R.string.courses_empty)); return; } // Remove old courses. progress(70, context.getString(R.string.cleaning_db)); LLNCampus.getDatabase().delete("Courses", "", null); LLNCampus.getDatabase().delete("Horaire", "", null); // Add new data. i = 80; for (Course c : courses) { progress(i, context.getString(R.string.add_courses_db)); ContentValues cv = new ContentValues(); cv.put("CODE", c.getCourseCode()); cv.put("NAME", c.getCoursName()); LLNCampus.getDatabase().insert("Courses", cv); i += (int) (20. / courses.size()); } progress(100, context.getString(R.string.end)); mProgress.cancel(); mHandler.post(end); } }).start(); } }); }
From source file:com.example.android.ennis.barrett.popularmovies.asynchronous.TMDbSyncUtil.java
/** * Removes all data from themovies, thevideos, and thereviews tables. Does not remove data * flagged favorite but the columns istoprated, and ispopular will be set to false, "0". * @param context/*w ww .j av a 2 s . c o m*/ */ public static void deletePopularAndTopRated(Context context) { ContentResolver contentResolver = context.getContentResolver(); ContentValues removePopAndTop = new ContentValues(2); removePopAndTop.put(TMDbContract.Movies.IS_POPULAR, "0"); removePopAndTop.put(TMDbContract.Movies.IS_TOP_RATED, "0"); contentResolver.update(TMDbContract.Movies.URI, removePopAndTop, TMDbContract.Movies.IS_FAVORITE + " = ?", new String[] { "1" }); contentResolver.delete(TMDbContract.Movies.URI, TMDbContract.Movies.IS_POPULAR + " = ? OR " + TMDbContract.Movies.IS_TOP_RATED + " = ?", new String[] { "1", "1" }); Cursor favoriteMovieIds = getFavoriteIds(context); int numberOfIds = favoriteMovieIds.getCount(); String[] movieIds = new String[numberOfIds]; String whereClauseVideos = ""; String whereClauseReviews = ""; for (int i = 0; i < numberOfIds; i++) { favoriteMovieIds.moveToNext(); movieIds[i] = Integer.toString( favoriteMovieIds.getInt(favoriteMovieIds.getColumnIndex(TMDbContract.Movies.MOVIE_ID))); if (i == numberOfIds - 1) { whereClauseVideos += TMDbContract.Videos.MOVIE_IDS + " != ? "; whereClauseReviews += TMDbContract.Videos.MOVIE_IDS + " != ? "; } else { whereClauseVideos += TMDbContract.Videos.MOVIE_IDS + " != ? OR "; whereClauseReviews += TMDbContract.Reviews.MOVIE_IDS + " != ? OR "; } } contentResolver.delete(TMDbContract.Videos.URI, whereClauseVideos, movieIds); contentResolver.delete(TMDbContract.Reviews.URI, whereClauseReviews, movieIds); }
From source file:com.smarthome.deskclock.Alarms.java
private static void enableAlarmInternal(final Context context, final Alarm alarm, boolean enabled) { if (alarm == null) { return;/* w w w.j a va2s . c o m*/ } ContentResolver resolver = context.getContentResolver(); ContentValues values = new ContentValues(2); values.put(Alarm.Columns.ENABLED, enabled ? 1 : 0); // If we are enabling the alarm, calculate alarm time since the time // value in Alarm may be old. if (enabled) { long time = 0; if (!alarm.daysOfWeek.isRepeatSet()) { time = calculateAlarm(alarm); } values.put(Alarm.Columns.ALARM_TIME, time); } else { // Clear the snooze if the id matches. disableSnoozeAlert(context, alarm.id); } resolver.update(ContentUris.withAppendedId(Alarm.Columns.CONTENT_URI, alarm.id), values, null, null); }
From source file:info.staticfree.android.units.UnitUsageDBHelper.java
/** * Increments the usage counter for the given unit. * @param unit name of the unit/*from w w w .j a va2 s . c om*/ * @param db the unit usage database */ public static void logUnitUsed(String unit, ContentResolver cr) { final String[] selectionArgs = { unit }; final Cursor c = cr.query(UsageEntry.CONTENT_URI, INCREMENT_QUERY_PROJECTION, UsageEntry._UNIT + "=?", selectionArgs, null); if (c.getCount() > 0) { c.moveToFirst(); final int useCount = c.getInt(c.getColumnIndex(UsageEntry._USE_COUNT)); final int id = c.getInt(c.getColumnIndex(UsageEntry._ID)); final ContentValues cv = new ContentValues(); cv.put(UsageEntry._USE_COUNT, useCount + 1); cr.update(ContentUris.withAppendedId(UsageEntry.CONTENT_URI, id), cv, null, null); } else { final ContentValues cv = new ContentValues(); cv.put(UsageEntry._UNIT, unit); cv.put(UsageEntry._USE_COUNT, 1); cv.put(UsageEntry._FACTOR_FPRINT, getFingerprint(unit)); cr.insert(UsageEntry.CONTENT_URI, cv); } c.close(); }
From source file:Main.java
public static ContentValues listToContentValues(List<String> values, String type) { ContentValues contentvalues = new ContentValues(); //Place values into contentvalue structure for (int i = 0; i < values.size(); i++) { String current = values.get(i); try {//from w w w.j a va 2 s .c om //Separate the value by = in order to get key:value Integer indexOfEquals = current.indexOf("="); String key = current.substring(0, indexOfEquals); String value = current.substring(indexOfEquals + 1); if (type.toUpperCase().equals("STRING")) contentvalues.put(key, value); if (type.toUpperCase().equals("BOOLEAN")) contentvalues.put(key, Boolean.valueOf(value)); if (type.toUpperCase().equals("INTEGER")) contentvalues.put(key, new Integer(value)); if (type.toUpperCase().equals("DOUBLE")) contentvalues.put(key, new Double(value)); if (type.toUpperCase().equals("FLOAT")) contentvalues.put(key, new Float(value)); if (type.toUpperCase().equals("LONG")) contentvalues.put(key, new Long(value)); if (type.toUpperCase().equals("SHORT")) contentvalues.put(key, new Short(value)); } catch (Exception e) { Log.e("mercury", "Error with argument " + current); } } return contentvalues; }
From source file:com.github.michalbednarski.intentslab.Utils.java
public static ContentValues jsonObjectToContentValues(JSONObject jsonObject) throws JSONException { if (jsonObject == null) { return null; }//from w ww . ja va 2s . c o m ContentValues contentValues = new ContentValues(); @SuppressWarnings("unchecked") final Iterator<String> iterator = jsonObject.keys(); while (iterator.hasNext()) { String key = iterator.next(); contentValues.put(key, jsonObject.getString(key)); } return contentValues; }
From source file:org.jsharkey.sky.WebserviceHelper.java
/** * Perform a webservice query to retrieve and store the forecast for the * given widget. This call blocks until request is finished and * {@link Forecasts#CONTENT_URI} has been updated. *///from ww w . ja va 2 s. c o m public static void updateForecasts(Context context, Uri appWidgetUri, int days) throws ForecastParseException { Uri appWidgetForecasts = Uri.withAppendedPath(appWidgetUri, AppWidgets.TWIG_FORECASTS); ContentResolver resolver = context.getContentResolver(); Cursor cursor = null; double lat = Double.NaN; double lon = Double.NaN; // Pull exact forecast location from database try { cursor = resolver.query(appWidgetUri, PROJECTION_APPWIDGET, null, null, null); if (cursor != null && cursor.moveToFirst()) { lat = cursor.getDouble(COL_LAT); lon = cursor.getDouble(COL_LON); } } finally { if (cursor != null) { cursor.close(); } } // Query webservice for this location List<Forecast> forecasts = queryLocation(lat, lon, days); if (forecasts == null || forecasts.size() == 0) { throw new ForecastParseException("No forecasts found from webservice query"); } // Purge existing forecasts covered by incoming data, and anything // before today long lastMidnight = ForecastUtils.getLastMidnight(); long earliest = Long.MAX_VALUE; for (Forecast forecast : forecasts) { earliest = Math.min(earliest, forecast.validStart); } resolver.delete(appWidgetForecasts, ForecastsColumns.VALID_START + " >= " + earliest + " OR " + ForecastsColumns.VALID_START + " <= " + lastMidnight, null); // Insert any new forecasts found ContentValues values = new ContentValues(); for (Forecast forecast : forecasts) { Log.d(TAG, "inserting forecast with validStart=" + forecast.validStart); values.clear(); values.put(ForecastsColumns.VALID_START, forecast.validStart); values.put(ForecastsColumns.TEMP_HIGH, forecast.tempHigh); values.put(ForecastsColumns.TEMP_LOW, forecast.tempLow); values.put(ForecastsColumns.CONDITIONS, forecast.conditions); values.put(ForecastsColumns.URL, forecast.url); if (forecast.alert) { values.put(ForecastsColumns.ALERT, ForecastsColumns.ALERT_TRUE); } resolver.insert(appWidgetForecasts, values); } // Mark widget cache as being updated values.clear(); values.put(AppWidgetsColumns.LAST_UPDATED, System.currentTimeMillis()); resolver.update(appWidgetUri, values, null, null); }
From source file:com.google.samples.apps.topeka.persistence.TopekaDatabaseHelper.java
/** * Updates a list of given quizzes./* w w w.j a va2 s .com*/ * * @param writableDatabase The database to write the quizzes to. * @param quizzes The quizzes to write. */ private static void updateQuizzes(SQLiteDatabase writableDatabase, List<Quiz> quizzes) { Quiz quiz; ContentValues quizValues = new ContentValues(); String[] quizArgs = new String[1]; for (int i = 0; i < quizzes.size(); i++) { quiz = quizzes.get(i); quizValues.clear(); quizValues.put(QuizTable.COLUMN_SOLVED, quiz.isSolved()); quizArgs[0] = quiz.getQuestion(); writableDatabase.update(QuizTable.NAME, quizValues, QuizTable.COLUMN_QUESTION + "=?", quizArgs); } }
From source file:org.devtcg.five.provider.FiveSyncAdapter.java
private static void downloadFileAndUpdateProviderCancelable(final SyncContext context, final AbstractSyncProvider serverDiffs, final HttpGet request, final Uri localUri, final Uri localFeedItemUri, final String columnToUpdate) throws ClientProtocolException, IOException { sClient.execute(request, new ResponseHandler<Void>() { public Void handleResponse(HttpResponse response) throws ClientProtocolException, IOException { if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) return null; if (context.hasCanceled()) return null; /*/*from w w w.ja v a2 s . c om*/ * Access a temp file path (FiveProvider treats this as a * special case when isTemporary is true and uses a temporary * path to be moved manually during merging). */ ParcelFileDescriptor pfd = serverDiffs.openFile(localUri, "w"); InputStream in = response.getEntity().getContent(); OutputStream out = new ParcelFileDescriptor.AutoCloseOutputStream(pfd); try { IOUtilities.copyStream(in, out); if (context.hasCanceled() == true) return null; /* * Update the record to reflect the newly downloaded uri. * During table merging we'll need to move the file and * update the uri we store here. */ ContentValues values = new ContentValues(); values.put(columnToUpdate, localUri.toString()); serverDiffs.update(localFeedItemUri, values, null, null); } finally { if (in != null) IOUtilities.close(in); if (out != null) IOUtilities.close(out); } return null; } }); }
From source file:com.bchalk.GVCallback.callback.GVCommunicator.java
public static void insertPlaceholderCall(ContentResolver contentResolver, String number) { ContentValues values = new ContentValues(); values.put(CallLog.Calls.NUMBER, number); values.put(CallLog.Calls.DATE, System.currentTimeMillis()); values.put(CallLog.Calls.DURATION, 0); values.put(CallLog.Calls.TYPE, CallLog.Calls.OUTGOING_TYPE); values.put(CallLog.Calls.NEW, 1);/* www . j a v a 2 s. c om*/ values.put(CallLog.Calls.CACHED_NAME, ""); values.put(CallLog.Calls.CACHED_NUMBER_TYPE, 0); values.put(CallLog.Calls.CACHED_NUMBER_LABEL, ""); Log.d(TAG, "Inserting call log placeholder for " + number); contentResolver.insert(CallLog.Calls.CONTENT_URI, values); }