Example usage for android.database.sqlite SQLiteDatabase update

List of usage examples for android.database.sqlite SQLiteDatabase update

Introduction

In this page you can find the example usage for android.database.sqlite SQLiteDatabase update.

Prototype

public int update(String table, ContentValues values, String whereClause, String[] whereArgs) 

Source Link

Document

Convenience method for updating rows in the database.

Usage

From source file:com.armtimes.activities.SingleArticlePreviewActivity.java

@Override
public void onSingleArticleDownloadCompleted(final ArticleInfo articleInfo) {

    if (progressDialog != null) {
        progressDialog.dismissAllowingStateLoss();
        progressDialog = null;/*from   w w  w  . ja  v  a2  s  .c o  m*/
    }

    // Finish current activity if Description or Title
    // are missing, missing of image is not a case to
    // finish activity.
    if (articleInfo == null) {
        Toast.makeText(getApplicationContext(), R.string.cant_show_news_data_missing, Toast.LENGTH_LONG).show();
        setResult(Activity.RESULT_CANCELED);
        finish();
        return;
    }

    // Title comes from the Database and it should be there
    // as it is downloaded at first phase from RSS.
    String title = getIntent().getStringExtra(EXTRA_TITLE);
    if (title == null || title.isEmpty()) {
        Toast.makeText(getApplicationContext(), R.string.cant_show_news_data_missing, Toast.LENGTH_LONG).show();
        setResult(Activity.RESULT_CANCELED);
        finish();
        return;
    }

    String description = articleInfo.getDescription();
    if (description == null || description.isEmpty()) {
        Toast.makeText(getApplicationContext(), R.string.cant_show_news_data_missing, Toast.LENGTH_LONG).show();
        setResult(Activity.RESULT_CANCELED);
        finish();
        return;
    }

    // If news article information was successfully downloaded,
    // and shown to the user - update database by setting given
    // news item read state to TRUE.
    try {
        // Get current table name, in which information for given
        // article must be updated.
        final String table = getIntent().getStringExtra(EXTRA_CATEGORY).toUpperCase();
        // Create Database helper object.
        NewsDatabaseHelper helper = new NewsDatabaseHelper(getApplicationContext());
        SQLiteDatabase database = helper.getWritableDatabase();
        // Create data which must be updated.
        ContentValues cv = new ContentValues();
        cv.put(NewsContract.COL_NAME_NEWS_IS_READ, 1);
        // Update appropriate field in database.
        database.update(table, cv, String.format("%s=\"%s\"", NewsContract.COL_NAME_NEWS_URL, articleInfo.url),
                null);
        // Close database
        database.close();
        helper.close();
    } catch (Exception ex) {
        Logger.e(TAG, "Exception occurs while trying to Update database!");
    }

    // Set layout Visible.
    layoutMain.setVisibility(View.VISIBLE);

    textTitle.setText(title.trim());
    textDescription.setText(Html.fromHtml(articleInfo.getDescription()));

    // Try to set image if it exists.
    InputStream is = null;
    try {
        is = new FileInputStream(new File(articleInfo.getMainImagePath()));
        imageBanner.setImageBitmap(BitmapFactory.decodeStream(is));
        imageBanner.setScaleType(ImageView.ScaleType.CENTER_CROP);
    } catch (IOException ex) {
        imageBanner.setScaleType(ImageView.ScaleType.CENTER);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException ex) {
                Logger.e(TAG, "Error occurs while trying to close Banner Image Stream.");
            }
        }
    }

    setResult(Activity.RESULT_OK);
}

From source file:github.popeen.dsub.util.SongDBHandler.java

public synchronized void setSongPlayed(DownloadFile downloadFile, boolean submission) {
    // TODO: In case of offline want to update all matches
    Pair<Integer, String> pair = getOnlineSongId(downloadFile);
    if (pair == null) {
        return;/*from w w  w.  j a v  a  2  s  .co  m*/
    }
    int serverKey = pair.getFirst();
    String id = pair.getSecond();

    // Open and make sure song is in db
    SQLiteDatabase db = this.getWritableDatabase();
    addSongImpl(db, serverKey, id, downloadFile.getSaveFile().getAbsolutePath());

    // Update song's last played
    ContentValues values = new ContentValues();
    values.put(submission ? SONGS_LAST_COMPLETED : SONGS_LAST_PLAYED, System.currentTimeMillis());
    db.update(TABLE_SONGS, values, SONGS_SERVER_KEY + " = ? AND " + SONGS_SERVER_ID + " = ?",
            new String[] { Integer.toString(serverKey), id });
    db.close();
}

From source file:com.matthewmitchell.wakeifyplus.database.AlarmCursorAdapter.java

@Override
public void bindView(View v, Context context, Cursor c) {

    final String name = c.getString(c.getColumnIndex("name"));
    final long time = c.getLong(c.getColumnIndex("time"));

    TextView time_text = (TextView) v.findViewById(R.id.time);
    if (time_text != null) {
        time_text.setText(date_format.format(new Date(time)));
    }/*from  w  w w. j  a  va 2  s.c  o m*/

    TextView name_text = (TextView) v.findViewById(R.id.name);
    if (name_text != null) {
        name_text.setText(name);
    }

    // Do on/off button alarm code

    CompoundButton onOff = (CompoundButton) v.findViewById(R.id.alarm_switch);
    // Make sure the change listener is not set for setting value from database.
    onOff.setOnCheckedChangeListener(null);
    onOff.setChecked(c.getInt(c.getColumnIndex("onOff")) == 1);
    final Context contextl = context;
    final long id = c.getInt(c.getColumnIndex("_id"));
    onOff.setOnCheckedChangeListener(new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            AlarmDatabase database = new AlarmDatabase(contextl);
            SQLiteDatabase write = database.getWritableDatabase();
            ContentValues values = new ContentValues(1);
            if (isChecked) {
                // Alarm has been turned on
                values.put("onOff", 1);
                // Add system alarm
                AlarmReceiver.scheduleAlarm(contextl, id, false);
            } else {
                // Alarm has been switched off
                values.put("onOff", 0);
                AlarmReceiver.removeAlarm(contextl, id);
            }
            write.update(AlarmDatabase.ALARMS_TABLE, values, "_id = " + id, null);
            write.close();
            database.close();
            // Reload cursor
            main.getSupportLoaderManager().restartLoader(0, null, main);
        }

    });
}

From source file:org.akop.crosswords.Storage.java

public boolean moveTo(long folderId, long... puzzleIds) {
    if (puzzleIds.length < 1) {
        return false;
    }/*from ww  w . java 2s. c  o m*/

    StringBuilder whereBuilder = new StringBuilder();
    whereBuilder.append(Puzzle._ID);
    whereBuilder.append(" IN (");
    for (int i = 0, n = puzzleIds.length - 1; i <= n; i++) {
        whereBuilder.append(puzzleIds[i]);
        if (i < n) {
            whereBuilder.append(",");
        }
    }
    whereBuilder.append(")");

    StorageHelper helper = getHelper();
    SQLiteDatabase db = helper.getWritableDatabase();
    int rowsUpdated = 0;

    ContentValues cv = new ContentValues();
    cv.put(Puzzle.FOLDER_ID, folderId);

    try {
        rowsUpdated += db.update(Puzzle.TABLE, cv, whereBuilder.toString(), null);
    } finally {
        db.close();
    }

    if (rowsUpdated > 0) {
        Intent outgoing = new Intent(ACTION_PUZZLE_CHANGE);
        sendLocalBroadcast(outgoing);
    }

    Crosswords.logv("Moved %d puzzles to folder id %d", rowsUpdated, folderId);

    return rowsUpdated > 0;
}

From source file:net.olejon.mdapp.NotesEditActivity.java

private void saveNote() {
    String title = mTitleEditText.getText().toString().trim();
    String text = mTextEditText.getText().toString().trim();
    String patientId = mPatientIdEditText.getText().toString().trim();
    String patientName = mPatientNameEditText.getText().toString().trim();
    String patientDoctor = mPatientDoctorEditText.getText().toString().trim();
    String patientDepartment = mPatientDepartmentEditText.getText().toString().trim();
    String patientRoom = mPatientRoomEditText.getText().toString().trim();

    if (title.equals("") || text.equals("")) {
        mTools.showToast(getString(R.string.notes_edit_invalid_values), 1);
    } else {//from   w  w w. ja v  a 2 s .  co  m
        ContentValues contentValues = new ContentValues();

        contentValues.put(NotesSQLiteHelper.COLUMN_TITLE, title);
        contentValues.put(NotesSQLiteHelper.COLUMN_TEXT, text);
        contentValues.put(NotesSQLiteHelper.COLUMN_DATA, "");
        contentValues.put(NotesSQLiteHelper.COLUMN_PATIENT_ID, patientId);
        contentValues.put(NotesSQLiteHelper.COLUMN_PATIENT_NAME, patientName);
        contentValues.put(NotesSQLiteHelper.COLUMN_PATIENT_DOCTOR, patientDoctor);
        contentValues.put(NotesSQLiteHelper.COLUMN_PATIENT_DEPARTMENT, patientDepartment);
        contentValues.put(NotesSQLiteHelper.COLUMN_PATIENT_ROOM, patientRoom);

        if (mPatientMedicationsJsonArray.length() == 0) {
            contentValues.put(NotesSQLiteHelper.COLUMN_PATIENT_MEDICATIONS, "");
        } else {
            contentValues.put(NotesSQLiteHelper.COLUMN_PATIENT_MEDICATIONS,
                    mPatientMedicationsJsonArray.toString());
        }

        SQLiteDatabase sqLiteDatabase = new NotesSQLiteHelper(mContext).getWritableDatabase();

        if (noteId == 0) {
            sqLiteDatabase.insert(NotesSQLiteHelper.TABLE, null, contentValues);
        } else {
            sqLiteDatabase.update(NotesSQLiteHelper.TABLE, contentValues,
                    NotesSQLiteHelper.COLUMN_ID + " = " + noteId, null);
        }

        sqLiteDatabase.close();

        mTools.showToast(getString(R.string.notes_edit_saved), 1);

        finish();
    }
}

From source file:net.survivalpad.android.entity.Article.java

@Override
public long update(SQLiteDatabase db) {
    ContentValues values = new ContentValues();
    write(values);/*from  w  w  w.  j a v a 2 s  .  c  om*/

    db.update(getTableName(), values, "_id = ?", new String[] { String.valueOf(id) });

    new Column().deleteByArticleId(id, db);
    for (Column column : columns) {
        column.setArticleId(id);
        column.insert(db);
    }

    new ArticleDisasterType().deleteByArticleId(id, db);
    for (DisasterType disasterType : disasterTypes) {
        ArticleDisasterType obj = new ArticleDisasterType();
        obj.setArticleId(id);
        obj.setDisastertypeId(disasterType.getId());
        obj.insert(db);
    }

    return id;
}

From source file:heartware.com.heartware_master.DBAdapter.java

public int updateProfile(HashMap<String, String> queryValues) {
    SQLiteDatabase database = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(USERNAME, queryValues.get(USERNAME));
    values.put(PASSWORD, queryValues.get(PROFILE_ID));
    values.put(DIFFICULTY, queryValues.get(DIFFICULTY));
    values.put(DISABILITY, queryValues.get(DISABILITY));
    // update(TableName, ContentValueForTable, WhereClause, ArgumentForWhereClause)
    return database.update(PROFILES_TABLE, values, PROFILE_ID + " = ?",
            new String[] { queryValues.get(PROFILE_ID) });
}

From source file:org.emergent.android.weave.syncadapter.SyncCache.java

public boolean updateLastSync(URI uri, String engineName, Date lastSyncDate) {
    Log.d(TAG, "SyncCache.updateLastSync()");
    if (lastSyncDate == null) {
        Log.w(TAG, "lastSyncDate was null");
        return false;
    }/*from   ww  w . ja  v  a  2  s.c o  m*/

    long lastSync = lastSyncDate.getTime();
    SQLiteDatabase db = null;
    try {
        String uriStr = uri.toASCIIString();
        db = m_helper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(MgColumns.LAST_MODIFIED, lastSync);
        long updateCount = db.update(META_GLOBAL_TABLE_NAME, values,
                MgColumns.NODE_URI + " = ? AND " + MgColumns.ENGINE_NAME + " = ?",
                new String[] { uriStr, engineName });
        assert updateCount < 2 : "Should not be able to update more than one row by constraints!";
        return updateCount > 0;
    } finally {
        if (db != null)
            try {
                db.close();
            } catch (Exception ignored) {
            }
    }
}

From source file:com.example.easyvoice.MessageDetail.java

public void onUpdate(View view) {
    Log.i(getClass().getSimpleName(), "onUpdate");

    SQLiteDatabase db = null;
    try {/* w  w  w.  ja v a  2s .co  m*/
        db = this.openOrCreateDatabase(DB_NAME, MODE_PRIVATE, null);

        ContentValues values = new ContentValues();

        values.put("disp_name", displayEdit.getText().toString());
        values.put("content", contentEdit.getText().toString());

        String whereClause = "msg_id = ?";
        String[] whereArgs = new String[] { Integer.toString(msgId) };

        int count = db.update(TABLE_NAME, values, whereClause, whereArgs);
        if (count != 1)
            Log.w("expect 1, got ", "onUpdate");
        // go back
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);

    } catch (SQLiteException se) {
        Log.e(getClass().getSimpleName(), "Could not create or Open the database");
    }

}

From source file:com.example.shutapp.DatabaseHandler.java

/**
 * @param chatroom/*  w w  w .  j ava  2 s.  c o m*/
 * @return 
 */
public int updateChatrooms(Chatroom chatroom) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_NAME, chatroom.getName()); // Chatroom Name
    values.put(KEY_LATITUDE, chatroom.getLatitude()); // Chatroom Latitude
    values.put(KEY_LONGITUDE, chatroom.getLongitude()); // Chatroom Longitude
    values.put(KEY_RADIUS, chatroom.getRadius()); // Chatroom Radius

    // updating row
    return db.update(TABLE_CHATROOMS, values, KEY_NAME + " = ?", new String[] { chatroom.getName() });
}