/**
   * Creates the {@link ContentValues} for a {@link Location}.
   *
   * @param location the location
   * @param trackId the track id
   */
  private ContentValues createContentValues(Location location, long trackId) {
    ContentValues values = new ContentValues();
    values.put(TrackPointsColumns.TRACKID, trackId);
    values.put(TrackPointsColumns.LONGITUDE, (int) (location.getLongitude() * 1E6));
    values.put(TrackPointsColumns.LATITUDE, (int) (location.getLatitude() * 1E6));

    // Hack for Samsung phones that don't properly populate the time field
    long time = location.getTime();
    if (time == 0) {
      time = System.currentTimeMillis();
    }
    values.put(TrackPointsColumns.TIME, time);
    if (location.hasAltitude()) {
      values.put(TrackPointsColumns.ALTITUDE, location.getAltitude());
    }
    if (location.hasAccuracy()) {
      values.put(TrackPointsColumns.ACCURACY, location.getAccuracy());
    }
    if (location.hasSpeed()) {
      values.put(TrackPointsColumns.SPEED, location.getSpeed());
    }
    if (location.hasBearing()) {
      values.put(TrackPointsColumns.BEARING, location.getBearing());
    }

    if (location instanceof MyTracksLocation) {
      MyTracksLocation myTracksLocation = (MyTracksLocation) location;
      if (myTracksLocation.getSensorDataSet() != null) {
        values.put(TrackPointsColumns.SENSOR, myTracksLocation.getSensorDataSet().toByteArray());
      }
    }
    return values;
  }
Example #2
1
  public void updateFavorite(int channelId, boolean isFavorite) {

    synchronized (lock) {
      SQLiteDatabase database = getWritableDatabase();
      Cursor cursor =
          database.query(
              FAVORITE_TABLE_NAME,
              new String[] {KEY_CHANNEL_ID},
              KEY_CHANNEL_ID + "=" + channelId,
              null,
              null,
              null,
              null);

      try {
        ContentValues values = new ContentValues();
        values.put(KEY_CHANNEL_ID, channelId);
        values.put(KEY_IS_FAVORITE, isFavorite ? 1 : 0);

        if (cursor.getCount() > 0) {
          database.update(FAVORITE_TABLE_NAME, values, KEY_CHANNEL_ID + "=" + channelId, null);
        } else {
          database.insert(FAVORITE_TABLE_NAME, null, values);
        }
      } finally {
        cursor.close();
        database.close();
      }
    }
  }
 @Override
 public void onDialogSaveButtonClick(String name) {
   Log.i(MyPocApplication.LOG_TAG, "Received the data: " + name);
   ContentValues mNewValues = new ContentValues();
   mNewValues.put(DataEntryColumns.NAME, name);
   asyncQuery.startInsert(ASYNC_INSERT_TOKEN, null, DataEntryColumns.CONTENT_URI, mNewValues);
 }
Example #4
0
  public void setAsCurrent() {
    if (mUri == null) {
      return;
    }
    Cursor cur = mContext.getContentResolver().query(mUri, null, null, null, null);
    cur.moveToFirst();
    int index = cur.getColumnIndex("_id");
    String apnId = cur.getString(index);
    cur.close();

    ContentValues values = new ContentValues();
    values.put("apn_id", apnId);
    if (mSlot == -1) {
      mContext
          .getContentResolver()
          .update(Uri.parse("content://telephony/carriers/preferapn"), values, null, null);
    } else {
      int simNo = mSlot + 1;
      mContext
          .getContentResolver()
          .update(
              Uri.parse("content://telephony/carriers_sim" + simNo + "/preferapn"),
              values,
              null,
              null);
    }
  }
  @Override
  public Uri insert(Uri url, ContentValues initialValues) {
    if (URI_MATCHER.match(url) != CONTACTS) {
      throw new IllegalArgumentException("Cannot insert into URL: " + url);
    }

    ContentValues values =
        (initialValues != null) ? new ContentValues(initialValues) : new ContentValues();

    for (String colName : RosterConstants.getRequiredColumns()) {
      if (values.containsKey(colName) == false) {
        throw new IllegalArgumentException("Missing column: " + colName);
      }
    }

    SQLiteDatabase db = mOpenHelper.getWritableDatabase();

    long rowId = db.insert(TABLE_ROSTER, RosterConstants.USER_ID, values);

    if (rowId < 0) {
      throw new SQLException("Failed to insert row into " + url);
    }

    Uri noteUri = ContentUris.withAppendedId(CONTENT_URI, rowId);

    notifyChange();

    return noteUri;
  }
Example #6
0
 /** sMovieUrl 插入影片历史数据 */
 public synchronized long insertMovieHistroy(DownLoadInfo downInfo) {
   long sec = -1;
   try {
     ContentValues values = new ContentValues();
     values.put(TableName.MovieID, downInfo.getDownID());
     values.put(TableName.MovieName, downInfo.getDownName());
     values.put(TableName.MovieImgUrl, downInfo.getDownImg());
     values.put(TableName.MovieUrl, StringUtils.getDate()); // MovieUrl 在此处替代插入时间
     values.put(TableName.MoviePlaySourKey, downInfo.getDownTag());
     values.put(TableName.MoviePlayProgress, downInfo.getDownProgress());
     values.put(TableName.MovieSize, downInfo.getDownTotalSize());
     values.put(TableName.MoviePlayPosition, downInfo.getDownPosition());
     values.put(TableName.MovieLocalUrl, downInfo.getDownPath());
     database = pipiDBHelp.getWritableDatabase();
     Log.i(
         "TAG999",
         "insertMovieHistroy  = "
             + downInfo.getDownPosition()
             + "*******"
             + downInfo.getDownProgress());
     if (isMovieHistroyByID(downInfo.getDownID())) { // 存在记录,删除记录
       //	sec = database.update(PipiDBHelp.HISTROY_TABLENAME, values, "sMovieID=?",
       //			new String[]{downInfo.getDownID()});
       sec =
           database.delete(
               PipiDBHelp.HISTROY_TABLENAME, "sMovieID=?", new String[] {downInfo.getDownID()});
     }
     sec = database.insert(PipiDBHelp.HISTROY_TABLENAME, null, values);
   } catch (Exception e) {
     // TODO: handle exception
   }
   return sec;
 }
  @Override
  protected Void doInBackground(Long... params) {
    long movieId = params[0];

    WebService webService = new WebService();
    List<Trailer> trailers = webService.getMovieTrailers(movieId);

    Vector<ContentValues> cVVector = new Vector<ContentValues>(trailers.size());
    for (int i = 0; i < trailers.size(); i++) {
      Trailer trailer = trailers.get(i);
      ContentValues values = trailer.asContentValues();
      values.put(MovieContract.TrailerEntry.COLUMN_MOVIE_ID, movieId);
      cVVector.add(values);
    }

    // add to database
    int inserted = 0;
    if (cVVector.size() > 0) {
      ContentValues[] contentValues = new ContentValues[cVVector.size()];
      cVVector.toArray(contentValues);
      inserted =
          mContext
              .getContentResolver()
              .bulkInsert(MovieContract.TrailerEntry.CONTENT_URI, contentValues);
    }
    Log.d(TAG, "FetchTrailersTask Complete. " + inserted + " Inserted");

    return null;
  }
Example #8
0
  public static void addAlbumToPlaylist(ContentResolver contentResolver, long playlistId, long id) {
    String[] projection = {
      MediaStore.Audio.Media._ID,
    };

    String selection = MediaStore.Audio.Media.ALBUM_ID + "=" + id;

    Cursor cursor =
        contentResolver.query(
            MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
            projection,
            selection,
            null,
            MediaStore.Audio.Media.TRACK);

    if (cursor != null) {
      int base = getLastTrackNumber(contentResolver, playlistId) + 1;

      while (cursor.moveToNext()) {
        ContentValues contentValues = new ContentValues();
        contentValues.put(MediaStore.Audio.Playlists.Members.AUDIO_ID, cursor.getLong(0));
        contentValues.put(MediaStore.Audio.Playlists.Members.PLAY_ORDER, base);
        base++;

        contentResolver.insert(
            MediaStore.Audio.Playlists.Members.getContentUri("external", playlistId),
            contentValues);
      }
    }
  }
  private int[] modifyAmount(SQLiteDatabase db, String productId, int delta) {
    int oldAmount = getInt(db, "Inventory", "amount", 0, "productId=?", productId);
    int newAmount = oldAmount + delta;

    if (newAmount < 0) {
      Log.w(
          TAG,
          "New inventory amount of "
              + productId
              + " is negative: "
              + newAmount
              + " was: "
              + oldAmount
              + ", using 0 instead");
      newAmount = 0;
    }

    ContentValues cv = new ContentValues();
    cv.put("productId", productId);
    cv.put("amount", newAmount);

    if (count(db, "Inventory", "productId=?", productId) > 0) { // already on the table
      db.update("Inventory", cv, "productId=?", new String[] {productId});
    } else {
      db.insert("Inventory", null, cv);
    }

    Log.w(TAG, "Inventory amount of " + productId + " was: " + oldAmount + ", now: " + newAmount);
    return new int[] {oldAmount, newAmount};
  }
 @Override
 public ContentValues setUpParams(int action) {
   ContentValues values = new ContentValues();
   values.put("username", username);
   values.put("password", password);
   return values;
 }
Example #11
0
  public long addLocation(
      String addLocationSetting,
      String addLocationCity,
      double addLocationLat,
      double addLocationLon) {

    ContentResolver weatherProvider = mContext.getContentResolver();
    long locationId = 0;

    Cursor cFetchByLocation =
        weatherProvider.query(
            LocationEntry.CONTENT_URI,
            new String[] {BaseColumns._ID},
            LocationEntry.COLUMN_LOCATION_SETTING + " = ?",
            new String[] {addLocationSetting},
            null);

    if (!cFetchByLocation.moveToFirst()) {
      ContentValues locationValues = new ContentValues(4);

      locationValues.put(LocationEntry.COLUMN_LOCATION_SETTING, addLocationSetting);
      locationValues.put(LocationEntry.COLUMN_CITY_NAME, addLocationCity);
      locationValues.put(LocationEntry.COLUMN_COORD_LAT, addLocationLat);
      locationValues.put(LocationEntry.COLUMN_COORD_LONG, addLocationLon);

      Uri recordInsertedUri = weatherProvider.insert(LocationEntry.CONTENT_URI, locationValues);
      locationId = ContentUris.parseId(recordInsertedUri);
    } else {
      final int id = cFetchByLocation.getColumnIndex(BaseColumns._ID);
      locationId = cFetchByLocation.getLong(id);
    }

    cFetchByLocation.close();
    return locationId;
  }
  public static void PublishUnreadCount(Context context) {
    try {
      // Check if TeslaUnread is installed before doing some expensive database query
      ContentValues cv = new ContentValues();
      cv.put("tag", "de.luhmer.owncloudnewsreader/de.luhmer.owncloudnewsreader");
      cv.put("count", 0);
      context
          .getContentResolver()
          .insert(Uri.parse("content://com.teslacoilsw.notifier/unread_count"), cv);

      // If we get here.. TeslaUnread is installed
      DatabaseConnectionOrm dbConn = new DatabaseConnectionOrm(context);
      int count =
          Integer.parseInt(
              dbConn.getUnreadItemsCountForSpecificFolder(
                  SubscriptionExpandableListAdapter.SPECIAL_FOLDERS.ALL_UNREAD_ITEMS));

      cv.put("count", count);
      context
          .getContentResolver()
          .insert(Uri.parse("content://com.teslacoilsw.notifier/unread_count"), cv);
    } catch (IllegalArgumentException ex) {
      /* Fine, TeslaUnread is not installed. */
    } catch (Exception ex) {
      /* Some other error, possibly because the format of the ContentValues are incorrect.
      Log but do not crash over this. */

      ex.printStackTrace();
    }
  }
Example #13
0
 private void insertData(String difficulty, int won, int lost, SQLiteDatabase db) {
   ContentValues contentValues = new ContentValues();
   contentValues.put(COL_1, difficulty);
   contentValues.put(COL_2, won);
   contentValues.put(COL_3, lost);
   db.insert(TABLE_NAME, null, contentValues);
 }
Example #14
0
    /** @return ContentValues to be passed to UploadProvider.insert() */
    ContentValues toContentValues() {
      ContentValues values = new ContentValues();
      assert mTargetUrl != null;
      values.put(COLUMN_TARGET_URL, mTargetUrl.toString());

      if (!mRequestHeaders.isEmpty()) {
        encodeHttpHeaders(values);
      }

      if (!mContentDispositions.isEmpty()) {
        encodePayload(values);
      }
      // NOTE: if you change items here , you should also go to UploadProvider and add them in
      // filteredValue.
      updateFilename(mFileUri);
      putIfNonNull(values, COLUMN_LOCAL_FILENAME, mFilename);
      putIfNonNull(values, COLUMN_FILE_URI, mFileUri);
      putIfNonNull(
          values,
          COLUMN_MIME_TYPE,
          mMimeType == null ? mContext.getContentResolver().getType(mFileUri) : mMimeType);
      putIfNonNull(values, COLUMN_TITLE, new File(mFilename).getName());
      putIfNonNull(
          values, COLOMN_DATA_FIELD_NAME, mDataFieldName == null ? "file" : mDataFieldName);
      // use filename as default title.
      putIfNonNull(values, COLUMN_TITLE, mTitle);
      putIfNonNull(values, COLUMN_DESCRIPTION, mDescription);
      putIfNonNull(values, COLUMN_USER_AGENT, mUserAgent);

      values.put(COLUMN_VISIBILITY, mNotificationVisibility);
      values.put(COLUMN_ALLOW_ROAMING, mMobileAllowed);
      return values;
    }
  public void logout(String token) {

    String selectQuery =
        "SELECT * FROM " + TABLE_USER + " WHERE " + KEY_TOKEN + " = '" + token + "'";

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {

      User user = new User();
      user.setUserId(Integer.parseInt(cursor.getString(0)));

      ContentValues values = new ContentValues();
      values.put(KEY_TOKEN, "");

      // updating row
      db.update(
          TABLE_USER,
          values,
          KEY_USER_ID + " = ?",
          new String[] {String.valueOf(user.getUserId())});
    }
    cursor.close();
  }
Example #16
0
  // Update single ScavItem
  public void updateScavItem(ScavItem scavItem) {
    SQLiteDatabase db = this.getWritableDatabase();
    Log.d(TAG, db.toString());

    ContentValues values = new ContentValues();
    values.put(KEY_NAME, scavItem.get_name()); // ScavItem name
    values.put(KEY_ADDRESS, scavItem.get_address()); // ScavItem address
    values.put(KEY_DIRECTIONS, scavItem.get_directions()); // ScavItem directions
    values.put(KEY_IMAGE, scavItem.get_image()); // ScavItem image

    // Update the corresponding row
    try {
      int i =
          db.update(
              TABLE_SCAV_ITEMS,
              values,
              KEY_ID + "=?",
              new String[] {String.valueOf(scavItem.get_id())});
      if (i <= 0) {
        Log.e(TAG, "Update failed in a weird way");
      }

    } catch (Exception e) {
      Log.e(TAG, "Update failed", e);
    }
    db.close();
  }
  void addUserRole(User user, String role) {
    SQLiteDatabase db = this.getWritableDatabase();

    int role_id = 0;

    String selectQuery =
        "SELECT "
            + KEY_ROLE_ID
            + " FROM "
            + TABLE_ROLES
            + " WHERE "
            + KEY_ROLE
            + " = '"
            + role
            + "'";

    Cursor cursor = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
      role_id = Integer.parseInt(cursor.getString(0));
    }

    ContentValues values = new ContentValues();
    values.put(KEY_USER_ID, user.getUserId());
    values.put(KEY_ROLE_ID, role_id);

    // Insert Row
    db.insert(TABLE_USER_ROLES, null, values);
    db.close();
  }
Example #18
0
 /**
  * Inserts a new entry in the database, if there is no entry for the given date yet. Use this
  * method for restoring data from a backup.
  *
  * <p>This method does nothing if there is already an entry for 'date'.
  *
  * @param date the date in ms since 1970
  * @param steps the step value for 'date'; must be >= 0
  * @return true if a new entry was created, false if there was already an entry for 'date'
  */
 public boolean insertDayFromBackup(long date, int steps) {
   database.beginTransaction();
   boolean re;
   try {
     Cursor c =
         database.query(
             DB_NAME,
             new String[] {"date"},
             "date = ?",
             new String[] {String.valueOf(date)},
             null,
             null,
             null);
     re = c.getCount() == 0 && steps >= 0;
     if (re) {
       ContentValues values = new ContentValues();
       values.put("date", date);
       values.put("steps", steps);
       database.insert(DB_NAME, null, values);
     }
     c.close();
     database.setTransactionSuccessful();
   } finally {
     database.endTransaction();
   }
   return re;
 }
  public boolean addWord(String origWord, String translation) {
    ContentValues values = new ContentValues();
    values.put(NewWordsTable.Cols.ORIGINAL_WORD, origWord);
    values.put(NewWordsTable.Cols.TRANSLATION, translation);

    return mDatabase.insert(NewWordsTable.NAME, null, values) == -1;
  }
Example #20
0
  /**
   * Inserts a new entry in the database, if there is no entry for the given date yet. Steps should
   * be the current number of steps and it's negative value will be used as offset for the new date.
   * Also adds 'steps' steps to the previous day, if there is an entry for that date.
   *
   * <p>This method does nothing if there is already an entry for 'date' - use {@link #updateSteps}
   * in this case.
   *
   * <p>To restore data from a backup, use {@link #insertDayFromBackup}
   *
   * @param date the date in ms since 1970
   * @param steps the current step value to be used as negative offset for the new day; must be >= 0
   */
  public void insertNewDay(long date, int steps) {
    database.beginTransaction();
    try {
      Cursor c =
          database.query(
              DB_NAME,
              new String[] {"date"},
              "date = ?",
              new String[] {String.valueOf(date)},
              null,
              null,
              null);
      if (c.getCount() == 0 && steps >= 0) {
        ContentValues values = new ContentValues();
        values.put("date", date);
        // use the negative steps as offset
        values.put("steps", -steps);
        database.insert(DB_NAME, null, values);

        // add 'steps' to yesterdays count
        date -= 24 * 60 * 60 * 1000;
        updateSteps(date, steps);
      }
      c.close();
      if (Logger.LOG) {
        Logger.log("insertDay " + date + " / " + steps);
        logState();
      }
      database.setTransactionSuccessful();
    } finally {
      database.endTransaction();
    }
  }
  /**
   * Saves the reminders, if they changed. Returns true if the database was updated.
   *
   * @param cr the ContentResolver
   * @param taskId the id of the task whose reminders are being updated
   * @param reminderMinutes the array of reminders set by the user
   * @param originalMinutes the original array of reminders
   * @return true if the database was updated
   */
  static boolean saveReminders(
      ContentResolver cr,
      long taskId,
      ArrayList<Integer> reminderMinutes,
      ArrayList<Integer> originalMinutes) {
    // If the reminders have not changed, then don't update the database
    if (reminderMinutes.equals(originalMinutes)) {
      return false;
    }

    // Delete all the existing reminders for this event
    String where = ReminderProvider.Reminders.TASK_ID + "=?";
    String[] args = new String[] {Long.toString(taskId)};
    cr.delete(ReminderProvider.Reminders.CONTENT_URI, where, args);

    ContentValues values = new ContentValues();
    int len = reminderMinutes.size();

    // Insert the new reminders, if any
    for (int i = 0; i < len; i++) {
      int minutes = reminderMinutes.get(i);

      values.clear();
      values.put(ReminderProvider.Reminders.MINUTES, minutes);
      values.put(ReminderProvider.Reminders.METHOD, ReminderProvider.Reminders.METHOD_ALERT);
      values.put(ReminderProvider.Reminders.TASK_ID, taskId);
      cr.insert(ReminderProvider.Reminders.CONTENT_URI, values);
    }
    return true;
  }
  protected void toggleBoughtItem(String contentUri) {

    if (!OPEN_IN_PHONE_ACTION_RETRY.equals(contentUri)) {

      ContentValues values = new ContentValues();

      if (getItem(mPos).bought) {

        Log.d(LOG_TAG, "getItem(mPos).bought");

        values.put(Shopping.Contains.STATUS, Shopping.Status.WANT_TO_BUY);

      } else {

        Log.d(LOG_TAG, "NOT getItem(mPos).bought");

        values.put(Shopping.Contains.STATUS, Shopping.Status.BOUGHT);
      }

      Log.d(LOG_TAG, "           values: " + values);
      Log.d(LOG_TAG, "contentUri: " + contentUri);

      int count = getContentResolver().update(Uri.parse(contentUri), values, null, null);
      Log.v(LOG_TAG, count + " item(s) updated.");
    }

    sendShoppingItem(mPos);
  }
 public void updateBlock(byte[] blockHash, boolean isMain) {
   SQLiteDatabase db = this.mDb.getWritableDatabase();
   ContentValues cv = new ContentValues();
   cv.put(AbstractDb.BlocksColumns.IS_MAIN, isMain ? 1 : 0);
   db.update(
       AbstractDb.Tables.BLOCKS, cv, "block_hash=?", new String[] {Base58.encode(blockHash)});
 }
Example #24
0
  public int updateCustomer(Customer customer, int userid) {
    int num = 0;
    try {
      SQLiteDatabase db = this.DbHelper.getWritableDatabase();

      ContentValues values = new ContentValues();
      values.put(KEY_FIRST_NAME, customer.first_name);
      values.put(KEY_LAST_NAME, customer.last_name);
      values.put(KEY_ADDRESS, customer.address);
      values.put(KEY_ADDRESS_LANDMARK, customer.address_landmark);
      values.put(KEY_TEL_NO, customer.tel_no);
      values.put(KEY_MOBILE_NO, customer.mobile_no);
      values.put(KEY_LAST_UPDATED_USER_ID, userid);
      values.put(KEY_LAST_UPDATED_DATE, formatter.format(new Date()));
      values.put(KEY_IS_SYNCED, 0);

      num =
          db.update(
              TABLE_CUSTOMER,
              values,
              KEY_CUSTOMER_ID + " = ?",
              new String[] {String.valueOf(customer.customer_id)});
      db.close();
      Log.d("pos", "updateCustomer - success");
    } catch (Exception e) {
      Log.e("pos_error", "updateCustomer: " + e);
    }
    return num;
  }
 public void insertEntry(String username, String password) {
   ContentValues contentValues = new ContentValues();
   contentValues.put("User", username);
   contentValues.put("Password", password);
   db.insert(TABLE_name, null, contentValues);
   Toast.makeText(context, "Reminder Is Successfully Saved", Toast.LENGTH_LONG).show();
 }
Example #26
0
 public void updateEntry(long row, String name, String email) {
   // TODO Auto-generated method stub
   ContentValues cvUpdate = new ContentValues();
   cvUpdate.put(KEY_NAME, name);
   cvUpdate.put(KEY_EMAIL, email);
   ourDatabase.update(DATABASE_TABLE, cvUpdate, KEY_ROWID + "=" + row, null);
 }
Example #27
0
 public synchronized int fetchStatusUpdates() {
   Log.d(TAG, "Fetching status updates");
   Twitter twitter = this.getTwitter();
   if (twitter == null) {
     Log.d(TAG, "Twitter connection info not initialized");
     return 0;
   }
   try {
     List<Status> statusUpdates = twitter.getFriendsTimeline();
     long latestStatusCreatedAtTime = this.getStatusData().getLatestStatusCreatedAtTime();
     int count = 0;
     ContentValues contentValues = new ContentValues();
     for (Status status : statusUpdates) {
       contentValues.put(StatusData.C_ID, status.getId());
       long createdAt = status.getCreatedAt().getTime();
       contentValues.put(StatusData.C_CREATED_AT, createdAt);
       contentValues.put(StatusData.C_TEXT, status.getText());
       contentValues.put(StatusData.C_USER, status.getUser().getName());
       Log.d(TAG, "Got update with id " + status.getId() + ". Saving");
       this.getStatusData().insertOrIgnore(contentValues);
       if (latestStatusCreatedAtTime < createdAt) {
         count++;
       }
     }
     Log.d(TAG, count > 0 ? "Got" + count + " status updates" : "No new staus updates");
     return count;
   } catch (RuntimeException e) {
     Log.e(TAG, "Failed to fetch status updates", e);
     return 0;
   }
 }
Example #28
0
 public void createEntry(String name, String email) {
   // TODO Auto-generated method stub
   ContentValues cv = new ContentValues();
   cv.put(KEY_NAME, name);
   cv.put(KEY_EMAIL, email);
   ourDatabase.insert(DATABASE_TABLE, null, cv);
 }
Example #29
0
  @SuppressLint("SimpleDateFormat")
  @Override
  public Uri insert(Uri uri, ContentValues values) {
    // TODO Auto-generated method stub
    // 新增,故uri只能为collection
    if (sUriMatch.match(uri) != HISTORY_COLLECTION_URI_INDICATOR) {
      throw new IllegalArgumentException("URI =" + uri);
    }
    // 允许插入空行
    ContentValues cv;
    if (values == null) {
      cv = new ContentValues();
    } else {
      cv = new ContentValues(values);
    }
    //
    if (cv.containsKey(ChatHistoryTable.CHAT_TIME)) {
      SimpleDateFormat sdf = new SimpleDateFormat("MM/dd-HH:mm:ss");
      String now = sdf.format(new Date(System.currentTimeMillis()));
      cv.put(ChatHistoryTable.CHAT_TIME, now);
    }

    mDb = mOpenHelper.getWritableDatabase();
    long rowId = mDb.insert(ChatHistoryTable.TABLE_NAME, null, cv);
    if (rowId > 0) {
      Uri insertUri = ContentUris.withAppendedId(ChatHistoryTable.CONTENT_URI, rowId);
      mContentResolver.notifyChange(insertUri, null);
      return insertUri;
    }
    throw new SQLiteException("Failed to insert!!!");
  }
 // ///////////////////////////////////////////////////////////////////////////
 // CONTENT VALUES / PERSISTENCE
 // ///////////////////////////////////////////////////////////////////////////
 public ContentValues createContentValues(int status) {
   ContentValues cValues = super.createContentValues(status);
   if (file != null) {
     cValues.put(OperationSchema.COLUMN_NODE_ID, file.getPath());
   }
   return cValues;
 }