Exemplo n.º 1
0
    public void onCreate(SQLiteDatabase db) {
      Log.d(LOG_TAG, "--- onCreate database ---");
      ContentValues cv = new ContentValues();

      // создаем таблицу должностей
      db.execSQL("create table position (id integer primary key, name text, salary integer);");

      // заполняем ее
      for (int i = 0; i < position_id.length; i++) {
        cv.clear();
        cv.put("id", position_id[i]);
        cv.put("name", position_name[i]);
        cv.put("salary", position_salary[i]);
        db.insert("position", null, cv);
      }

      db.execSQL(
          "create table people (id integer primary key autoincrement, name text, posid integer);");

      for (int i = 0; i < people_name.length; i++) {
        cv.clear();
        cv.put("name", people_name[i]);
        cv.put("posid", people_posid[i]);
        db.insert("people", null, cv);
      }
    }
Exemplo n.º 2
0
  /** Update the percentages of our workouts. */
  public void updatePercentages(int[] weekOne, int[] weekTwo, int[] weekThree, int[] weekFour) {
    ContentValues cv = new ContentValues();

    cv.put(KEY_WEEK_ONE, weekOne[0]);
    cv.put(KEY_WEEK_TWO, weekTwo[0]);
    cv.put(KEY_WEEK_THREE, weekThree[0]);
    cv.put(KEY_WEEK_FOUR, weekFour[0]);

    mDatabase.update(DATABASE_TABLE_PERCENT, cv, KEY_ROW_ID + "=?", new String[] {"1"});

    cv.clear();
    cv.put(KEY_WEEK_ONE, weekOne[1]);
    cv.put(KEY_WEEK_TWO, weekTwo[1]);
    cv.put(KEY_WEEK_THREE, weekThree[1]);
    cv.put(KEY_WEEK_FOUR, weekFour[1]);

    mDatabase.update(DATABASE_TABLE_PERCENT, cv, KEY_ROW_ID + "=?", new String[] {"2"});

    cv.clear();
    cv.put(KEY_WEEK_ONE, weekOne[2]);
    cv.put(KEY_WEEK_TWO, weekTwo[2]);
    cv.put(KEY_WEEK_THREE, weekThree[2]);
    cv.put(KEY_WEEK_FOUR, weekFour[2]);

    mDatabase.update(DATABASE_TABLE_PERCENT, cv, KEY_ROW_ID + "=?", new String[] {"3"});
  }
Exemplo n.º 3
0
    public void onCreate(SQLiteDatabase db) {
      ContentValues cv = new ContentValues();
      db.execSQL(
          "create table position ("
              + " id integer primary key, "
              + " name text, "
              + " salary integer);");
      for (int i = 0; i < position_id.length; i++) {
        cv.clear();
        cv.put("id", position_id[i]);
        cv.put("name", position_name[i]);
        cv.put("salary", position_salary[i]);
        db.insert("position", null, cv);
      }

      db.execSQL(
          "create table people ("
              + " id integer primary key autoincrement, "
              + " name text, "
              + " posid integer);");
      for (int i = 0; i < people_name.length; i++) {
        cv.clear();
        cv.put("name", people_name[i]);
        cv.put("posid", people_posid[i]);
        db.insert("people", null, cv);
      }
    }
Exemplo n.º 4
0
  /** Insert the percentages for our workouts. */
  public void insertWeekPercentages(int[] weekOne, int[] weekTwo, int[] weekThree, int[] weekFour) {
    ContentValues cv = new ContentValues();

    cv.put(KEY_WEEK_ONE, weekOne[0]);
    cv.put(KEY_WEEK_TWO, weekTwo[0]);
    cv.put(KEY_WEEK_THREE, weekThree[0]);
    cv.put(KEY_WEEK_FOUR, weekFour[0]);

    mDatabase.insert(DATABASE_TABLE_PERCENT, null, cv);

    cv.clear();
    cv.put(KEY_WEEK_ONE, weekOne[1]);
    cv.put(KEY_WEEK_TWO, weekTwo[1]);
    cv.put(KEY_WEEK_THREE, weekThree[1]);
    cv.put(KEY_WEEK_FOUR, weekFour[1]);

    mDatabase.insert(DATABASE_TABLE_PERCENT, null, cv);

    cv.clear();
    cv.put(KEY_WEEK_ONE, weekOne[2]);
    cv.put(KEY_WEEK_TWO, weekTwo[2]);
    cv.put(KEY_WEEK_THREE, weekThree[2]);
    cv.put(KEY_WEEK_FOUR, weekFour[2]);

    mDatabase.insert(DATABASE_TABLE_PERCENT, null, cv);
  }
Exemplo n.º 5
0
  /** 由于我拿到的中国城市信息是xml格式的,我先将其转化为json,然后在这里写入数据库中 */
  public void jsonToDb() {

    ChinaDBOpenHelper dbOpenHelper = new ChinaDBOpenHelper(context);
    SQLiteDatabase database = dbOpenHelper.getReadableDatabase();

    // 获取到json字符串,并保存在StringBuffer中
    StringBuffer sb = new StringBuffer();
    byte[] buffer = new byte[1024];
    String line;
    try {
      InputStream is = context.getAssets().open("location.json");
      BufferedReader br = new BufferedReader(new InputStreamReader(is));

      while ((line = br.readLine()) != null) {
        sb.append(line);
      }
    } catch (IOException e) {
      e.printStackTrace();
    }

    // 将json字符串转化为对象
    Gson gson = new Gson();
    China chinaBean = gson.fromJson(sb.toString(), China.class);
    List<Province> provinceList = chinaBean.getProvinceList();

    for (Province province : provinceList) {
      ContentValues values = new ContentValues(); // 插入所有省份信息
      values.put("_id", province.getId());
      values.put("name", province.getName());
      database.insert("province", null, values);
      values.clear();

      for (City city : province.getCityList()) {
        ContentValues values1 = new ContentValues(); // 插入所有城市信息
        values1.put("_id", city.getId());
        values1.put("name", city.getName());
        values1.put("provinceId", province.getId());
        database.insert("city", null, values1);
        values1.clear();

        for (County county : city.getCountyList()) { // 插入所有区域信息,其中County中的_id为天气城市代码
          ContentValues values2 = new ContentValues();
          values2.put("_id", county.getWeatherCode());
          values2.put("name", county.getName());
          values2.put("cityId", city.getId());
          database.insert("county", null, values2);
          values2.clear();
        }
      }
    }

    database.close();
    dbOpenHelper.close();
  }
Exemplo n.º 6
0
 @Override
 public int delete(Uri uri, String where, String[] whereArgs) {
   String table;
   int count;
   switch (sUriMatcher.match(uri)) {
     case TIMERS:
       table = TABLE_TIMERS;
       where = ID + "=?";
       count = mDB.delete(table, where, whereArgs);
       where = TIMERSID + "=?";
       table = TABLE_TIMES;
       mDB.delete(table, where, whereArgs);
       getContext().getContentResolver().notifyChange(uri, null);
       return count;
     case TIMES:
       table = TABLE_TIMES;
       break;
     case TIMES_ID:
       table = TABLE_TIMES;
       where = where + ID2 + "=" + uri.getLastPathSegment();
       break;
     case RESETCOUNTERS:
       table = TABLE_TIMES;
       count = mDB.delete(table, where, whereArgs);
       Cursor c =
           mDB.query(
               TABLE_TIMERS, new String[] {RecordsDbHelper.ID}, null, null, null, null, null);
       ContentValues cv = new ContentValues();
       while (c.moveToNext()) {
         int id = c.getInt(0);
         cv.clear();
         cv.put(RecordsDbHelper.TIMERSID, id);
         if (id == 1) cv.put(STARTTIME, (new Date()).getTime());
         mDB.insert(TABLE_TIMES, null, cv);
       }
       cv.clear();
       cv.put(RecordsDbHelper.ISRUNNING, 0);
       mDB.update(
           TABLE_TIMERS, cv, RecordsDbHelper.ISRUNNING + "=?", new String[] {String.valueOf(1)});
       cv.clear();
       cv.put(RecordsDbHelper.ISRUNNING, 1);
       mDB.update(TABLE_TIMERS, cv, RecordsDbHelper.ID + "=?", new String[] {String.valueOf(1)});
       getContext().getContentResolver().notifyChange(uri, null);
       return count;
     default:
       throw new IllegalArgumentException("Unknown URI " + uri);
   }
   count = mDB.delete(table, where, whereArgs);
   getContext().getContentResolver().notifyChange(uri, null);
   return count;
 }
Exemplo n.º 7
0
  public void testCatalogsQueryOneItem() {
    String targetName = "target";
    int targetType = Constants.CatalogType.CATALOG;
    // insert items
    ContentValues cv = new ContentValues(2);
    cv.put(CatalogProviderContract.Tables.CatalogItems.TITLE_COLUMN, "catalog1");
    cv.put(
        CatalogProviderContract.Tables.CatalogItems.ITEM_TYPE_COLUMN,
        Constants.CatalogType.CATALOG);
    getMockContentResolver().insert(CatalogProviderContract.CATALOGS_URI, cv);
    cv.clear();
    cv.put(CatalogProviderContract.Tables.CatalogItems.TITLE_COLUMN, targetName);
    cv.put(CatalogProviderContract.Tables.CatalogItems.ITEM_TYPE_COLUMN, targetType);
    Uri targetUri = getMockContentResolver().insert(CatalogProviderContract.CATALOGS_URI, cv);
    cv.clear();
    cv.put(CatalogProviderContract.Tables.CatalogItems.TITLE_COLUMN, "catalog2");
    cv.put(
        CatalogProviderContract.Tables.CatalogItems.ITEM_TYPE_COLUMN,
        Constants.CatalogType.CATALOG);
    getMockContentResolver().insert(CatalogProviderContract.CATALOGS_URI, cv);

    String[] catalogsProjection = {
      CatalogProviderContract.Tables.CatalogItems._ID,
      CatalogProviderContract.Tables.CatalogItems.TITLE_COLUMN,
      CatalogProviderContract.Tables.CatalogItems.ITEM_TYPE_COLUMN,
      CatalogProviderContract.Tables.CatalogItems.PARENT_CATALOG_COLUMN
    };
    Cursor cursor = getMockContentResolver().query(targetUri, catalogsProjection, null, null, null);
    try {
      assertEquals(1, cursor.getCount());

      // check content
      cursor.moveToFirst();
      assertFalse(cursor.isAfterLast());
      assertEquals(
          targetName,
          cursor.getString(
              cursor.getColumnIndex(CatalogProviderContract.Tables.CatalogItems.TITLE_COLUMN)));
      assertEquals(
          targetType,
          cursor.getInt(
              cursor.getColumnIndex(CatalogProviderContract.Tables.CatalogItems.ITEM_TYPE_COLUMN)));
      assertEquals(
          Constants.ROOT_CATALOG_ID,
          cursor.getInt(
              cursor.getColumnIndex(
                  CatalogProviderContract.Tables.CatalogItems.PARENT_CATALOG_COLUMN)));
    } finally {
      cursor.close();
    }
  }
Exemplo n.º 8
0
  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case R.id.menu_add_ls:
        ContentResolver mResolver = getContentResolver();
        ContentValues values = new ContentValues();
        Uri livestockUri = Livestock.buildInsertLivestockUri();
        values.clear();
        values.put(AquaNotesDbContract.Livestock.COMMON_NAME, "Red Balloon");
        values.put(AquaNotesDbContract.Livestock.TYPE, "SPS");
        values.put(AquaNotesDbContract.Livestock.THUMBNAIL, R.drawable.red_balloon);
        values.put(AquaNotesDbContract.Livestock.TIMESTAMP, 0);
        try {
          mResolver.insert(livestockUri, values);
        } catch (SQLException e) {
          Log.e("LOG_TAG", "Inserting livestock", e);
        }

        // Directory.addToCategory(0,new LivestockEntry("Blue Balloon", R.drawable.blue_balloon));
        return true;

      default:
        return super.onOptionsItemSelected(item);
    }
  }
  public void update(Routine updatedRoutine) throws Exception {
    SQLiteDatabase database = dbHelper.getWritableDatabase();

    database.beginTransaction();
    try {
      SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.UK);
      Date date = new Date();
      ContentValues values = new ContentValues();
      int routineId = updatedRoutine.getId();
      String[] whereArgs = new String[] {Integer.toString(routineId)};
      values.put(DbHelper.ROUTINE_NAME, updatedRoutine.getName());
      values.put(DbHelper.ROUTINE_DATE_UPDATED, dateFormat.format(date));

      database.update(DbHelper.ROUTINES, values, DbHelper.ROUTINE_ID + "=?", whereArgs);
      values.clear();
      database.delete(DbHelper.STEPS, DbHelper.STEP_ROUTINE_ID + "=?", whereArgs);
      saveSteps(updatedRoutine, database);
      database.setTransactionSuccessful();
    } catch (Exception e) {
      database.endTransaction();
      database.close();
      throw e;
    }
    database.endTransaction();
    database.close();
  }
Exemplo n.º 10
0
  /** Executes on a worker thread. */
  @Override
  protected void onHandleIntent(Intent intent) {
    Log.d(TAG, "onHandleIntent");

    // Do we have yamba client?
    if (yamba == null) {
      noYamba();
      return;
    }

    // Pull the data from the cloud
    try {
      ContentValues values = new ContentValues();

      List<Status> timeline = yamba.getTimeline(20);
      for (Status status : timeline) {
        // Insert into db
        values.clear();
        values.put(StatusContract.Columns.ID, status.getId());
        values.put(StatusContract.Columns.USER, status.getUser());
        values.put(StatusContract.Columns.MESSAGE, status.getMessage());
        values.put(StatusContract.Columns.CREATED_AT, status.getCreatedAt().getTime());
        getContentResolver().insert(StatusContract.CONTENT_URI, values);

        Log.d(TAG, String.format("%s: %s", status.getUser(), status.getMessage()));
      }
    } catch (YambaClientException e) {
      e.printStackTrace();
      noYamba();
    }
  }
Exemplo n.º 11
0
  protected void insertRequestReceiveFileMsg(PeerHolder gpeer, GMessageTcp msgTcp) {
    ContentValues cv = new ContentValues();
    long date = System.currentTimeMillis();

    cv.put(MsgTable.FROM, MsgTable.FROM_INCOMING);
    cv.put(MsgTable.TYPE, MsgTable.TYPE_RECEIVE_ATTACH_REQUEST);
    cv.put(MsgTable.STATUS, MsgTable.STATUS_RECEIVE_COMPLETE);
    cv.put(MsgTable.FLAG, msgTcp.flag);
    cv.put(MsgTable.MAC_ADDRESS, gpeer.macAddress);
    cv.put(MsgTable.DATE, date);

    if (UID.curMacAddress != null && UID.curMacAddress.equals(gpeer.macAddress)) {
      cv.put(MsgTable.READ, MsgTable.READ_READED);
    }

    MsgTable.getInstance().insert(cv);

    for (int i = 0; i < msgTcp.msgAttach.length; i++) {
      cv.clear();
      long adate = System.currentTimeMillis();

      cv.put(AttachTable.MAC_ADDRESS, gpeer.macAddress);
      cv.put(AttachTable.FILE_PATH, msgTcp.msgAttach[i].filePath);
      cv.put(AttachTable.TYPE, msgTcp.msgAttach[i].type);
      cv.put(AttachTable.FLAG, msgTcp.msgAttach[i].flag);
      cv.put(AttachTable.ATT_FLAG, msgTcp.msgAttach[i].attflag);
      cv.put(AttachTable.SIZE, msgTcp.msgAttach[i].size);
      cv.put(AttachTable.DATE, adate);
      AttachTable.getInstance().insert(cv);
    }

    //	    MsgCenter.getInstance().loadPeerGDialogAttach(msgTcp.flag);

    refreshDialogAndnotibar(gpeer, date, msgTcp.msgAttach[0].filePath);
  }
Exemplo n.º 12
0
  /**
   * 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;
  }
Exemplo n.º 13
0
 @Override
 public void onReceive(Context context, Intent intent) {
   Session current = Session.getInstance();
   ContentResolver resolver = context.getContentResolver();
   ContentValues values = new ContentValues();
   values.clear();
   boolean isLogin = intent.getBooleanExtra("LoginState", false);
   try {
     if (isLogin) {
       current.isLogin(true);
       current.setServer(intent.getStringExtra("Server"));
       current.setCookie(intent.getStringExtra("Cookie"));
       values.put("Server", intent.getStringExtra("Server"));
       values.put("Cookie", intent.getStringExtra("Cookie"));
       resolver.update(Uri.parse(GlobalConst.CONTENT_SESSION_URI), values, null, null);
     } else {
       current.isLogin(false);
       current.setServer("");
       current.setCookie("");
       values.put("Server", "");
       values.put("Cookie", "");
       resolver.update(Uri.parse(GlobalConst.CONTENT_SESSION_URI), values, null, null);
     }
   } catch (IllegalArgumentException e) {
     current.isLogin(false);
     current.setServer("");
     current.setCookie("");
   }
 }
Exemplo n.º 14
0
  @Override
  public void onCreate(SQLiteDatabase db) {

    int i = 0;
    String[] taming = new String[] {"1min", "5min", "10min", "20min", "kids"};
    ContentValues values = new ContentValues();

    db.execSQL(
        "CREATE TABLE "
            + TABLE_NAME
            + " (_ID INTEGER PRIMARY KEY AUTOINCREMENT, "
            + TIMING
            + " TEXT, "
            + DAYS
            + " TEXT, "
            + TIME_OF_A_DAY
            + " TEXT);");

    while (i < 5) {
      values.put(TIMING, taming[i]);
      values.put(DAYS, "0000000");
      values.put(TIME_OF_A_DAY, "0");
      db.insert(TABLE_NAME, null, values);
      values.clear();
      i++;
    }
  }
Exemplo n.º 15
0
  @Override
  public void onCreate(SQLiteDatabase db) {
    // create table
    String sqlQuery =
        String.format(
            "CREATE TABLE %s (_id INTEGER PRIMARY KEY AUTOINCREMENT, %s TEXT, %s TEXT)",
            AnswersDatabase.TABLE,
            AnswersDatabase.Columns.QUESTION,
            AnswersDatabase.Columns.ANSWERS);
    db.execSQL(sqlQuery);

    // insert values
    ContentValues values = new ContentValues();
    values.clear();
    for (Questions question : Questions.values()) {
      Log.d(
          "AnswersDatabaseHelper",
          "inserting: " + question.getQuestionText() + ": " + question.getPossibleAnswers());
      values.put(AnswersDatabase.Columns.QUESTION, question.getQuestionText());
      values.put(AnswersDatabase.Columns.ANSWERS, question.getPossibleAnswers());
      db.insertWithOnConflict(AnswersDatabase.TABLE, null, values, SQLiteDatabase.CONFLICT_IGNORE);
    }

    Log.d(
        "MainActivity",
        "Number of entries in database: "
            + DatabaseUtils.queryNumEntries(db, AnswersDatabase.TABLE));
    Log.d("AnswersDatabaseHelper", "creating answers table; pre-populating with answers");
  }
  @Override
  protected void initTempProvider(SyncableContentProvider cp) {
    // TODO: don't use the real db's calendar id's.  create new ones locally and translate
    // during CalendarProvider's merge.

    // populate temp provider with calendar ids, so joins work.
    ContentValues map = new ContentValues();
    Cursor c =
        getContext()
            .getContentResolver()
            .query(
                Calendar.Calendars.CONTENT_URI,
                CALENDARS_PROJECTION,
                SELECT_BY_ACCOUNT,
                new String[] {getAccount()},
                null /* sort order */);
    final int idIndex = c.getColumnIndexOrThrow(Calendars._ID);
    final int urlIndex = c.getColumnIndexOrThrow(Calendars.URL);
    final int timezoneIndex = c.getColumnIndexOrThrow(Calendars.TIMEZONE);
    while (c.moveToNext()) {
      map.clear();
      map.put(Calendars._ID, c.getLong(idIndex));
      map.put(Calendars.URL, c.getString(urlIndex));
      map.put(Calendars.TIMEZONE, c.getString(timezoneIndex));
      cp.insert(Calendar.Calendars.CONTENT_URI, map);
    }
    c.close();
  }
 /* addCourse - adds all information for a course to the database adding
  * course, offerings, tasks and contacts information, if information exists
  * for the course then an update is done, otherwise and insert is done
  * @param course - the course information to add to the course table
  */
 public void addCourse(Course course) {
   SQLiteDatabase db = this.getWritableDatabase();
   ContentValues values = new ContentValues();
   long num = 0;
   boolean update = false;
   // check if the course already exists in the table
   num =
       DatabaseUtils.queryNumEntries(
           db,
           TABLE_COURSES,
           KEY_SUBJ + " ='" + course.mSubject + "' AND " + KEY_CODE + "='" + course.mCode + "'");
   if (num > 0) // if it exists then do an update
   update = true;
   // values to be added to the table
   values.put(KEY_SUBJ, course.mSubject); // subject code
   values.put(KEY_CODE, course.mCode);
   values.put(KEY_DESC, course.mDesc);
   values.put(KEY_INSTRUCTOR, course.mInstructor);
   values.put(KEY_INSTREMAIL, course.mInstructor_email);
   // Inserting or updating Row
   if (update)
     db.update(
         TABLE_COURSES,
         values,
         KEY_SUBJ + " ='" + course.mSubject + "' AND " + KEY_CODE + "='" + course.mCode + "'",
         null);
   else db.insert(TABLE_COURSES, null, values);
   db.close(); // Closing database connection
   values.clear();
   addOfferings(course); // add the offerings for the course
   addTasks(course); // add the tasks for the course
   addContacts(course.mContacts); // add the contacts for the course
   db.close(); // close the database
 }
Exemplo n.º 18
0
  public void testCatalogsInsert() {
    ContentValues cv = new ContentValues(2);
    cv.put(CatalogProviderContract.Tables.CatalogItems.TITLE_COLUMN, "catalog1");
    cv.put(
        CatalogProviderContract.Tables.CatalogItems.ITEM_TYPE_COLUMN,
        Constants.CatalogType.CATALOG);
    getMockContentResolver().insert(CatalogProviderContract.CATALOGS_URI, cv);
    String[] catalogsProjection = {CatalogProviderContract.Tables.CatalogItems._ID};
    Cursor cursor =
        getMockContentResolver()
            .query(CatalogProviderContract.CATALOGS_URI, catalogsProjection, null, null, null);
    try {
      assertEquals(1, cursor.getCount());
    } finally {
      cursor.close();
    }

    cv.clear();
    cv.put(CatalogProviderContract.Tables.CatalogItems.TITLE_COLUMN, "catalog2");
    cv.put(
        CatalogProviderContract.Tables.CatalogItems.ITEM_TYPE_COLUMN,
        Constants.CatalogType.CATALOG);
    getMockContentResolver().insert(CatalogProviderContract.CATALOGS_URI, cv);
    cursor =
        getMockContentResolver()
            .query(CatalogProviderContract.CATALOGS_URI, catalogsProjection, null, null, null);
    try {
      assertEquals(2, cursor.getCount());
    } finally {
      cursor.close();
    }
  }
Exemplo n.º 19
0
 @Override
 public long insertMessageInfo(Context context, MessageInfoModel info) {
   ContentValues values = convertMessageInfo2CV(info);
   long result = DBManager.insert(context, TableMessage.TABLE_NAME, values);
   values.clear();
   return result;
 }
Exemplo n.º 20
0
  public void testCatalogsDeleteOneItem() {
    // insert items
    ContentValues cv = new ContentValues(2);
    cv.put(CatalogProviderContract.Tables.CatalogItems.TITLE_COLUMN, "catalog1");
    cv.put(
        CatalogProviderContract.Tables.CatalogItems.ITEM_TYPE_COLUMN,
        Constants.CatalogType.CATALOG);
    getMockContentResolver().insert(CatalogProviderContract.CATALOGS_URI, cv);
    cv.clear();
    cv.put(CatalogProviderContract.Tables.CatalogItems.TITLE_COLUMN, "catalog2");
    cv.put(
        CatalogProviderContract.Tables.CatalogItems.ITEM_TYPE_COLUMN,
        Constants.CatalogType.CATALOG);
    Uri targetUri = getMockContentResolver().insert(CatalogProviderContract.CATALOGS_URI, cv);
    cv.clear();
    cv.put(CatalogProviderContract.Tables.CatalogItems.TITLE_COLUMN, "catalog2");
    cv.put(
        CatalogProviderContract.Tables.CatalogItems.ITEM_TYPE_COLUMN,
        Constants.CatalogType.CATALOG);
    getMockContentResolver().insert(CatalogProviderContract.CATALOGS_URI, cv);

    // check count
    String[] catalogsProjection = {CatalogProviderContract.Tables.CatalogItems._ID};
    Cursor cursor =
        getMockContentResolver()
            .query(CatalogProviderContract.CATALOGS_URI, catalogsProjection, null, null, null);
    try {
      assertEquals(3, cursor.getCount());
    } finally {
      cursor.close();
    }

    // delete one item
    assertEquals(1, getMockContentResolver().delete(targetUri, null, null));

    // check count
    cursor =
        getMockContentResolver()
            .query(CatalogProviderContract.CATALOGS_URI, catalogsProjection, null, null, null);
    try {
      assertEquals(2, cursor.getCount());
    } finally {
      cursor.close();
    }
  }
Exemplo n.º 21
0
 public void insert(String id) {
   db = this.getWritableDatabase();
   row = new ContentValues();
   row.put("id", id);
   db.insert("googleeventlist", null, row);
   row.clear();
   db.close();
   this.close();
 }
Exemplo n.º 22
0
 @Override
 public boolean updateMessageInfo(Context context, MessageInfoModel info) {
   ContentValues values = convertMessageInfo2CV(info);
   String where = TableMessage.Column.MESSAGE_ID + " = ?";
   String[] args = new String[] {info.id};
   boolean result = DBManager.update(context, TableMessage.TABLE_NAME, values, where, args) != -1;
   values.clear();
   return result;
 }
Exemplo n.º 23
0
  /**
   * Test case for the behavior of the ContactsProvider's groups table It does not test any APIs in
   * android.provider.Contacts.java
   */
  public void testGroupsTable() {
    final String[] GROUPS_PROJECTION =
        new String[] {Groups._ID, Groups.NAME, Groups.NOTES, Groups.SYSTEM_ID};
    final int ID_INDEX = 0;
    final int NAME_INDEX = 1;
    final int NOTES_INDEX = 2;
    final int SYSTEM_ID_INDEX = 3;

    String insertGroupsName = "name_insert";
    String insertGroupsNotes = "notes_insert";
    String updateGroupsNotes = "notes_update";
    String updateGroupsSystemId = "system_id_update";

    try {
      // Test: insert
      ContentValues value = new ContentValues();
      value.put(GroupsColumns.NAME, insertGroupsName);
      value.put(GroupsColumns.NOTES, insertGroupsNotes);
      value.put(GroupsColumns.SYSTEM_ID, Groups.GROUP_MY_CONTACTS);

      Uri uri = mProvider.insert(Groups.CONTENT_URI, value);
      Cursor cursor =
          mProvider.query(
              Groups.CONTENT_URI,
              GROUPS_PROJECTION,
              Groups._ID + " = ?",
              new String[] {uri.getPathSegments().get(1)},
              null);
      assertTrue(cursor.moveToNext());
      assertEquals(insertGroupsName, cursor.getString(NAME_INDEX));
      assertEquals(insertGroupsNotes, cursor.getString(NOTES_INDEX));
      assertEquals(Groups.GROUP_MY_CONTACTS, cursor.getString(SYSTEM_ID_INDEX));
      int id = cursor.getInt(ID_INDEX);
      cursor.close();

      // Test: update
      value.clear();
      value.put(GroupsColumns.NOTES, updateGroupsNotes);
      value.put(GroupsColumns.SYSTEM_ID, updateGroupsSystemId);

      assertEquals(1, mProvider.update(uri, value, null, null));
      cursor =
          mProvider.query(
              Groups.CONTENT_URI, GROUPS_PROJECTION, Groups._ID + " = " + id, null, null);
      assertTrue(cursor.moveToNext());
      assertEquals(updateGroupsNotes, cursor.getString(NOTES_INDEX));
      assertEquals(updateGroupsSystemId, cursor.getString(SYSTEM_ID_INDEX));
      cursor.close();

      // Test: delete
      assertEquals(1, mProvider.delete(uri, null, null));
    } catch (RemoteException e) {
      fail("Unexpected RemoteException");
    }
  }
Exemplo n.º 24
0
  private void saveStackBlocking() {
    final ContentResolver resolver = getContentResolver();
    final ContentValues values = new ContentValues();

    final byte[] rawStack = DurableUtils.writeToArrayOrNull(mState.stack);
    if (mState.action == ACTION_CREATE || mState.action == ACTION_OPEN_TREE) {
      // Remember stack for last create
      values.clear();
      values.put(RecentColumns.KEY, mState.stack.buildKey());
      values.put(RecentColumns.STACK, rawStack);
      resolver.insert(RecentsProvider.buildRecent(), values);
    }

    // Remember location for next app launch
    final String packageName = getCallingPackageMaybeExtra();
    values.clear();
    values.put(ResumeColumns.STACK, rawStack);
    values.put(ResumeColumns.EXTERNAL, 0);
    resolver.insert(RecentsProvider.buildResume(packageName), values);
  }
  private void deletedEntryToContentValues(
      Long syncLocalId, EventEntry event, ContentValues values) {
    // see #deletedCursorToEntry.  this deletion cannot be an exception to a recurrence (e.g.,
    // deleting an instance of a repeating event) -- new recurrence exceptions would be
    // insertions.
    values.clear();

    // Base sync info
    values.put(Events._SYNC_LOCAL_ID, syncLocalId);
    values.put(Events._SYNC_ID, event.getId());
    values.put(Events._SYNC_VERSION, event.getEditUri());
  }
Exemplo n.º 26
0
 @Override
 public boolean insertMessageInfo(Context context, List<MessageInfoModel> list) {
   List<ContentValues> values = new ArrayList<ContentValues>();
   for (MessageInfoModel info : list) {
     values.add(convertMessageInfo2CV(info));
   }
   boolean result = DBManager.bulkInsert(context, TableMessage.TABLE_NAME, values);
   for (ContentValues cv : values) {
     cv.clear();
   }
   return result;
 }
Exemplo n.º 27
0
  @Override
  public void store(@NonNull SQLiteDatabase db, @NonNull List<? extends Page> mPages) {
    if (mPages.isEmpty()) {
      return;
    }

    ContentValues pageValues = new ContentValues(14);
    ContentValues authorValues = new ContentValues(3);
    for (Page mPage : mPages) {
      List<Page> pages = new ArrayList<>();
      pages.add(mPage);
      pages.addAll(mPage.getSubPages());
      for (Page page : pages) {
        pageValues.clear();
        pageValues.put(CacheHelper.PAGE_ID, page.getId());
        pageValues.put(CacheHelper.PAGE_TITLE, page.getTitle());
        pageValues.put(CacheHelper.PAGE_TYPE, page.getType());
        pageValues.put(CacheHelper.PAGE_STATUS, page.getStatus());
        pageValues.put(CacheHelper.PAGE_MODIFIED, page.getModified());
        pageValues.put(CacheHelper.PAGE_DESCRIPTION, page.getDescription());
        pageValues.put(CacheHelper.PAGE_CONTENT, page.getContent());
        pageValues.put(CacheHelper.PAGE_PARENT_ID, page.getParentId());
        pageValues.put(CacheHelper.PAGE_ORDER, page.getOrder());
        pageValues.put(CacheHelper.PAGE_THUMBNAIL, page.getThumbnail());
        pageValues.put(CacheHelper.PAGE_LOCATION, mLocation.getId());
        pageValues.put(CacheHelper.PAGE_LANGUAGE, mLanguage.getId());
        pageValues.put(CacheHelper.PAGE_AUTHOR, page.getAuthor().getLogin());
        pageValues.put(CacheHelper.PAGE_AUTO_TRANSLATED, page.isAutoTranslated() ? 1 : 0);
        db.replace(CacheHelper.TABLE_PAGE, null, pageValues);

        authorValues.clear();
        authorValues.put(CacheHelper.AUTHOR_USERNAME, page.getAuthor().getLogin());
        authorValues.put(CacheHelper.AUTHOR_FIRSTNAME, page.getAuthor().getFirstName());
        authorValues.put(CacheHelper.AUTHOR_LASTNAME, page.getAuthor().getLastName());
        db.replace(CacheHelper.TABLE_AUTHOR, null, authorValues);

        mAvailableLanguageResource.store(db, page);
      }
    }
  }
 /**
  * 更新群组到数据库
  *
  * @param member
  * @return
  */
 public static long insertGroupMember(ECGroupMember member) {
   if (member == null
       || TextUtils.isEmpty(member.getBelong())
       || TextUtils.isEmpty(member.getVoipAccount())) {
     return -1L;
   }
   ContentValues values = null;
   try {
     if (!ContactSqlManager.hasContact(member.getVoipAccount())
         || needUpdateSexPhoto(member.getBelong(), member.getVoipAccount(), member.getSex())) {
       updateContact(member);
     } else {
       if (!TextUtils.isEmpty(member.getDisplayName())) {
         ContactSqlManager.updateContactName(member);
       }
     }
     values = new ContentValues();
     values.put(GroupMembersColumn.OWN_GROUP_ID, member.getBelong());
     values.put(GroupMembersColumn.VOIPACCOUNT, member.getVoipAccount());
     values.put(GroupMembersColumn.TEL, member.getTel());
     values.put(GroupMembersColumn.MAIL, /*member.getEmail()*/ "*****@*****.**");
     values.put(GroupMembersColumn.REMARK, member.getDisplayName());
     values.put(GroupMembersColumn.ISBAN, member.isBan() ? 2 : 1);
     values.put(GroupMembersColumn.ROLE, member.getRole());
     values.put(GroupMembersColumn.SEX, member.getSex());
     if (!isExitGroupMember(member.getBelong(), member.getVoipAccount())) {
       return getInstance()
           .sqliteDB()
           .insert(DatabaseHelper.TABLES_NAME_GROUP_MEMBERS, null, values);
     } else {
       return getInstance()
           .sqliteDB()
           .update(
               DatabaseHelper.TABLES_NAME_GROUP_MEMBERS,
               values,
               "group_id ='"
                   + member.getBelong()
                   + "'"
                   + " and voipaccount='"
                   + member.getVoipAccount()
                   + "'",
               null);
     }
   } catch (Exception e) {
     e.printStackTrace();
   } finally {
     if (values != null) {
       values.clear();
     }
   }
   return -1L;
 }
Exemplo n.º 29
0
  public void saveGameRank(String name, int score) {

    db = helper.getWritableDatabase();
    // db.execSQL("insert into game_rank(name,score) values('Peter Kwok',100)");
    // or
    ContentValues values = new ContentValues();
    values.put("name", name);
    values.put("score", score);
    db.insert("game_rank", "name", values);
    values.clear();
    db.close();
    Log.v("MyActivity", "Save Game Rank success!");
  }
Exemplo n.º 30
0
  public void insert(List<String> values) {
    if (values == null || values.isEmpty()) return;

    ContentValues cv = new ContentValues();
    for (String name : values) {
      if (contains(name)) {
        continue;
      }
      cv.clear();
      cv.put(KEY_GENRE, name);
      db.insert(GENRES_TABLE, null, cv);
    }
  }