Example #1
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();
      }
    }
  }
  @LargeTest
  public void testManyRowsTxtLong() throws Exception {
    mDatabase.execSQL("CREATE TABLE test (_id INTEGER PRIMARY KEY, txt TEXT, data INT);");

    Random random = new Random(System.currentTimeMillis());
    StringBuilder randomString = new StringBuilder(1979);
    for (int i = 0; i < 1979; i++) {
      randomString.append((random.nextInt() & 0xf) % 10);
    }

    // if cursor window size changed, adjust this value too
    final int count = 600;
    for (int i = 0; i < count; i++) {
      StringBuilder sql = new StringBuilder(2100);
      sql.append("INSERT INTO test (txt, data) VALUES ('");
      sql.append(randomString);
      sql.append("','");
      sql.append(i);
      sql.append("');");
      mDatabase.execSQL(sql.toString());
    }

    Cursor c = mDatabase.query("test", new String[] {"txt", "data"}, null, null, null, null, null);
    assertNotNull(c);

    int i = 0;
    while (c.moveToNext()) {
      assertEquals(randomString.toString(), c.getString(0));
      assertEquals(i, c.getInt(1));
      i++;
    }
    assertEquals(count, i);
    assertEquals(count, c.getCount());
    c.close();
  }
  @MediumTest
  public void testCursorUpdate() {
    mDatabase.execSQL("CREATE TABLE test (_id INTEGER PRIMARY KEY, d INTEGER, s INTEGER);");
    for (int i = 0; i < 20; i++) {
      mDatabase.execSQL("INSERT INTO test (d, s) VALUES (" + i + "," + i % 2 + ");");
    }

    Cursor c = mDatabase.query("test", null, "s = 0", null, null, null, null);
    int dCol = c.getColumnIndexOrThrow("d");
    int sCol = c.getColumnIndexOrThrow("s");

    int count = 0;
    while (c.moveToNext()) {
      assertTrue(c.updateInt(dCol, 3));
      count++;
    }
    assertEquals(10, count);

    assertTrue(c.commitUpdates());

    assertTrue(c.requery());

    count = 0;
    while (c.moveToNext()) {
      assertEquals(3, c.getInt(dCol));
      count++;
    }

    assertEquals(10, count);
    assertTrue(c.moveToFirst());
    assertTrue(c.deleteRow());
    assertEquals(9, c.getCount());
    c.close();
  }
Example #4
1
 @Override
 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
   SQLiteDatabase db = helper.getWritableDatabase();
   int count = 0;
   switch (uriMatcher.match(uri)) {
     case MEDIAS:
       count = db.update(MediaSchema.TABLE_NAME, values, selection, selectionArgs);
       break;
     case MEDIA_ID:
       count =
           db.update( //
               MediaSchema.TABLE_NAME, //
               values, //
               MediaSchema._ID
                   + " = "
                   + uri.getPathSegments().get(1)
                   + (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""), //
               selectionArgs //
               );
       break;
     default:
       throw new IllegalArgumentException("Unknown URI " + uri);
   }
   getContext().getContentResolver().notifyChange(uri, null);
   return count;
 }
  @MediumTest
  public void testLargeField() throws Exception {
    mDatabase.execSQL("CREATE TABLE test (_id INTEGER PRIMARY KEY, data TEXT);");

    StringBuilder sql = new StringBuilder(2100);
    sql.append("INSERT INTO test (data) VALUES ('");
    Random random = new Random(System.currentTimeMillis());
    StringBuilder randomString = new StringBuilder(1979);
    for (int i = 0; i < 1979; i++) {
      randomString.append((random.nextInt() & 0xf) % 10);
    }
    sql.append(randomString);
    sql.append("');");
    mDatabase.execSQL(sql.toString());

    Cursor c = mDatabase.query("test", null, null, null, null, null, null);
    assertNotNull(c);
    assertEquals(1, c.getCount());

    assertTrue(c.moveToFirst());
    assertEquals(0, c.getPosition());
    String largeString = c.getString(c.getColumnIndexOrThrow("data"));
    assertNotNull(largeString);
    assertEquals(randomString.toString(), largeString);
    c.close();
  }
Example #6
1
 private int deleteMessages(SQLiteDatabase db, String selection, String[] selectionArgs) {
   int count = 0;
   String sqlDesc = "";
   db.beginTransaction();
   try {
     // Delete all related records from MyDatabase.MsgOfUser for these messages
     String selectionG =
         " EXISTS ("
             + "SELECT * FROM "
             + Msg.TABLE_NAME
             + " WHERE ("
             + Msg.TABLE_NAME
             + "."
             + BaseColumns._ID
             + "="
             + MsgOfUser.TABLE_NAME
             + "."
             + MyDatabase.MsgOfUser.MSG_ID
             + ") AND ("
             + selection
             + "))";
     String descSuffix = "; args=" + Arrays.toString(selectionArgs);
     sqlDesc = selectionG + descSuffix;
     count = db.delete(MsgOfUser.TABLE_NAME, selectionG, selectionArgs);
     // Now delete messages themselves
     sqlDesc = selection + descSuffix;
     count = db.delete(Msg.TABLE_NAME, selection, selectionArgs);
     db.setTransactionSuccessful();
   } catch (Exception e) {
     MyLog.d(TAG, "; SQL='" + sqlDesc + "'", e);
   } finally {
     db.endTransaction();
   }
   return count;
 }
Example #7
0
 @Override
 public int delete(Uri uri, String selection, String[] selectionArgs) {
   final SQLiteDatabase db = dbHelper.getWritableDatabase();
   final int match = uriMatcher.match(uri);
   int rowsDeleted;
   switch (match) {
     case BOOK:
       rowsDeleted = db.delete(AlexandriaContract.BookEntry.TABLE_NAME, selection, selectionArgs);
       break;
     case AUTHOR:
       rowsDeleted =
           db.delete(AlexandriaContract.AuthorEntry.TABLE_NAME, selection, selectionArgs);
       break;
     case CATEGORY:
       rowsDeleted =
           db.delete(AlexandriaContract.CategoryEntry.TABLE_NAME, selection, selectionArgs);
       break;
     case BOOK_ID:
       rowsDeleted =
           db.delete(
               AlexandriaContract.BookEntry.TABLE_NAME,
               AlexandriaContract.BookEntry._ID + " = '" + ContentUris.parseId(uri) + "'",
               selectionArgs);
       break;
     default:
       throw new UnsupportedOperationException("Unknown uri: " + uri);
   }
   // Because a null deletes all rows
   if (selection == null || rowsDeleted != 0) {
     getContext().getContentResolver().notifyChange(uri, null);
   }
   return rowsDeleted;
 }
 public void cleanOldBlock() {
   SQLiteDatabase db = this.mDb.getReadableDatabase();
   String sql = "select count(0) cnt from blocks";
   Cursor c = db.rawQuery(sql, null);
   int cnt = 0;
   if (c.moveToNext()) {
     int idColumn = c.getColumnIndex("cnt");
     if (idColumn != -1) {
       cnt = c.getInt(idColumn);
     }
   }
   c.close();
   if (cnt > 5000) {
     sql = "select max(block_no) max_block_no from blocks where is_main=1";
     c = db.rawQuery(sql, null);
     int maxBlockNo = 0;
     if (c.moveToNext()) {
       int idColumn = c.getColumnIndex("max_block_no");
       if (idColumn != -1) {
         maxBlockNo = c.getInt(idColumn);
       }
     }
     c.close();
     int blockNo =
         (maxBlockNo - BitherjSettings.BLOCK_DIFFICULTY_INTERVAL)
             - maxBlockNo % BitherjSettings.BLOCK_DIFFICULTY_INTERVAL;
     db = this.mDb.getWritableDatabase();
     db.delete(AbstractDb.Tables.BLOCKS, "block_no<?", new String[] {Integer.toString(blockNo)});
   }
 }
  public List<EdificioMOD> getEdificioListbyTipoSitio(String Nombre) {
    List<EdificioMOD> lista = new ArrayList<EdificioMOD>();
    EdificioMOD _edificioMOD;
    String Idcampus = "";

    String sql1 = "select idEdificio from sitio where tipo='" + Nombre + "'";
    Cursor ccc = database.rawQuery(sql1, null);
    if (ccc.moveToFirst()) {

      do {
        Idcampus = ccc.getString(0);

        String sql =
            "select nombreEdificio from edificio where idEdificio ='"
                + Idcampus
                + "' order by nombreEdificio asc";
        Cursor c = database.rawQuery(sql, null);

        if (c != null && c.moveToFirst()) {
          do {
            _edificioMOD = new EdificioMOD();
            _edificioMOD.setNombreEdificio(c.getString(c.getColumnIndex("nombreEdificio")));

            lista.add(_edificioMOD);
          } while (c.moveToNext());
        }

      } while (ccc.moveToNext());
    }

    return lista;
  }
Example #10
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;
 }
 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)});
 }
  /**
   * Exec SQL from file in assets
   *
   * @param filename
   * @param db
   */
  protected void execSQLFile(String filename, SQLiteDatabase db) {
    // get SQL
    String sql = getSQLFromFile(filename);

    // check sql
    if (sql == null || sql.length() == 0) return;

    // split sql queries
    String[] queries = sql.split(";");

    // begin transaction
    db.beginTransaction();

    try {
      // iteratate and exec queries
      for (String query : queries) {
        db.execSQL(query);
      }

      // set transaction successful
      db.setTransactionSuccessful();
    } catch (Exception e) {
      AppLog.e(e);
    } finally {
      // end transaction
      db.endTransaction();
    }
  }
  public int updateFiche(enregistrement Enregistrement) {

    // 1. get reference to writable DB
    SQLiteDatabase db = this.getWritableDatabase();

    // 2. create ContentValues to add key "column"/value
    ContentValues values = new ContentValues();

    values.put("val_nom", Enregistrement.getVal_nom());
    values.put("val_prenom", Enregistrement.getVal_prenom());
    values.put("val_sexe", Enregistrement.getVal_sexe());
    values.put("val_phone", Enregistrement.getVal_phone());
    values.put("val_observation", Enregistrement.getVal_observation());
    values.put("jj", Enregistrement.getJj());
    values.put("mm", Enregistrement.getMm());
    values.put("yy", Enregistrement.getYy());

    // 3. updating row
    int i =
        db.update(
            TABLE_Patient, // table
            values, // column/value
            KEY_val_nom + " = ?", // selections
            new String[] {String.valueOf(Enregistrement.getVal_nom())});

    // 4. close
    db.close();

    return i;
  }
Example #14
0
  public boolean hasFavorites() {
    boolean found = false;
    synchronized (lock) {
      SQLiteDatabase database = getReadableDatabase();

      Cursor cursor =
          database.query(
              FAVORITE_TABLE_NAME,
              new String[] {KEY_IS_FAVORITE},
              KEY_IS_FAVORITE + "=1",
              null,
              null,
              null,
              null);

      try {
        if (cursor.getCount() > 0) {
          found = true;
        }
      } finally {
        cursor.close();
        database.close();
      }
    }

    return found;
  }
  // 添加player,如果有就更新,没有就添加。
  public void add(BubblePlayer player) {
    db.beginTransaction(); // 开始事务
    try {
      BubblePlayer personInDB = new BubblePlayer();
      personInDB = query(player.getId());

      // 如果没有找到就直接添加,如果找到了就更新
      if (null == personInDB) {
        db.execSQL(
            "INSERT INTO starchat_bubbleplayer(id, name, latitude, lontitude, headImg, sex) VALUES(?, ?, ?, ?, ?, ?)",
            new Object[] {
              player.getId(),
              player.getName(),
              player.getLatitude(),
              player.getLontitude(),
              player.getHeadImg(),
              player.getSex()
            });
      } else {
        updatePlayer(player);
      }
      db.setTransactionSuccessful(); // 设置事务成功完成
    } finally {
      db.endTransaction(); // 结束事务
    }
  }
  @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;
  }
  public boolean openOrCreateDatabase(Context context, File dbFile) {

    try {

      if (dbFile.exists()) {
        Log.i("SQLiteHelper", "Opening database at " + dbFile);
        mDb =
            SQLiteDatabase.openDatabase(
                dbFile.getAbsolutePath(), null, SQLiteDatabase.OPEN_READWRITE);
        return true;

        // Test if DB works properly
        // get(MapTile.TABLE_TILE_NAME, "tilekey");
        // ---

        // if (DATABASE_VERSION > db.getVersion())
        // upgrade();
      } else {
        Log.i("SQLiteHelper", "Creating database at " + dbFile);
        mDb = SQLiteDatabase.openOrCreateDatabase(dbFile, null);
        Log.i("SQLiteHelper", "Opened database at " + dbFile);
        upgradeFromFile(mDb, R.raw.sql_osm_maptile);
        return true;
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

    return false;
  }
  @Override
  public int delete(Uri url, String where, String[] whereArgs) {
    SQLiteDatabase db = mOpenHelper.getWritableDatabase();
    int count;
    switch (URI_MATCHER.match(url)) {
      case CONTACTS:
        count = db.delete(TABLE_ROSTER, where, whereArgs);
        break;

      case CONTACT_ID:
        String segment = url.getPathSegments().get(1);

        if (TextUtils.isEmpty(where)) {
          where = "_id=" + segment;
        } else {
          where = "_id=" + segment + " AND (" + where + ")";
        }

        count = db.delete(TABLE_ROSTER, where, whereArgs);
        break;

      default:
        throw new IllegalArgumentException("Cannot delete from URL: " + url);
    }

    getContext().getContentResolver().notifyChange(GROUPS_URI, null);
    notifyChange();

    return count;
  }
 public void delete(String timezone_id) {
   SQLiteDatabase db = dh.getWritableDatabase();
   db.execSQL(
       "delete from " + TimezoneDatabaseOpenHelper.TABLE_NAME + " where timezone_id = ?",
       new String[] {timezone_id});
   db.close();
 }
  @Override
  public Uri insert(Uri uri, ContentValues values) {
    final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
    final int match = sUriMatcher.match(uri);
    Uri returnUri;

    switch (match) {
      case MOVIES:
        {
          long _id = db.insert(MoviesContract.MoviesEntry.TABLE_NAME, null, values);
          if (_id > 0) returnUri = MoviesContract.MoviesEntry.buildMovieUri(_id);
          else throw new android.database.SQLException("Failed to insert row into " + uri);
          break;
        }
      case TRAILERS:
        {
          long _id = db.insert(MoviesContract.TrailersEntry.TABLE_NAME, null, values);
          if (_id > 0) returnUri = MoviesContract.TrailersEntry.buildTrailerUri(_id);
          else throw new android.database.SQLException("Failed to insert row into " + uri);
          break;
        }
      case REVIEWS:
        {
          long _id = db.insert(MoviesContract.ReviewsEntry.TABLE_NAME, null, values);
          if (_id > 0) returnUri = MoviesContract.ReviewsEntry.buildReviewUri(_id);
          else throw new android.database.SQLException("Failed to insert row into " + uri);
          break;
        }
      default:
        throw new UnsupportedOperationException("Unknown uri: " + uri);
    }
    getContext().getContentResolver().notifyChange(uri, null);
    return returnUri;
  }
Example #21
0
  @Override
  public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
    final SQLiteDatabase db = dbHelper.getWritableDatabase();
    final int match = uriMatcher.match(uri);
    int rowsUpdated;
    switch (match) {
      case BOOK:
        rowsUpdated =
            db.update(AlexandriaContract.BookEntry.TABLE_NAME, values, selection, selectionArgs);
        break;
      case AUTHOR:
        rowsUpdated =
            db.update(AlexandriaContract.AuthorEntry.TABLE_NAME, values, selection, selectionArgs);
        break;
      case CATEGORY:
        rowsUpdated =
            db.update(
                AlexandriaContract.CategoryEntry.TABLE_NAME, values, selection, selectionArgs);
        break;

      default:
        throw new UnsupportedOperationException("Unknown uri: " + uri);
    }
    if (rowsUpdated != 0) {
      getContext().getContentResolver().notifyChange(uri, null);
    }
    return rowsUpdated;
  }
 @Override
 public int delete(Uri uri, String selection, String[] selectionArgs) {
   final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
   final int match = sUriMatcher.match(uri);
   int rowsDeleted;
   // this makes delete all rows return the number of rows deleted
   if (null == selection) selection = "1";
   switch (match) {
     case MOVIES:
       rowsDeleted = db.delete(MoviesContract.MoviesEntry.TABLE_NAME, selection, selectionArgs);
       break;
     case MOVIE_WITH_ID:
       selectionArgs =
           new String[] {Long.toString(MoviesContract.MoviesEntry.getMovieIDFromUri(uri))};
       rowsDeleted =
           db.delete(MoviesContract.MoviesEntry.TABLE_NAME, sItemMovieIDSelection, selectionArgs);
       break;
     default:
       throw new UnsupportedOperationException("Unknown uri: " + uri);
   }
   // Because a null deletes all rows
   if (rowsDeleted != 0) {
     getContext().getContentResolver().notifyChange(uri, null);
   }
   return rowsDeleted;
 }
  public ArrayList<Contact> getAllContacts() {

    ArrayList<Contact> contactList = new ArrayList<Contact>();

    String selectQuery = "SELECT  * FROM " + TABLE_DETAILS;

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

    if (cursor.moveToFirst()) { // if (cursor != null)
      do {
        Contact contact = new Contact();
        contact.setName(cursor.getString(1));
        contact.setAddress(cursor.getString(4));
        contact.setPhone(cursor.getString(5));

        String interest = getInterest(cursor.getInt(0));
        contact.setInterest(interest);

        contactList.add(contact);

      } while (cursor.moveToNext());
    }
    return contactList;
  }
  @Override
  public int update(
      Uri uri, ContentValues contentValues, String selection, String[] selectionArgs) {
    final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
    final int match = sUriMatcher.match(uri);
    int rowsUpdated;

    switch (match) {
      case MOVIES:
        rowsUpdated =
            db.update(
                MoviesContract.MoviesEntry.TABLE_NAME, contentValues, selection, selectionArgs);
        break;
      case MOVIE_WITH_ID:
        selectionArgs =
            new String[] {Long.toString(MoviesContract.MoviesEntry.getMovieIDFromUri(uri))};
        rowsUpdated =
            db.update(
                MoviesContract.MoviesEntry.TABLE_NAME,
                contentValues,
                sItemMovieIDSelection,
                selectionArgs);
        break;
      default:
        throw new UnsupportedOperationException("Unknown uri: " + uri);
    }
    if (rowsUpdated != 0) {
      getContext().getContentResolver().notifyChange(uri, null);
    }
    return rowsUpdated;
  }
  // @Large
  @Suppress
  public void testLoadingThreadDelayRegisterData() throws Exception {
    mDatabase.execSQL("CREATE TABLE test (_id INTEGER PRIMARY KEY, data INT);");

    final int count = 505;
    String sql = "INSERT INTO test (data) VALUES (?);";
    SQLiteStatement s = mDatabase.compileStatement(sql);
    for (int i = 0; i < count; i++) {
      s.bindLong(1, i);
      s.execute();
    }

    int maxRead = 500;
    int initialRead = 5;
    SQLiteCursor c =
        (SQLiteCursor) mDatabase.rawQuery("select * from test;", null, initialRead, maxRead);

    TestObserver observer = new TestObserver(count, c);
    c.getCount();
    c.registerDataSetObserver(observer);
    if (!observer.quit) {
      Looper.loop();
    }
    c.close();
  }
Example #26
0
 @Override
 public void onCreate(SQLiteDatabase db) {
   // TODO Auto-generated method stub
   db.execSQL(CREATE_USER_TABLE);
   db.execSQL(CREATE_LAST_USER_TABLE);
   db.execSQL(CREATE_LOCAL_TABLE);
 }
  private void populateDefaultTable() {
    mDatabase.execSQL("CREATE TABLE test (_id INTEGER PRIMARY KEY, data TEXT);");

    mDatabase.execSQL("INSERT INTO test (data) VALUES ('" + sString1 + "');");
    mDatabase.execSQL("INSERT INTO test (data) VALUES ('" + sString2 + "');");
    mDatabase.execSQL("INSERT INTO test (data) VALUES ('" + sString3 + "');");
  }
 /** add persons */
 public void add(List<BubblePlayer> bubbleplayers) {
   db.beginTransaction(); // 开始事务
   try {
     for (BubblePlayer player : bubbleplayers) {
       // db.execSQL("INSERT INTO starchat_bubbleplayer(id, name, latitude, lontitude ) VALUES(5,
       // 'name', 31, 130)");
       BubblePlayer personInDB = new BubblePlayer();
       personInDB = query(player.getId());
       if (null == personInDB) {
         db.execSQL(
             "INSERT INTO starchat_bubbleplayer(id, name, latitude, lontitude, headImg, sex) VALUES(?, ?, ?, ?, ?, ?)",
             new Object[] {
               player.getId(),
               player.getName(),
               player.getLatitude(),
               player.getLontitude(),
               player.getHeadImg(),
               player.getSex()
             });
       } else {
         updatePlayer(player);
       }
     }
     db.setTransactionSuccessful(); // 设置事务成功完成
   } finally {
     db.endTransaction(); // 结束事务
   }
 }
Example #29
0
 public Cursor getMemos() {
   this.memos = new MemoDBHelper(this);
   SQLiteDatabase db = memos.getReadableDatabase();
   Cursor cursor = db.query("memoDB", MemoList.cols, null, null, null, null, null);
   this.startManagingCursor(cursor);
   return cursor;
 }
Example #30
0
  public void loadFavorites(List<ChannelEntry> channels) {
    synchronized (lock) {
      SQLiteDatabase database = getReadableDatabase();
      try {
        for (ChannelEntry channel : channels) {
          Cursor cursor =
              database.query(
                  FAVORITE_TABLE_NAME,
                  new String[] {KEY_IS_FAVORITE},
                  KEY_CHANNEL_ID + "=" + channel.getChannelId(),
                  null,
                  null,
                  null,
                  null);
          if (cursor.getCount() > 0) {
            cursor.moveToFirst();
            int index = cursor.getColumnIndex(KEY_IS_FAVORITE);
            boolean favorite = cursor.getInt(index) != 0;
            channel.setFavorite(favorite);
          }

          cursor.close();
        }

      } finally {
        database.close();
      }
    }
  }