Example usage for android.database.sqlite SQLiteDatabase delete

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

Introduction

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

Prototype

public int delete(String table, String whereClause, String[] whereArgs) 

Source Link

Document

Convenience method for deleting rows in the database.

Usage

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

private void getNotes() {
    if (mIsAuthenticated) {
        GetNotesTask getNotesTask = new GetNotesTask();
        getNotesTask.execute();/*from  w w  w  . j  ava 2  s .  c  om*/
    } else {
        new MaterialDialog.Builder(mContext).title(getString(R.string.notes_dialog_verify_pin_code_title))
                .customView(R.layout.activity_notes_dialog_verify_pin_code, true)
                .positiveText(getString(R.string.notes_dialog_verify_pin_code_positive_button))
                .negativeText(getString(R.string.notes_dialog_verify_pin_code_negative_button))
                .neutralText(getString(R.string.notes_dialog_verify_pin_code_neutral_button))
                .callback(new MaterialDialog.ButtonCallback() {
                    @Override
                    public void onPositive(MaterialDialog dialog) {
                        EditText pinCodeEditText = (EditText) dialog
                                .findViewById(R.id.notes_dialog_verify_pin_code);

                        String pinCode = pinCodeEditText.getText().toString();

                        if (pinCode.equals(mTools.getSharedPreferencesString("NOTES_PIN_CODE"))) {
                            GetNotesTask getNotesTask = new GetNotesTask();
                            getNotesTask.execute();

                            dialog.dismiss();
                        } else {
                            mTools.showToast(getString(R.string.notes_dialog_verify_pin_code_wrong), 1);
                        }
                    }

                    @Override
                    public void onNegative(MaterialDialog dialog) {
                        dialog.dismiss();

                        finish();
                    }

                    @Override
                    public void onNeutral(MaterialDialog dialog) {
                        dialog.dismiss();

                        new MaterialDialog.Builder(mContext)
                                .title(getString(R.string.notes_dialog_reset_pin_code_title))
                                .content(getString(R.string.notes_dialog_reset_pin_code_message))
                                .positiveText(getString(R.string.notes_dialog_reset_pin_code_positive_button))
                                .neutralText(getString(R.string.notes_dialog_reset_pin_code_neutral_button))
                                .callback(new MaterialDialog.ButtonCallback() {
                                    @Override
                                    public void onPositive(MaterialDialog dialog) {
                                        mTools.setSharedPreferencesString("NOTES_PIN_CODE", "");

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

                                        sqLiteDatabase.delete(NotesSQLiteHelper.TABLE, null, null);

                                        sqLiteDatabase.close();

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

                                        finish();
                                    }

                                    @Override
                                    public void onNeutral(MaterialDialog dialog) {
                                        finish();
                                    }
                                }).cancelListener(new DialogInterface.OnCancelListener() {
                                    @Override
                                    public void onCancel(DialogInterface dialogInterface) {
                                        finish();
                                    }
                                }).contentColorRes(R.color.black).positiveColorRes(R.color.red)
                                .neutralColorRes(R.color.dark_blue).show();
                    }
                }).showListener(new DialogInterface.OnShowListener() {
                    @Override
                    public void onShow(DialogInterface dialogInterface) {
                        mInputMethodManager.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
                    }
                }).cancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialogInterface) {
                        dialogInterface.dismiss();

                        finish();
                    }
                }).contentColorRes(R.color.black).positiveColorRes(R.color.dark_blue)
                .negativeColorRes(R.color.black).neutralColorRes(R.color.dark_blue).autoDismiss(false).show();
    }
}

From source file:uk.org.rivernile.edinburghbustracker.android.SettingsDatabase.java

/**
 * Clean up alerts. This removes any alerts which are older than 1 hour.
 * /*from w ww  .  j  a va 2s.c om*/
 * @param db The SQLiteDatabase on which we are operating.
 */
public void cleanupAlerts(final SQLiteDatabase db) {
    if (!db.isReadOnly()) {
        db.delete(ALERTS_TABLE, ALERTS_TIME_ADDED + " < ?",
                new String[] { String.valueOf(System.currentTimeMillis() - 3600000) });
    }
}

From source file:uk.org.rivernile.edinburghbustracker.android.SettingsDatabase.java

/**
 * Delete an alert of a particular type. This can be either
 * {@link SettingsDatabase#ALERTS_TYPE_PROXIMITY} or
 * {@link SettingsDatabase#ALERTS_TYPE_TIME}.
 * //from w w w .  j  a v  a2 s  .co  m
 * @param type The type of alert to delete.
 * @see SettingsDatabase#ALERTS_TYPE_PROXIMITY
 * @see SettingsDatabase#ALERTS_TYPE_TIME
 */
public void deleteAllAlertsOfType(final byte type) {
    final SQLiteDatabase db = getWritableDatabase();
    cleanupAlerts(db);
    db.delete(ALERTS_TABLE, ALERTS_TYPE + " = ?", new String[] { String.valueOf(type) });
}

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

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Connected?
    if (!mTools.isDeviceConnected()) {
        mTools.showToast(getString(R.string.device_not_connected), 1);

        finish();//from w ww  . ja  v a2  s  .  c  o  m

        return;
    }

    // Intent
    final Intent intent = getIntent();

    searchString = intent.getStringExtra("search");

    // Layout
    setContentView(R.layout.activity_interactions_cards);

    // Toolbar
    mToolbar = (Toolbar) findViewById(R.id.interactions_cards_toolbar);
    mToolbar.setTitle(getString(R.string.interactions_cards_search) + ": \"" + searchString + "\"");

    setSupportActionBar(mToolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    // Progress bar
    mProgressBar = (ProgressBar) findViewById(R.id.interactions_cards_toolbar_progressbar);
    mProgressBar.setVisibility(View.VISIBLE);

    // Refresh
    mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.interactions_cards_swipe_refresh_layout);
    mSwipeRefreshLayout.setColorSchemeResources(R.color.accent_blue, R.color.accent_green,
            R.color.accent_purple, R.color.accent_orange);

    mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            search(searchString, false);
        }
    });

    // Recycler view
    mRecyclerView = (RecyclerView) findViewById(R.id.interactions_cards_cards);

    mRecyclerView.setHasFixedSize(true);
    mRecyclerView.setAdapter(new InteractionsCardsAdapter(mContext, mProgressBar, new JSONArray()));
    mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));

    // No interactions
    mNoInteractionsLayout = (LinearLayout) findViewById(R.id.interactions_cards_no_interactions);

    Button noInteractionsButton = (Button) findViewById(R.id.interactions_cards_no_interactions_button);

    noInteractionsButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            try {
                Intent intent = new Intent(mContext, MainWebViewActivity.class);
                intent.putExtra("title",
                        getString(R.string.interactions_cards_search) + ": \"" + searchString + "\"");
                intent.putExtra("uri", "http://interaksjoner.no/analyser.asp?PreparatNavn="
                        + URLEncoder.encode(searchString.toLowerCase(), "utf-8") + "&submit1=Sjekk");
                mContext.startActivity(intent);
            } catch (Exception e) {
                Log.e("InteractionsCards", Log.getStackTraceString(e));
            }
        }
    });

    // Search
    search(searchString, true);

    // Correct
    RequestQueue requestQueue = Volley.newRequestQueue(mContext);

    try {
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
                getString(R.string.project_website_uri) + "api/1/correct/?search="
                        + URLEncoder.encode(searchString, "utf-8"),
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            final String correctSearchString = response.getString("correct");

                            if (!correctSearchString.equals("")) {
                                new MaterialDialog.Builder(mContext)
                                        .title(getString(R.string.correct_dialog_title))
                                        .content(Html.fromHtml(getString(R.string.correct_dialog_message)
                                                + ":<br><br><b>" + correctSearchString + "</b>"))
                                        .positiveText(getString(R.string.correct_dialog_positive_button))
                                        .negativeText(getString(R.string.correct_dialog_negative_button))
                                        .callback(new MaterialDialog.ButtonCallback() {
                                            @Override
                                            public void onPositive(MaterialDialog dialog) {
                                                ContentValues contentValues = new ContentValues();
                                                contentValues.put(InteractionsSQLiteHelper.COLUMN_STRING,
                                                        correctSearchString);

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

                                                sqLiteDatabase.delete(InteractionsSQLiteHelper.TABLE,
                                                        InteractionsSQLiteHelper.COLUMN_STRING + " = "
                                                                + mTools.sqe(searchString) + " COLLATE NOCASE",
                                                        null);
                                                sqLiteDatabase.insert(InteractionsSQLiteHelper.TABLE, null,
                                                        contentValues);

                                                sqLiteDatabase.close();

                                                mToolbar.setTitle(getString(R.string.interactions_cards_search)
                                                        + ": \"" + correctSearchString + "\"");

                                                mProgressBar.setVisibility(View.VISIBLE);

                                                mNoInteractionsLayout.setVisibility(View.GONE);
                                                mSwipeRefreshLayout.setVisibility(View.VISIBLE);

                                                search(correctSearchString, true);
                                            }
                                        }).contentColorRes(R.color.black).positiveColorRes(R.color.dark_blue)
                                        .negativeColorRes(R.color.black).show();
                            }
                        } catch (Exception e) {
                            Log.e("InteractionsCards", Log.getStackTraceString(e));
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e("InteractionsCards", error.toString());
                    }
                });

        jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        requestQueue.add(jsonObjectRequest);
    } catch (Exception e) {
        Log.e("InteractionsCards", Log.getStackTraceString(e));
    }
}

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

public void write(long puzzleId, Crossword.State state) {
    long started = SystemClock.uptimeMillis();

    ContentValues cv = new ContentValues();

    cv.put(PuzzleState.PUZZLE_ID, puzzleId);
    cv.put(PuzzleState.CLASS, state.getClass().getName());
    cv.put(PuzzleState.OBJECT, mGson.toJson(state));
    cv.put(PuzzleState.OBJECT_VERSION, 1);
    cv.put(PuzzleState.PERCENT_SOLVED, state.getPercentSolved());
    cv.put(PuzzleState.PERCENT_CHEATED, state.getPercentCheated());
    cv.put(PuzzleState.PERCENT_WRONG, state.getPercentWrong());
    cv.put(PuzzleState.PLAY_TIME_MILLIS, state.getPlayTimeMillis());

    long lastPlayed = 0;
    if (state.getLastPlayed() != null) {
        lastPlayed = state.getLastPlayed().getMillis();
    }/* w  ww . j a va  2s .c  o  m*/
    cv.put(PuzzleState.LAST_PLAYED, lastPlayed);

    cv.put(PuzzleState.LAST_UPDATED, System.currentTimeMillis());

    StorageHelper helper = getHelper();
    SQLiteDatabase db = helper.getWritableDatabase();

    try {
        // Delete any existing rows
        db.delete(PuzzleState.TABLE, PuzzleState.PUZZLE_ID + "=" + puzzleId, null);
        // Insert the new one
        db.insert(PuzzleState.TABLE, null, cv);
    } finally {
        db.close();
    }

    Crosswords.logv("Wrote state for %d (%dms)", puzzleId, SystemClock.uptimeMillis() - started);

    // Add a copy to the cache
    mStateCache.put((int) puzzleId, new Crossword.State(state));

    // Broadcast the change
    Intent intent = new Intent(ACTION_PUZZLE_STATE_CHANGE);
    intent.putExtra(INTENT_PUZZLE_ID, puzzleId);

    Context context = Crosswords.getInstance();
    LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}

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

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Connected?
    if (!mTools.isDeviceConnected()) {
        mTools.showToast(getString(R.string.device_not_connected), 1);

        finish();/*from  w ww.  j  ava2  s.co m*/

        return;
    }

    // Intent
    final Intent intent = getIntent();

    searchString = intent.getStringExtra("search");

    // Layout
    setContentView(R.layout.activity_clinicaltrials_cards);

    // Toolbar
    mToolbar = (Toolbar) findViewById(R.id.clinicaltrials_cards_toolbar);
    mToolbar.setTitle(getString(R.string.clinicaltrials_cards_search) + ": \"" + searchString + "\"");

    setSupportActionBar(mToolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    // Progress bar
    mProgressBar = (ProgressBar) findViewById(R.id.clinicaltrials_cards_toolbar_progressbar);
    mProgressBar.setVisibility(View.VISIBLE);

    // Refresh
    mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.clinicaltrials_cards_swipe_refresh_layout);
    mSwipeRefreshLayout.setColorSchemeResources(R.color.accent_blue, R.color.accent_green,
            R.color.accent_purple, R.color.accent_orange);

    mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            search(searchString, false);
        }
    });

    // Recycler view
    mRecyclerView = (RecyclerView) findViewById(R.id.clinicaltrials_cards_cards);

    mRecyclerView.setHasFixedSize(true);
    mRecyclerView.setAdapter(new ClinicalTrialsCardsAdapter(mContext, new JSONArray()));
    mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));

    // No clinical trials
    mNoClinicalTrialsLayout = (LinearLayout) findViewById(R.id.clinicaltrials_cards_no_clinicaltrials);

    Button noClinicalTrialsButton = (Button) findViewById(R.id.clinicaltrials_cards_no_results_button);

    noClinicalTrialsButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            try {
                Intent intent = new Intent(mContext, MainWebViewActivity.class);
                intent.putExtra("title",
                        getString(R.string.clinicaltrials_cards_search) + ": \"" + searchString + "\"");
                intent.putExtra("uri", "https://clinicaltrials.gov/ct2/results?term="
                        + URLEncoder.encode(searchString.toLowerCase(), "utf-8") + "&no_unk=Y");
                mContext.startActivity(intent);
            } catch (Exception e) {
                Log.e("ClinicalTrialsCards", Log.getStackTraceString(e));
            }
        }
    });

    // Search
    search(searchString, true);

    // Correct
    RequestQueue requestQueue = Volley.newRequestQueue(mContext);

    try {
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
                getString(R.string.project_website_uri) + "api/1/correct/?search="
                        + URLEncoder.encode(searchString, "utf-8"),
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            final String correctSearchString = response.getString("correct");

                            if (!correctSearchString.equals("")) {
                                new MaterialDialog.Builder(mContext)
                                        .title(getString(R.string.correct_dialog_title))
                                        .content(Html.fromHtml(getString(R.string.correct_dialog_message)
                                                + ":<br><br><b>" + correctSearchString + "</b>"))
                                        .positiveText(getString(R.string.correct_dialog_positive_button))
                                        .negativeText(getString(R.string.correct_dialog_negative_button))
                                        .callback(new MaterialDialog.ButtonCallback() {
                                            @Override
                                            public void onPositive(MaterialDialog dialog) {
                                                ContentValues contentValues = new ContentValues();
                                                contentValues.put(ClinicalTrialsSQLiteHelper.COLUMN_STRING,
                                                        correctSearchString);

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

                                                sqLiteDatabase.delete(ClinicalTrialsSQLiteHelper.TABLE,
                                                        ClinicalTrialsSQLiteHelper.COLUMN_STRING + " = "
                                                                + mTools.sqe(searchString) + " COLLATE NOCASE",
                                                        null);
                                                sqLiteDatabase.insert(ClinicalTrialsSQLiteHelper.TABLE, null,
                                                        contentValues);

                                                sqLiteDatabase.close();

                                                mToolbar.setTitle(
                                                        getString(R.string.clinicaltrials_cards_search) + ": \""
                                                                + correctSearchString + "\"");

                                                mProgressBar.setVisibility(View.VISIBLE);

                                                mNoClinicalTrialsLayout.setVisibility(View.GONE);
                                                mSwipeRefreshLayout.setVisibility(View.VISIBLE);

                                                search(correctSearchString, true);
                                            }
                                        }).contentColorRes(R.color.black).positiveColorRes(R.color.dark_blue)
                                        .negativeColorRes(R.color.black).show();
                            }
                        } catch (Exception e) {
                            Log.e("ClinicalTrialsCards", Log.getStackTraceString(e));
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e("ClinicalTrialsCards", error.toString());
                    }
                });

        jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        requestQueue.add(jsonObjectRequest);
    } catch (Exception e) {
        Log.e("ClinicalTrialsCards", Log.getStackTraceString(e));
    }
}

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

public boolean emptyFolder(long folderId) {
    StorageHelper helper = getHelper();/* w w w  .j a va  2 s .  c  o m*/
    SQLiteDatabase db = helper.getWritableDatabase();

    int puzzlesDeleted;
    int statesDeleted;

    try {
        statesDeleted = db.delete(PuzzleState.TABLE, PuzzleState.PUZZLE_ID + " IN (" + "SELECT " + Puzzle._ID
                + " " + "FROM " + Puzzle.TABLE + " " + "WHERE " + Puzzle.FOLDER_ID + "=" + folderId + ")",
                null);
        puzzlesDeleted = db.delete(Puzzle.TABLE, Puzzle.FOLDER_ID + "=" + folderId, null);
    } finally {
        db.close();
    }

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

    Crosswords.logv("Deleted %d puzzles and %d states", puzzlesDeleted, statesDeleted);

    return puzzlesDeleted > 0;
}

From source file:de.stadtrallye.rallyesoft.model.Server.java

private void writeGroups() {
    Log.v(THIS, "Saving Groups:" + groups);

    final SQLiteDatabase db = Storage.getDatabaseProvider().getDatabase();
    db.delete(Groups.TABLE, null, null);

    for (Group g : groups) {
        ContentValues insert = new ContentValues();
        insert.put(Groups.KEY_ID, g.groupID);
        insert.put(Groups.KEY_NAME, g.name);
        insert.put(Groups.KEY_DESCRIPTION, g.description);
        db.insert(Groups.TABLE, null, insert);
    }/*from  w  w w  .  j  a v  a 2  s .c o  m*/
}

From source file:redgun.bakingapp.data.RecipesProvider.java

@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 RECIPES:
        rowsDeleted = db.delete(RecipesContract.RecipeEntry.TABLE_NAME, selection, selectionArgs);
        break;//from w w w. j a v a  2  s .com

    default:
        throw new UnsupportedOperationException("Unknown uri: " + uri);
    }
    // Because a null deletes all rows
    if (rowsDeleted != 0) {
        getContext().getContentResolver().notifyChange(uri, null);
    }
    return rowsDeleted;
}

From source file:de.stadtrallye.rallyesoft.model.Server.java

public void writeUsers(List<GroupUser> users) {
    Log.v(THIS, "Saving Users");

    final SQLiteDatabase db = Storage.getDatabaseProvider().getDatabase();

    db.delete(Users.TABLE, null, null);

    for (GroupUser u : users) {
        ContentValues insert = new ContentValues();
        insert.put(Users.KEY_ID, u.userID);
        insert.put(Users.KEY_NAME, u.name);
        insert.put(Users.FOREIGN_GROUP, u.groupID);
        db.insert(Users.TABLE, null, insert);
    }/*  w w  w. java  2  s .  c  o  m*/
}