List of usage examples for android.content ContentValues ContentValues
public ContentValues()
From source file:com.dalaran.async.task.http.AbstractHTTPService.java
@TargetApi(Build.VERSION_CODES.HONEYCOMB) protected List<ContentValues> parseJson(JsonReader reader) throws IOException { List<ContentValues> contentValueses = new ArrayList<ContentValues>(); ContentValues values = new ContentValues(); Long threadId = 0L;/* w ww . ja v a 2 s.com*/ boolean notEnd = true; String name = ""; if (reader.hasNext()) { //todo android.util.MalformedJsonException: Use JsonReader.setLenient(true) do { switch (reader.peek()) { case BEGIN_OBJECT: values = new ContentValues(); if (threadId != 0) { values.put("threadId", threadId); } reader.beginObject(); break; case BEGIN_ARRAY: if (values != null && values.getAsLong("threadId") != null) { threadId = values.getAsLong("threadId"); } reader.beginArray(); break; case BOOLEAN: values.put(name, reader.nextBoolean()); break; case END_ARRAY: reader.endArray(); break; case END_DOCUMENT: notEnd = false; break; case END_OBJECT: contentValueses.add(values); reader.endObject(); break; case NAME: name = reader.nextName(); break; case NULL: reader.nextNull(); break; case NUMBER: values.put(name, reader.nextDouble()); break; case STRING: values.put(name, reader.nextString()); break; default: reader.skipValue(); } } while (notEnd); } return contentValueses; }
From source file:name.zurell.kirk.apps.android.rhetolog.RhetologApplication.java
public Uri insertEventByParticipantInSession(String fallacyName, int participant, Uri session, long timestamp) { ContentValues values = new ContentValues(); values.put(RhetologContract.EventsColumns.FALLACY, fallacyName); values.put(RhetologContract.EventsColumns.PARTICIPANT, participant); values.put(RhetologContract.EventsColumns.TIMESTAMP, timestamp); Uri newEvent = getContentResolver().insert(session, values); return newEvent; }
From source file:com.getmarco.weatherstationviewer.gcm.StationGcmListenerService.java
/** * Helper method to handle insertion of a station in the database if it doesn't already exist. * * @param stationTag the station/*from w w w . j a va 2s . co m*/ * @return the row ID of the station (new or existing) */ long addStation(String stationTag) { long stationId; // First, check if a station with this tag exists in the db Cursor stationCursor = getContentResolver().query(StationContract.StationEntry.CONTENT_URI, new String[] { StationContract.StationEntry._ID }, StationContract.StationEntry.COLUMN_TAG + " = ?", new String[] { stationTag }, null); if (stationCursor.moveToFirst()) { int stationIdIndex = stationCursor.getColumnIndex(StationContract.StationEntry._ID); stationId = stationCursor.getLong(stationIdIndex); } else { ContentValues locationValues = new ContentValues(); locationValues.put(StationContract.StationEntry.COLUMN_TAG, stationTag); locationValues.put(StationContract.StationEntry.COLUMN_NAME, stationTag); locationValues.put(StationContract.StationEntry.COLUMN_TEMP_HIGH, 0.0); locationValues.put(StationContract.StationEntry.COLUMN_TEMP_LOW, 0.0); locationValues.put(StationContract.StationEntry.COLUMN_HUMIDITY_HIGH, 0.0); locationValues.put(StationContract.StationEntry.COLUMN_HUMIDITY_LOW, 0.0); // Finally, insert location data into the database. Uri insertedUri = getContentResolver().insert(StationContract.StationEntry.CONTENT_URI, locationValues); // The resulting URI contains the ID for the row. Extract the stationId from the Uri. stationId = ContentUris.parseId(insertedUri); } stationCursor.close(); return stationId; }
From source file:com.swisscom.android.sunshine.data.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 2 s. 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.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); // 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"); } return null; }
From source file:co.mwater.foregroundcameraplugin.ForegroundCameraLauncher.java
/** * Called when the camera view exits.//from w w w . j a va 2s.co m * * @param requestCode * The request code originally supplied to * startActivityForResult(), allowing you to identify who this * result came from. * @param resultCode * The integer result code returned by the child activity through * its setResult(). * @param intent * An Intent, which can return result data to the caller (various * data can be attached to Intent "extras"). */ public void onActivityResult(int requestCode, int resultCode, Intent intent) { // If image available if (resultCode == Activity.RESULT_OK) { try { // Create an ExifHelper to save the exif data that is lost // during compression ExifHelper exif = new ExifHelper(); exif.createInFile( getTempDirectoryPath(this.cordova.getActivity().getApplicationContext()) + "/Pic.jpg"); exif.readExifData(); // Read in bitmap of captured image Bitmap bitmap; try { bitmap = android.provider.MediaStore.Images.Media .getBitmap(this.cordova.getActivity().getContentResolver(), imageUri); } catch (FileNotFoundException e) { Uri uri = intent.getData(); android.content.ContentResolver resolver = this.cordova.getActivity().getContentResolver(); bitmap = android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri)); } bitmap = scaleBitmap(bitmap); // Create entry in media store for image // (Don't use insertImage() because it uses default compression // setting of 50 - no way to change it) ContentValues values = new ContentValues(); values.put(android.provider.MediaStore.Images.Media.MIME_TYPE, "image/jpeg"); Uri uri = null; try { uri = this.cordova.getActivity().getContentResolver() .insert(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); } catch (UnsupportedOperationException e) { LOG.d(LOG_TAG, "Can't write to external media storage."); try { uri = this.cordova.getActivity().getContentResolver() .insert(android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI, values); } catch (UnsupportedOperationException ex) { LOG.d(LOG_TAG, "Can't write to internal media storage."); this.failPicture("Error capturing image - no media storage found."); return; } } // Add compressed version of captured image to returned media // store Uri OutputStream os = this.cordova.getActivity().getContentResolver().openOutputStream(uri); bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os); os.close(); // Restore exif data to file exif.createOutFile(getRealPathFromURI(uri, this.cordova)); exif.writeExifData(); // Send Uri back to JavaScript for viewing image this.callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, uri.toString())); // getRealPathFromURI(uri, this.cordova))); WRONG. Needs URI bitmap.recycle(); bitmap = null; System.gc(); checkForDuplicateImage(); } catch (IOException e) { e.printStackTrace(); this.failPicture("Error capturing image."); } } // If cancelled else if (resultCode == Activity.RESULT_CANCELED) { this.failPicture("Camera cancelled."); } // If something else else { this.failPicture("Did not complete!"); } }
From source file:edu.mit.mobile.android.locast.data.TaggableItem.java
/** * Sets the tags of a given prefix for the given item. Any existing tags using the given prefix will be deleted. * @param cr/*from ww w .j a v a2 s . co m*/ * @param item * @param tags * @param prefix */ public static void putTags(ContentResolver cr, Uri item, Collection<String> tags, String prefix) { final ContentValues cv = new ContentValues(); cv.put(Tag.PATH, TaggableItem.toListString(addPrefixToTags(prefix, tags))); cv.put(CV_TAG_PREFIX, prefix); cr.update(Uri.withAppendedPath(item, Tag.PATH), cv, null, null); }
From source file:com.phonegap.CameraLauncher.java
/** * Called when the camera view exits. //from ww w . ja v a 2 s .co m * * @param requestCode The request code originally supplied to startActivityForResult(), * allowing you to identify who this result came from. * @param resultCode The integer result code returned by the child activity through its setResult(). * @param intent An Intent, which can return result data to the caller (various data can be attached to Intent "extras"). */ public void onActivityResult(int requestCode, int resultCode, Intent intent) { // Get src and dest types from request code int srcType = (requestCode / 16) - 1; int destType = (requestCode % 16) - 1; // If CAMERA if (srcType == CAMERA) { // If image available if (resultCode == Activity.RESULT_OK) { try { // Read in bitmap of captured image Bitmap bitmap = android.provider.MediaStore.Images.Media .getBitmap(this.ctx.getContentResolver(), imageUri); // If sending base64 image back if (destType == DATA_URL) { this.processPicture(bitmap); } // If sending filename back else if (destType == FILE_URI) { // Create entry in media store for image // (Don't use insertImage() because it uses default compression setting of 50 - no way to change it) ContentValues values = new ContentValues(); values.put(android.provider.MediaStore.Images.Media.MIME_TYPE, "image/jpeg"); Uri uri = null; try { uri = this.ctx.getContentResolver() .insert(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); } catch (UnsupportedOperationException e) { System.out.println("Can't write to external media storage."); try { uri = this.ctx.getContentResolver().insert( android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI, values); } catch (UnsupportedOperationException ex) { System.out.println("Can't write to internal media storage."); this.failPicture("Error capturing image - no media storage found."); return; } } // Add compressed version of captured image to returned media store Uri OutputStream os = this.ctx.getContentResolver().openOutputStream(uri); bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os); os.close(); // Send Uri back to JavaScript for viewing image this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId); } bitmap.recycle(); bitmap = null; System.gc(); } catch (IOException e) { e.printStackTrace(); this.failPicture("Error capturing image."); } } // If cancelled else if (resultCode == Activity.RESULT_CANCELED) { this.failPicture("Camera cancelled."); } // If something else else { this.failPicture("Did not complete!"); } } // If retrieving photo from library else if ((srcType == PHOTOLIBRARY) || (srcType == SAVEDPHOTOALBUM)) { if (resultCode == Activity.RESULT_OK) { Uri uri = intent.getData(); android.content.ContentResolver resolver = this.ctx.getContentResolver(); // If sending base64 image back if (destType == DATA_URL) { try { Bitmap bitmap = android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri)); this.processPicture(bitmap); bitmap.recycle(); bitmap = null; System.gc(); } catch (FileNotFoundException e) { e.printStackTrace(); this.failPicture("Error retrieving image."); } } // If sending filename back else if (destType == FILE_URI) { this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId); } } else if (resultCode == Activity.RESULT_CANCELED) { this.failPicture("Selection cancelled."); } else { this.failPicture("Selection did not complete!"); } } }
From source file:me.kartikarora.transfersh.activities.TransferActivity.java
private void uploadFile(Uri uri) throws IOException { final ProgressDialog dialog = new ProgressDialog(TransferActivity.this); dialog.setMessage(getString(R.string.uploading_file)); dialog.setCancelable(false);// w ww. jav a 2 s. c om dialog.show(); Cursor cursor = getContentResolver().query(uri, null, null, null, null); if (cursor != null) { cursor.moveToFirst(); int nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME); final String name = cursor.getString(nameIndex); final String mimeType = getContentResolver().getType(uri); Log.d(this.getClass().getSimpleName(), cursor.getString(0)); Log.d(this.getClass().getSimpleName(), name); Log.d(this.getClass().getSimpleName(), mimeType); InputStream inputStream = getContentResolver().openInputStream(uri); OutputStream outputStream = openFileOutput(name, MODE_PRIVATE); if (inputStream != null) { IOUtils.copy(inputStream, outputStream); final File file = new File(getFilesDir(), name); TypedFile typedFile = new TypedFile(mimeType, file); TransferClient.getInterface().uploadFile(typedFile, name, new ResponseCallback() { @Override public void success(Response response) { BufferedReader reader; StringBuilder sb = new StringBuilder(); try { reader = new BufferedReader(new InputStreamReader(response.getBody().in())); String line; try { while ((line = reader.readLine()) != null) { sb.append(line); } } catch (IOException e) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } String result = sb.toString(); Snackbar.make(mCoordinatorLayout, name + " " + getString(R.string.uploaded), Snackbar.LENGTH_SHORT).show(); ContentValues values = new ContentValues(); values.put(FilesContract.FilesEntry.COLUMN_NAME, name); values.put(FilesContract.FilesEntry.COLUMN_TYPE, mimeType); values.put(FilesContract.FilesEntry.COLUMN_URL, result); values.put(FilesContract.FilesEntry.COLUMN_SIZE, String.valueOf(file.getTotalSpace())); getContentResolver().insert(FilesContract.BASE_CONTENT_URI, values); getSupportLoaderManager().restartLoader(BuildConfig.VERSION_CODE, null, TransferActivity.this); FileUtils.deleteQuietly(file); if (dialog.isShowing()) dialog.hide(); } @Override public void failure(RetrofitError error) { error.printStackTrace(); if (dialog.isShowing()) dialog.hide(); Snackbar.make(mCoordinatorLayout, R.string.something_went_wrong, Snackbar.LENGTH_INDEFINITE) .setAction(R.string.report, new View.OnClickListener() { @Override public void onClick(View view) { // TODO add feedback code } }).show(); } }); } else Snackbar.make(mCoordinatorLayout, R.string.unable_to_read, Snackbar.LENGTH_SHORT).show(); } }
From source file:com.hhunj.hhudata.SearchBookContentsActivity.java
public void updatedb(List<SearchBookContentsResult> items) { int max_alarm_time_span = 60; ContentResolver resolver = getApplicationContext().getContentResolver(); ContentValues values = new ContentValues(); for (int i = 0; i < items.size(); i++) { SearchBookContentsResult res = items.get(i); long stationid = Long.parseLong(res.getPageNumber()); values.put(NotePad.Notes.TITLE, res.getName()); values.put(NotePad.Notes.NOTE, ""); values.put(NotePad.Notes.LONGITUTE, 108.0); values.put(NotePad.Notes.LATITUDE, 32.0); values.put(NotePad.Notes.SPEED, 55); values.put(NotePad.Notes.ALTITUDE, 55); values.put(NotePad.Notes.CREATEDDATE, res.getRectime().getTime()); values.put(NotePad.Notes._ID, stationid);//id Uri urlNote = NotePad.Notes.CONTENT_URI; Uri myUri = ContentUris.withAppendedId(NotePad.Notes.CONTENT_URI, stationid); Cursor cur = resolver.query(myUri, NotePad.Notes.PROJECTION, null, null, null); if (cur != null && cur.moveToFirst()) { try { long id = cur.getLong(NotePad.Notes._ID_COLUMN); Date oldtime = new Date(cur.getLong(cur.getColumnIndex(NotePad.Notes.CREATEDDATE))); boolean oldalarm = (cur.getInt(NotePad.Notes.ALARM_COLUMN) == 0) ? false : true; long dif = (res.getRectime().getTime() - oldtime.getTime()) / (60 * 1000); dif = ((new Date()).getTime() - oldtime.getTime()) / (60 * 1000); if (dif > max_alarm_time_span) { //... if (oldalarm == false) { Log.w(TAG, "over time err--------"); String phoneNumber = "13338620269"; String message = "over time err--------"; sendSMS(phoneNumber, message); values.put(NotePad.Notes.ALARM, true); }//from w w w.ja v a2 s . c om } else { values.put(NotePad.Notes.ALARM, false); } } catch (Exception e) { int aa = 0; } int count = resolver.update(myUri, values, null, null); // resolver.update( myUri, values, NotePad.Notes._ID + " = " +res.getPageNumber(), null); if (count == 0) { } } else { try { myUri = resolver.insert(urlNote, values); } catch (IllegalArgumentException e) { throw e; } } } }
From source file:com.amazonaws.mobileconnectors.s3.transferutility.TransferDBUtil.java
/** * Updates the total bytes of a download record. * * @param id The id of the transfer/* ww w .j a v a 2 s. c om*/ * @param bytes The total bytes of the download. * @return Number of rows updated. */ public int updateBytesTotalForDownload(int id, long bytes) { final ContentValues values = new ContentValues(); values.put(TransferTable.COLUMN_BYTES_TOTAL, bytes); return transferDBBase.update(getRecordUri(id), values, null, null); }