Exemplo n.º 1
0
  @Override
  public Uri insertInTransaction(Uri uri, ContentValues values) {
    trace("Calling insert in transaction on URI: " + uri);

    final SQLiteDatabase db = getWritableDatabase(uri);
    int match = URI_MATCHER.match(uri);
    long id = -1;

    switch (match) {
      case CLIENTS:
        String guid = values.getAsString(Clients.GUID);
        debug("Inserting client in database with GUID: " + guid);
        id = db.insertOrThrow(TABLE_CLIENTS, Clients.GUID, values);
        break;

      case TABS:
        String url = values.getAsString(Tabs.URL);
        debug("Inserting tab in database with URL: " + url);
        id = db.insertOrThrow(TABLE_TABS, Tabs.TITLE, values);
        break;

      default:
        throw new UnsupportedOperationException("Unknown insert URI " + uri);
    }

    debug("Inserted ID in database: " + id);

    if (id >= 0) return ContentUris.withAppendedId(uri, id);

    return null;
  }
Exemplo n.º 2
0
  /* Insert new request into table 'request' */
  void insertRequest(int number) {

    // Log.i("PRIME", "Table : request : Inside insertRequest() : No -> "
    //		 										+ number);

    SQLiteDatabase db = this.getWritableDatabase();

    // ??
    String timeStamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());

    // Log.i("PRIME", "DbHandler : insertRequest() "
    //		 				+ "howmany -> " + number);

    ContentValues values = new ContentValues();
    values.put("howmany", number);
    values.put("current_count", 0);
    values.put("is_complete", "N");
    values.put("created_time", timeStamp);
    values.put("tstamp", timeStamp);

    try {
      // Inserting Row
      db.insertOrThrow(TABLE_REQUEST, null, values);

    } catch (android.database.sqlite.SQLiteConstraintException e) {
      Log.e("PRIME", "insertRequest : SQLiteConstraintException:" + e.getMessage());
    } catch (android.database.sqlite.SQLiteException e) {
      Log.e("PRIME", "SQLiteException:" + e.getMessage());
    } catch (Exception e) {
      Log.e("PRIME", "Exception:" + e.getMessage());
    }

    db.close(); // Closing database connection
  }
  public boolean updateFromServer(List<Nota> listaNotas) {
    SQLiteDatabase db =
        MyApp.getContext().openOrCreateDatabase("rescue_lite_db", Context.MODE_PRIVATE, null);
    boolean result = false;
    try {
      db.beginTransaction();

      // Delete all records
      db.delete(TABLE, null, null);

      // Insert all values
      ContentValues values;

      for (Nota nota : listaNotas) {
        values = new ContentValues();
        values.put(NOMBRE, nota.getNombre());
        values.put(DESCRIPCION, nota.getDescripcion());
        long new_id = db.insertOrThrow(TABLE, null, values);
      }

      db.setTransactionSuccessful();
      result = true;
    } catch (SQLException e) {
      // do some error handling
      result = false;
    } finally {
      db.endTransaction();
    }

    return result;
  }
Exemplo n.º 4
0
  public void insert_user(String username, String userid) {

    ContentValues content = new ContentValues();
    Cursor cur;
    content.put(NAME, username);
    content.put(ID, userid);
    Log.d("insert_user", "DB:: insert_user() " + username);
    // return db.insertOrThrow(TABLE_NAME, null, content);
    String whereclause = new String(NAME + " = \"" + username + "\"");
    cur =
        db.query(
            TABLE_NAME,
            new String[] {NAME, ID, PHOTOLIST},
            whereclause,
            null,
            null,
            null,
            null,
            null);
    if (cur.getCount() == 0) {
      db.insertOrThrow(TABLE_NAME, null, content);
      db_dump();
    } else {
      cur.moveToNext();
      Log.d("DB_read", "Found existing user : " + cur.getString(0));
    }

    return;
  }
Exemplo n.º 5
0
  /**
   * Inserts values into a table that has an unique id as identifier.
   *
   * @param table The affected table.
   * @param values The values to be inserted/ updated.
   * @param mId The identifier of the affected row.
   * @return The number of rows affected on update, the rowId on insert, -1 on error.
   */
  public int doInsertOrUpdate(String table, ContentValues values, Where where) {
    int result;

    open();
    Cursor oldVersion = get(table, where, null);

    if (oldVersion.moveToNext() && values.size() != 0) {
      String whereClause = null;
      if (where != null) {
        whereClause = where.toString().replace(" WHERE ", "");
      }

      result = mDb.update(table, values, whereClause, null);
    } else {
      String nullColumnHack = null;

      if (values.size() == 0) {
        // if no fields are defined on a model instance the nullColumnHack
        // needs to be utilized in order to insert an empty row.
        nullColumnHack = Model.PK;
      }

      result = (int) mDb.insertOrThrow(table, nullColumnHack, values);
    }

    oldVersion.close();
    close();
    return result;
  }
Exemplo n.º 6
0
 /**
  * ******************************************* Operacions sobre la taula d'assignatures
  * *******************************************
  */
 public long insertAssig(String name, String number, double avg) {
   ContentValues values = new ContentValues();
   values.put(KEY_ASSIG_NAME, name);
   values.put(KEY_ASSIG_NUMBER, number);
   values.put(KEY_ASSIG_AVG, avg);
   return database.insertOrThrow(ASSIG_TABLE, null, values);
 }
  // Adding new item
  void addItem(Item item, Item img) {

    try {
      SQLiteDatabase db = this.getWritableDatabase();

      ByteArrayOutputStream out = new ByteArrayOutputStream();
      img.get_image().compress(Bitmap.CompressFormat.PNG, 100, out);
      ContentValues values = new ContentValues();

      values.put(KEY_CATEGORY, item.get_category());
      values.put(KEY_DESC, item.get_desc()); //
      values.put(KEY_PRICE, item.get_price()); //
      values.put(KEY_DATE, item.get_date()); //
      values.put(KEY_TYPE, item.get_type()); //
      values.put(KEY_SUB_TYPE, item.get_sType()); //
      values.put(KEY_IMAGE, out.toByteArray());

      // Inserting Row
      db.insertOrThrow(TABLE_WARDROPE, null, values);
      db.close(); // Closing database connection
    } catch (Exception e) {

      System.out.println("Errrror is " + e);
    }
  }
  public void addMessage(String contactName, String messageText, boolean isLocal)
      throws SQLException {
    if (databaseHelper == null) {
      throw new RuntimeException("Database hasn't been opened.");
    }

    // Gets the data repository in write mode
    SQLiteDatabase db = databaseHelper.getWritableDatabase();

    // Create a new map of values, where column names are the keys
    ContentValues values = new ContentValues();

    String type = "local";
    if (!isLocal) {
      type = "remote";
    }

    int contactId = getContactIdFromName(contactName);

    values.put(DatabaseContract.MessageEntry.COLUMN_NAME_CONTACT_ID, contactId);
    values.put(DatabaseContract.MessageEntry.COLUMN_NAME_TEXT, messageText);
    values.put(DatabaseContract.MessageEntry.COLUMN_NAME_TYPE, type);

    db.insertOrThrow(DatabaseContract.MessageEntry.TABLE_NAME, null, values);
  }
  /*
   * Add contact if it doesn't exist already.
   * @return true if contact didn't exist (and hence was added), false if it existed
   */
  public boolean addContactIfNeded(String uri) {
    if (databaseHelper == null) {
      throw new RuntimeException("Database hasn't been opened.");
    }

    String contactName = uri.replaceAll("^sip:", "").replaceAll("@.*$", "");

    Cursor cursor = getContactFromName(contactName);
    if (!cursor.moveToFirst()) {
      // doesn't exist, need to create it
      // Gets the data repository in write mode
      SQLiteDatabase db = databaseHelper.getWritableDatabase();

      // Create a new map of values, where column names are the keys
      ContentValues values = new ContentValues();

      values.put(DatabaseContract.ContactEntry.COLUMN_NAME_NAME, contactName);
      values.put(DatabaseContract.ContactEntry.COLUMN_NAME_URI, contactName);

      db.insertOrThrow(DatabaseContract.ContactEntry.TABLE_NAME, null, values);

      return true;
    }
    return false;
  }
Exemplo n.º 10
0
  @Override
  public Uri insert(Uri uri, ContentValues values) {
    // Find matching path.
    final int match = sUriMatcher.match(uri);

    // Avoid the expensive string concatenation below if not loggable
    if (BuildConfig.DEBUG) {
      Log.v(TAG, "insert(uri=" + uri + ", values=" + values.toString() + ")");
    }

    // Get the database and run the insert
    SQLiteDatabase db = mOpenHelper.getWritableDatabase();
    switch (match) {
      case PAYMENTS:
        {
          db.insertOrThrow(AppDatabase.Tables.PAYMENTS, null, values);
          getContext().getContentResolver().notifyChange(uri, null);
          // Generate Uri with remote id.
          return AppContract.Payments.buildUri(values.getAsString(AppContract.Payments.ID));
        }
      default:
        {
          throw new UnsupportedOperationException("Unknown insert uri: " + uri);
        }
    }
  }
  public long addOrUpdateItem(ToDoItem toDoItem) {
    SQLiteDatabase db = getWritableDatabase();
    long id = -1;
    db.beginTransaction();
    try {
      ContentValues values = new ContentValues();
      values.put(KEY_DESCRIPTION, toDoItem.description);
      values.put(KEY_PRIORITY, toDoItem.priority);
      values.put(KEY_DUE_DATE, toDoItem.dueDate);
      values.put(KEY_MODIFIED_DATE, System.currentTimeMillis());

      if (toDoItem.action.contentEquals(CommonConstants.insertRecord)) {
        values.put(KEY_CREATED_DATE, System.currentTimeMillis());
        id = db.insertOrThrow(TABLE_TODO, null, values);
        db.setTransactionSuccessful();
      } else if (toDoItem.action.contentEquals(CommonConstants.updateRecord)) {
        id =
            db.update(
                TABLE_TODO, values, KEY_ID + " = ?", new String[] {Integer.toString(toDoItem.id)});
        db.setTransactionSuccessful();
      }
    } catch (Exception e) {
      Log.e(TAG, "Error while trying to update table. Exception is: " + e);
    } finally {
      db.endTransaction();
    }
    return id;
  }
  private void maybeAddBulletin(BulletinResponse bltn) {
    maybeAddBlockRef(bltn.blockReference);

    SQLiteDatabase db = getWritableDatabase();
    db.beginTransaction();
    try {
      ContentValues values = new ContentValues();
      values.put(NewBltnsTable.COLUMN_TXID, bltn.txid);
      values.put(NewBltnsTable.COLUMN_TIME, bltn.timestamp);
      values.put(NewBltnsTable.COLUMN_MSG, bltn.msg);
      values.put(NewBltnsTable.COLUMN_LAT, bltn.loc.lat);
      values.put(NewBltnsTable.COLUMN_LON, bltn.loc.lon);
      values.put(NewBltnsTable.COLUMN_H, bltn.loc.h);
      values.put(NewBltnsTable.COLUMN_AUTHOR, bltn.author);
      values.put(NewBltnsTable.COLUMN_NUM_ENDOS, bltn.numEndos);
      values.put(NewBltnsTable.COLUMN_BLOCK_REF, bltn.blockReference.hash);

      db.insertOrThrow(NewBltnsTable.TABLE_NAME, null, values);
      db.setTransactionSuccessful();

    } catch (Exception e) {

    } finally {
      db.endTransaction();
    }
  }
Exemplo n.º 13
0
 public void add(String base_server) {
   SQLiteDatabase db = dbh.getWritableDatabase();
   ContentValues datas = new ContentValues();
   datas.put("base_server", base_server);
   db.insertOrThrow(SpyConfig.SPY_CONFIG_TABLE, null, datas);
   Log.i(SpyConfig.SPY_LOGGING, "INSERT DATA");
 }
Exemplo n.º 14
0
  // insert or update(if exist) Favorte Item
  public boolean updateMessage(Message message) throws Exception {
    ContentValues values = new ContentValues();
    values.put("body", message.body);
    values.put("title", message.title);
    values.put("senderName", message.sender.name);
    values.put("senderLogo", message.sender.logo);
    values.put("senderDomain", message.sender.domain);
    values.put("receiverName", message.receiver.name);
    values.put("receiverLogo", message.receiver.logo);
    values.put("receiverDomain", message.receiver.domain);
    values.put("replyId", message.replyId);
    values.put("isSystem", message.isSystem);
    values.put("isRead", message.isRead);
    values.put("isAttached", message.isAttached);
    values.put("createdTime", message.createdTime.toLocaleString());

    SQLiteDatabase db = openDB();
    if (this.getMessage(message.id) == null) { // insert
      values.put("id", message.id);
      db.insertOrThrow("Message", null, values);
    } else { // update
      db.update("Message", values, "id=" + message.id, null);
    }
    db.close();
    return true;
  }
 public long insert(String table, ContentValues values) {
   try {
     return mDb.insertOrThrow(table, null, values);
   } catch (Exception e) {
     e.printStackTrace();
   }
   return 0;
 }
Exemplo n.º 16
0
 /**
  * 插入记录
  *
  * @param table 需要插入到的表
  * @param nullColumnHack 不允许为空的行
  * @param values 插入的值
  * @return
  */
 public boolean insertOrThrow(String table, String nullColumnHack, ContentValues values) {
   if (testSQLiteDatabase()) {
     return mSQLiteDatabase.insertOrThrow(table, nullColumnHack, values) > 0;
   } else {
     CHLogger.e(SQLiteDB.this, "数据库未打开!");
     return false;
   }
 }
  @Test(expected = android.database.SQLException.class)
  public void testInsertOrThrowWithSQLException() {
    ContentValues values = new ContentValues();
    values.put("id", 1);

    database.insertOrThrow("table_name", null, values);
    database.insertOrThrow("table_name", null, values);
  }
Exemplo n.º 18
0
  public void sendMensage(Mensagem m) {
    ContentValues values = new ContentValues();
    values.put("id_send", m.getId_send());
    values.put("id_receiver", m.getId_receiver());
    values.put("conteudo", m.getContent());

    conn.insertOrThrow("mensagem", null, values);
  }
Exemplo n.º 19
0
 public Recurring create() {
   database.beginTransaction();
   ContentValues values = getContentValues();
   values.remove("_id");
   int insertId = (int) database.insertOrThrow(TABLE, null, values);
   database.setTransactionSuccessful();
   database.endTransaction();
   return Recurring.get(insertId);
 }
 /* Adds a new item to a table */
 public int add(String tableName, ContentValues values) {
   try {
     SQLiteDatabase db = this.getWritableDatabase();
     long rowId = db.insertOrThrow(tableName, null, values);
     db.close();
     return rowId == -1 ? DatabaseHandler.UNKNOWN_ERROR : DatabaseHandler.SUCCESS;
   } catch (SQLiteConstraintException e) {
     return DatabaseHandler.RECORD_EXIST;
   }
 }
Exemplo n.º 21
0
 private void addEvent(String string, int score) {
   // Insert a new record into the Events data source.
   // You would do something similar for delete and update.
   SQLiteDatabase db = events.getWritableDatabase();
   ContentValues values = new ContentValues();
   values.put(NAME, string);
   values.put(TIME, System.currentTimeMillis());
   values.put(SCORE, score);
   db.insertOrThrow(TABLE_NAME, null, values);
 }
Exemplo n.º 22
0
 public long insertCategory(String name, String categoryFather, Bitmap picture) {
   Log.d(TAG, "insertCategory Name: " + name);
   SQLiteDatabase db = getWritableDatabase();
   ContentValues values = new ContentValues();
   values.put(CAT_COL_NAME, name);
   values.put(CAT_COL_CATEGORY_FATHER, categoryFather);
   values.put(CAT_COL_PICTURE, BitmapUtils.BitMapToString(picture));
   long id = db.insertOrThrow(TABLE_CATEGORIES, null, values);
   return id;
 }
Exemplo n.º 23
0
 public long insertIngredient(String name, double amount, int unit, String recipeName) {
   Log.d(TAG, "insertIngredient Name: " + name);
   SQLiteDatabase db = getWritableDatabase();
   ContentValues values = new ContentValues();
   values.put(ING_COL_NAME, name);
   values.put(ING_COL_AMOUNT, amount);
   values.put(ING_COL_UNIT, unit);
   values.put(ING_COL_RECIPE_NAME, recipeName);
   long id = db.insertOrThrow(TABLE_INGREDIENTS, null, values);
   return id;
 }
Exemplo n.º 24
0
 /**
  * Adds an image to the database
  *
  * @param imageObject DAO object whose info is saved
  */
 public void addToDB(ImageDAO imageObject) {
   db = taskDB.getWritableDatabase();
   ContentValues values = new ContentValues();
   values.put(MyDatabase.colImageUrl, imageObject.getUrl());
   try {
     db.insertOrThrow(MyDatabase.tableName, MyDatabase.colImageUrl, values);
   } catch (SQLException e) {
     // Whatever
   } finally {
     db.close();
   }
 }
Exemplo n.º 25
0
 public void addSearch(String name, String url, String term) {
   // I guess Java  doesn't have defaults
   if (term.equals("")) {
     term = "Search";
   }
   SQLiteDatabase db = this.getWritableDatabase();
   ContentValues values = new ContentValues();
   values.put(NAME, name);
   values.put(URL, url);
   values.put(TERM, term);
   db.insertOrThrow(TABLE_NAME, null, values);
 }
 private boolean addRootFolder(SQLiteDatabase db, long id, String bookmarksFolderName) {
   ContentValues values = new ContentValues();
   values.put(PartnerBookmarksContract.Bookmarks.ID, id);
   values.put(PartnerBookmarksContract.Bookmarks.TITLE, bookmarksFolderName);
   values.put(
       PartnerBookmarksContract.Bookmarks.PARENT,
       PartnerBookmarksContract.Bookmarks.BOOKMARK_PARENT_ROOT_ID);
   values.put(
       PartnerBookmarksContract.Bookmarks.TYPE,
       PartnerBookmarksContract.Bookmarks.BOOKMARK_TYPE_FOLDER);
   return db.insertOrThrow(TABLE_BOOKMARKS, null, values) != -1;
 }
Exemplo n.º 27
0
 private int addAccount(Account acct) {
   db.beginTransaction();
   int acct_id;
   try {
     ContentValues newValue = acctValues(acct);
     acct_id = (int) db.insertOrThrow("acct", "name", newValue);
     acct.ID = acct_id;
     db.setTransactionSuccessful();
   } finally {
     db.endTransaction();
   }
   return acct_id;
 }
Exemplo n.º 28
0
 public long insertRecipe(
     String name, String instructions, String categoryFather, Bitmap picture) {
   Log.d(TAG, "insertRecipe Name: " + name);
   SQLiteDatabase db = getWritableDatabase();
   ContentValues values = new ContentValues();
   values.put(RECIPE_COL_NAME, name);
   values.put(RECIPE_COL_INSTRUCTIONS, instructions);
   values.put(RECIPE_COL_CATEGORY_FATHER, categoryFather);
   new FreeMemory().run();
   values.put(RECIPE_COL_PICTURE, BitmapUtils.BitMapToString(picture));
   long id = db.insertOrThrow(TABLE_RECIPES, null, values);
   return id;
 }
Exemplo n.º 29
0
  @Override
  public int bulkInsert(Uri uri, ContentValues[] values) {
    final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
    final int match = sUriMatcher.match(uri);
    switch (match) {
      case FAVORITE_MOVIE:
        // allows for multiple transactions
        db.beginTransaction();

        // keep track of successful inserts
        int numInserted = 0;
        try {
          for (ContentValues value : values) {
            if (value == null) {
              throw new IllegalArgumentException("Cannot have null content values");
            }
            long _id = -1;
            try {
              _id =
                  db.insertOrThrow(
                      FavoriteMoviesContract.FavoriteMovieEntry.TABLE_FAVORITE_MOVIES, null, value);
            } catch (SQLiteConstraintException e) {
              Log.w(
                  LOG_TAG,
                  "Attempting to insert "
                      + value.getAsString(FavoriteMoviesContract.FavoriteMovieEntry.COLUMN_TITLE)
                      + " but value is already in database.");
            }
            if (_id != -1) {
              numInserted++;
            }
          }
          if (numInserted > 0) {
            // If no errors, declare a successful transaction.
            // database will not populate if this is not called
            db.setTransactionSuccessful();
          }
        } finally {
          // all transactions occur at once
          db.endTransaction();
        }
        if (numInserted > 0) {
          // if there was successful insertion, notify the content resolver that there
          // was a change
          getContext().getContentResolver().notifyChange(uri, null);
        }
        return numInserted;
      default:
        return super.bulkInsert(uri, values);
    }
  }
Exemplo n.º 30
0
  private int addTran(Transaction trans) {
    db.beginTransaction();
    int tran_id;
    try {
      ContentValues newValue = tranValues(trans);
      tran_id = (int) db.insertOrThrow("trans", "acct_id", newValue);
      trans.ID = tran_id;

      db.setTransactionSuccessful();
    } finally {
      db.endTransaction();
    }
    return tran_id;
  }