List of usage examples for android.content ContentValues ContentValues
public ContentValues()
From source file:cn.loveapple.client.android.shiba.database.impl.BookMarkDaoImpl.java
/** * {@inheritDoc}/*w w w . j av a2 s .c o m*/ */ public BookMarkEntity save(BookMarkEntity entity) { if (entity == null) { throw new IllegalArgumentException("history entity is null."); } if (StringUtils.isEmpty(entity.getUrl())) { throw new IllegalArgumentException("history url is null."); } ContentValues values = new ContentValues(); values.put(COLUMN_URL, entity.getUrl()); if (StringUtils.isNotEmpty(entity.getTitle())) { values.put(COLUMN_TITLE, entity.getTitle()); } if (entity.getTimestamp() != null) { values.put(COLUMN_TIMESTAMP, entity.getTimestamp().getTime()); } BookMarkEntity result = null; try { writableDb = getWritableDb(); int colNum = writableDb.update(TABLE_NAME, values, COLUMN_URL + "=?", new String[] { entity.getUrl() }); if (colNum < 1) { writableDb.insert(TABLE_NAME, null, values); Log.i(LOG_TAG, "update : " + ToStringBuilder.reflectionToString(values)); } result = getUrlHistory(entity.getUrl(), null); } finally { //writableDb.close(); } return result; }
From source file:com.codebutler.farebot.activities.ReadingTagActivity.java
private void resolveIntent(Intent intent) { final TextView textView = (TextView) findViewById(R.id.textView); try {//from w w w . j a v a 2s . c o m Bundle extras = intent.getExtras(); final Tag tag = (Tag) extras.getParcelable("android.nfc.extra.TAG"); ; final String[] techs = tag.getTechList(); new AsyncTask<Void, String, MifareCard>() { Exception mException; @Override protected MifareCard doInBackground(Void... params) { try { if (ArrayUtils.contains(techs, "android.nfc.tech.NfcB")) return CEPASCard.dumpTag(tag.getId(), tag); else if (ArrayUtils.contains(techs, "android.nfc.tech.IsoDep")) return DesfireCard.dumpTag(tag.getId(), tag); else throw new UnsupportedTagException(techs, Utils.getHexString(tag.getId())); } catch (Exception ex) { mException = ex; return null; } } @Override protected void onPostExecute(MifareCard card) { if (mException != null) { if (mException instanceof UnsupportedTagException) { UnsupportedTagException ex = (UnsupportedTagException) mException; new AlertDialog.Builder(ReadingTagActivity.this).setTitle("Unsupported Tag") .setMessage(ex.getMessage()).setCancelable(false) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface arg0, int arg1) { finish(); } }).show(); } else { Utils.showErrorAndFinish(ReadingTagActivity.this, mException); } return; } try { String cardXml = Utils.xmlNodeToString(card.toXML().getOwnerDocument()); ContentValues values = new ContentValues(); values.put(CardsTableColumns.TYPE, card.getCardType().toInteger()); values.put(CardsTableColumns.TAG_SERIAL, Utils.getHexString(card.getTagId())); values.put(CardsTableColumns.DATA, cardXml); values.put(CardsTableColumns.SCANNED_AT, card.getScannedAt().getTime()); Uri uri = getContentResolver().insert(CardProvider.CONTENT_URI_CARD, values); startActivity(new Intent(Intent.ACTION_VIEW, uri)); finish(); } catch (Exception ex) { Utils.showErrorAndFinish(ReadingTagActivity.this, ex); } } @Override protected void onProgressUpdate(String... values) { textView.setText(values[0]); } }.execute(); } catch (Exception ex) { Utils.showErrorAndFinish(this, ex); } }
From source file:github.popeen.dsub.util.SongDBHandler.java
public void importData(JSONArray array) { SQLiteDatabase db = this.getReadableDatabase(); try {// w ww.jav a 2 s . c o m for (int i = 0; i < array.length(); i++) { JSONObject row = array.getJSONObject(i); ContentValues values = new ContentValues(); values.put(SONGS_ID, row.getInt("SONGS_ID")); values.put(SONGS_SERVER_KEY, row.getInt("SONGS_SERVER_KEY")); values.put(SONGS_SERVER_ID, row.getString("SONGS_SERVER_ID")); values.put(SONGS_COMPLETE_PATH, row.getString("SONGS_COMPLETE_PATH")); values.put(SONGS_LAST_PLAYED, row.getInt("SONGS_LAST_PLAYED")); values.put(SONGS_LAST_COMPLETED, row.getInt("SONGS_LAST_COMPLETED")); db.insertWithOnConflict(TABLE_SONGS, null, values, SQLiteDatabase.CONFLICT_REPLACE); } } catch (Exception e) { } }
From source file:com.seneca.android.senfitbeta.DbHelper.java
public void addUsers(String email, String password) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(COLUMN_EMAIL, email);//from ww w.j ava2 s . c o m values.put(COLUMN_PASS, password); long id = db.insert(USER_TABLE, null, values); db.close(); }
From source file:org.odk.collect.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 {//from www . j ava 2 s . c o m // 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 = Collect.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 = Collect.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 = Collect.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(); message += e.getMessage(); } count++; if (message.equalsIgnoreCase("")) { message = Collect.getInstance().getString(R.string.success); } result.put(fd.formName, message); } return result; }
From source file:com.example.rafa.sunshine.app.experiments.FetchWeatherTask.java
/** * Helper method to handle insertion of a new location in the weather database. * * @param locationSetting The location string used to request updates from the server. * @param cityName A human-readable city name, e.g "Mountain View" * @param lat the latitude of the city/*from w ww. j a va 2 s.co m*/ * @param lon the longitude of the city * @return the row ID of the added location. */ long addLocation(String locationSetting, String cityName, double lat, double lon) { long locationId; // First, check if the location with this city name exists in the db Cursor locationCursor = mContext.getContentResolver().query(WeatherContract.LocationEntry.CONTENT_URI, new String[] { WeatherContract.LocationEntry._ID }, WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ?", new String[] { locationSetting }, null); //Si ja existeix aquesta localitzaci obtenim el ID. if (locationCursor.moveToFirst()) { //ara estem al primer registre (en aquest cas l'nic) //1. obtenim l'ndex de la columna que ens interessa, en aquest camp el del ID. //2. a partir d'aquest ndex, o per a que s'entengui ms, a partir d'aquesta columna (en //el registre que estem tractant) agafem el seu valor, en aquest cas el ID. int locationIdIndex = locationCursor.getColumnIndex(WeatherContract.LocationEntry._ID);//1 locationId = locationCursor.getLong(locationIdIndex);//2 //Si no crearem la localitzaci en la db. } else { // Now that the content provider is set up, inserting rows of data is pretty simple. // First create a ContentValues object to hold the data you want to insert. ContentValues locationValues = new ContentValues(); // Then add the data, along with the corresponding name of the data type, // so the content provider knows what kind of value is being inserted. locationValues.put(WeatherContract.LocationEntry.COLUMN_CITY_NAME, cityName); locationValues.put(WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING, locationSetting); locationValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LAT, lat); locationValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LONG, lon); // Finally, insert location data into the database. Uri insertedUri = mContext.getContentResolver().insert(WeatherContract.LocationEntry.CONTENT_URI, locationValues); // The resulting URI contains the ID for the row. Extract the locationId from the Uri. locationId = ContentUris.parseId(insertedUri); } locationCursor.close(); // Wait, that worked? Yes! return locationId; }
From source file:gov.wa.wsdot.android.wsdot.service.CamerasSyncService.java
@Override protected void onHandleIntent(Intent intent) { ContentResolver resolver = getContentResolver(); Cursor cursor = null;/*from w w w . j av a 2 s. 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, projection, Caches.CACHE_TABLE_NAME + " LIKE ?", new String[] { "cameras" }, null); if (cursor != null && cursor.moveToFirst()) { long lastUpdated = cursor.getLong(0); //long deltaDays = (now - lastUpdated) / DateUtils.DAY_IN_MILLIS; //Log.d(DEBUG_TAG, "Delta since last update is " + deltaDays + " day(s)"); shouldUpdate = (Math.abs(now - lastUpdated) > (7 * DateUtils.DAY_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(CAMERAS_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(); JSONObject obj = new JSONObject(jsonFile); JSONObject result = obj.getJSONObject("cameras"); JSONArray items = result.getJSONArray("items"); List<ContentValues> cams = new ArrayList<ContentValues>(); int numItems = items.length(); for (int j = 0; j < numItems; j++) { JSONObject item = items.getJSONObject(j); ContentValues cameraData = new ContentValues(); cameraData.put(Cameras.CAMERA_ID, item.getString("id")); cameraData.put(Cameras.CAMERA_TITLE, item.getString("title")); cameraData.put(Cameras.CAMERA_URL, item.getString("url")); cameraData.put(Cameras.CAMERA_LATITUDE, item.getString("lat")); cameraData.put(Cameras.CAMERA_LONGITUDE, item.getString("lon")); cameraData.put(Cameras.CAMERA_HAS_VIDEO, item.getString("video")); cameraData.put(Cameras.CAMERA_ROAD_NAME, item.getString("roadName")); if (starred.contains(Integer.parseInt(item.getString("id")))) { cameraData.put(Cameras.CAMERA_IS_STARRED, 1); } cams.add(cameraData); } // Purge existing cameras covered by incoming data resolver.delete(Cameras.CONTENT_URI, null, null); // Bulk insert all the new cameras resolver.bulkInsert(Cameras.CONTENT_URI, cams.toArray(new ContentValues[cams.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[] { "cameras" }); 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.CAMERAS_RESPONSE"); broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT); broadcastIntent.putExtra("responseString", responseString); sendBroadcast(broadcastIntent); }
From source file:com.yuntongxun.ecdemo.storage.IMessageSqlManager.java
public static long insertSysMessage(String txt, String sessionId) { long ownThreadId = ConversationSqlManager.querySessionIdForBySessionId(sessionId); ContentValues cv = new ContentValues(); cv.put(IMessageColumn.MESSAGE_ID, UUID.randomUUID().toString()); cv.put(IMessageColumn.MESSAGE_TYPE, 0); cv.put(IMessageColumn.BODY, txt);// w ww. ja v a 2s . co m cv.put(IMessageColumn.sender, CCPAppManager.getUserId()); cv.put(IMessageColumn.SEND_STATUS, 1); cv.put(IMessageColumn.OWN_THREAD_ID, ownThreadId); cv.put(IMessageColumn.USER_DATA, "yuntongxun009" + txt); cv.put(IMessageColumn.CREATE_DATE, System.currentTimeMillis()); cv.put(IMessageColumn.RECEIVE_DATE, System.currentTimeMillis()); return getInstance().sqliteDB().insertOrThrow(DatabaseHelper.TABLES_NAME_IM_MESSAGE, null, cv); }
From source file:gov.wa.wsdot.android.wsdot.service.TravelTimesSyncService.java
@Override protected void onHandleIntent(Intent intent) { ContentResolver resolver = getContentResolver(); Cursor cursor = null;//from www.ja v a 2 s . 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[] { "travel_times" }, 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(); } } // 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(TRAVEL_TIMES_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(); JSONObject obj = new JSONObject(jsonFile); JSONObject result = obj.getJSONObject("traveltimes"); JSONArray items = result.getJSONArray("items"); List<ContentValues> times = new ArrayList<ContentValues>(); int numItems = items.length(); for (int j = 0; j < numItems; j++) { JSONObject item = items.getJSONObject(j); ContentValues timesValues = new ContentValues(); timesValues.put(TravelTimes.TRAVEL_TIMES_TITLE, item.getString("title")); timesValues.put(TravelTimes.TRAVEL_TIMES_CURRENT, item.getInt("current")); timesValues.put(TravelTimes.TRAVEL_TIMES_AVERAGE, item.getInt("average")); timesValues.put(TravelTimes.TRAVEL_TIMES_DISTANCE, item.getString("distance") + " miles"); timesValues.put(TravelTimes.TRAVEL_TIMES_ID, Integer.parseInt(item.getString("routeid"))); timesValues.put(TravelTimes.TRAVEL_TIMES_UPDATED, item.getString("updated")); if (starred.contains(Integer.parseInt(item.getString("routeid")))) { timesValues.put(TravelTimes.TRAVEL_TIMES_IS_STARRED, 1); } times.add(timesValues); } // Purge existing travel times covered by incoming data resolver.delete(TravelTimes.CONTENT_URI, null, null); // Bulk insert all the new travel times resolver.bulkInsert(TravelTimes.CONTENT_URI, times.toArray(new ContentValues[times.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[] { "travel_times" }); 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.TRAVEL_TIMES_RESPONSE"); broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT); broadcastIntent.putExtra("responseString", responseString); sendBroadcast(broadcastIntent); }
From source file:cn.code.notes.gtask.data.SqlNote.java
public SqlNote(Context context) { mContext = context;//from w w w . jav a2 s . c om mContentResolver = context.getContentResolver(); mIsCreate = true; mId = INVALID_ID; mAlertDate = 0; mBgColorId = ResourceParser.getDefaultBgId(context); mCreatedDate = System.currentTimeMillis(); mHasAttachment = 0; mModifiedDate = System.currentTimeMillis(); mParentId = 0; mSnippet = ""; mType = Notes.TYPE_NOTE; mWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID; mWidgetType = Notes.TYPE_WIDGET_INVALIDE; mOriginParent = 0; mVersion = 0; mDiffNoteValues = new ContentValues(); mDataList = new ArrayList<SqlData>(); }