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:com.renjunzheng.vendingmachine.MyGcmListenerService.java

private void updatePurchaseInfo(String purchaseInfo) {
    try {/*w w w.j a  va2  s .  c  om*/
        DataDbHelper dbHelper = new DataDbHelper(this);
        SQLiteDatabase database = dbHelper.getWritableDatabase();

        database.delete(DataContract.PurchasedEntry.TABLE_NAME, null, null);
        database.execSQL(
                "DELETE FROM SQLITE_SEQUENCE WHERE NAME = '" + DataContract.PurchasedEntry.TABLE_NAME + "'");

        JSONArray valueArray = new JSONArray(purchaseInfo);
        Log.i(TAG, "the valueArray length: " + Integer.toString(valueArray.length()));
        for (int lc = 0; lc < valueArray.length(); ++lc) {
            JSONObject infoJson = valueArray.getJSONObject(lc);
            String item_name = infoJson.getString("item_name");
            database.execSQL("DELETE FROM SQLITE_SEQUENCE WHERE NAME = '"
                    + DataContract.PurchasedEntry.TABLE_NAME + "'");

            //query based on this item_name and get item id
            //currently if queried has no such item in current database then don't insert to purchase table
            //find user id using the stored email
            Cursor itemIDCursor;
            int waitTime = 0;
            boolean breaked = false;
            do {
                String[] itemProj = new String[] { DataContract.ItemEntry._ID };
                String[] itemSelArgs = new String[] { item_name };
                itemIDCursor = database.query(DataContract.ItemEntry.TABLE_NAME, itemProj,
                        DataContract.ItemEntry.COLUMN_ITEM_NAME + " = ?", itemSelArgs, null, null, null);
                if (waitTime != 0) {
                    // if the item is not yet exists in the item table, probably means update purchase get called before update storage. So wait until find
                    SystemClock.sleep(1000);
                    if (++waitTime > 30) {
                        breaked = true;
                        break;
                    }
                } else if (waitTime == 0) {
                    waitTime = 1;
                }
            } while (itemIDCursor == null || itemIDCursor.getCount() == 0);

            if (!breaked) {
                itemIDCursor.moveToNext();
                int itemID = itemIDCursor.getInt(0);
                itemIDCursor.close();

                String[] userProj = new String[] { DataContract.UserEntry._ID };
                String user_email = infoJson.getString("email");
                String[] userSelArgs = new String[] { user_email };
                Cursor userIDCursor = database.query(DataContract.UserEntry.TABLE_NAME, userProj,
                        DataContract.UserEntry.COLUMN_EMAIL + " = ?", userSelArgs, null, null, null);
                userIDCursor.moveToNext();
                Log.i(TAG, "userID: " + user_email);
                int userID = userIDCursor.getInt(0);
                Log.i(TAG, "itemID: " + itemID);
                Log.i(TAG, "userID: " + userID);
                userIDCursor.close();
                ContentValues newValues = new ContentValues();
                newValues.put(DataContract.PurchasedEntry.COLUMN_ITEM_KEY, itemID);
                newValues.put(DataContract.PurchasedEntry.COLUMN_USER_KEY, userID);
                newValues.put(DataContract.PurchasedEntry.COLUMN_ORDER_TIME, infoJson.getString("order_time"));
                newValues.put(DataContract.PurchasedEntry.COLUMN_PICK_UP_TIME,
                        infoJson.getString("pickup_time"));
                newValues.put(DataContract.PurchasedEntry.COLUMN_QUANTITY, infoJson.getString("quantity"));
                newValues.put(DataContract.PurchasedEntry.COLUMN_RECEIPT_NUM, infoJson.getString("receipt"));
                Uri returnedUri = getContentResolver().insert(DataContract.PurchasedEntry.CONTENT_URI,
                        newValues);
                Log.i(TAG, "inserted row num " + ContentUris.parseId(returnedUri));
            }
        }

        database.close();
        dbHelper.close();
    } catch (JSONException e) {
        Log.e(TAG, "error when parsing Json");
    }
}

From source file:org.mozilla.labs.Soup.provider.AppsProvider.java

@Override
public int delete(Uri uri, String where, String[] whereArgs) {
    SQLiteDatabase db = mOpenHelper.getWritableDatabase();
    int count;// w  w  w. j  a  v  a2s .  c om
    switch (sUriMatcher.match(uri)) {
    case APPS:
        count = db.delete(APPS_TABLE_NAME, where, whereArgs);
        break;

    case APP_ID:
        String appId = uri.getPathSegments().get(1);
        count = db.delete(APPS_TABLE_NAME,
                Apps._ID + "=" + appId + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
        break;

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

    getContext().getContentResolver().notifyChange(uri, null);
    return count;
}

From source file:de.stadtrallye.rallyesoft.model.map.MapManager.java

private void updateDatabase(List<Node> nodes, List<Edge> edges) {
    SQLiteDatabase db = getDb();

    db.beginTransaction();//w  w w .j  av a2  s .c  om
    try {
        db.delete(Edges.TABLE, null, null);
        db.delete(Nodes.TABLE, null, null);

        SQLiteStatement nodeIn = db.compileStatement("INSERT INTO " + Nodes.TABLE + " ("
                + DatabaseHelper.strStr(Nodes.COLS) + ") VALUES (?, ?, ?, ?, ?)");

        SQLiteStatement edgeIn = db.compileStatement(
                "INSERT INTO " + Edges.TABLE + " (" + DatabaseHelper.strStr(Edges.COLS) + ") VALUES (?, ?, ?)");

        for (Node n : nodes) {
            nodeIn.bindLong(1, n.nodeID);
            nodeIn.bindString(2, n.name);
            nodeIn.bindDouble(3, n.location.latitude);
            nodeIn.bindDouble(4, n.location.longitude);
            nodeIn.bindString(5, n.description);
            nodeIn.executeInsert();
        }

        for (Edge m : edges) {
            edgeIn.bindLong(1, m.nodeA.nodeID);
            edgeIn.bindLong(2, m.nodeB.nodeID);
            edgeIn.bindString(3, m.type.toString());
            edgeIn.executeInsert();
        }

        db.setTransactionSuccessful();
    } catch (Exception e) {
        Log.e(THIS, "Map Update on Database failed", e);
    } finally {
        db.endTransaction();
    }
}

From source file:com.dm.wallpaper.board.databases.Database.java

public void deleteWallpapers(@NonNull List<Wallpaper> wallpapers) {
    SQLiteDatabase db = this.getWritableDatabase();
    for (int i = 0; i < wallpapers.size(); i++) {
        db.delete(TABLE_WALLPAPERS, KEY_URL + " = ?", new String[] { wallpapers.get(i).getUrl() });
    }//from w w w . j  a v a 2 s . co  m
    db.close();
}

From source file:com.alley.android.ppi.app.DetailFragment.java

private void delete() {
    SQLiteDatabase db = new PropertyDbHelper(getActivity()).getWritableDatabase();
    Log.i(LOG_TAG, "database is open - " + db.isOpen());

    int i = db.delete(PropertyContract.PropertyEntry.TABLE_NAME,
            PropertyContract.PropertyEntry.COLUMN_ADDRESS + " like ?", new String[] { "336%" });
    Log.i(LOG_TAG, "deleted - " + i + " records");
}

From source file:com.gmail.emerssso.srbase.database.SRContentProvider.java

@Override
public int delete(Uri uri, String selection, String[] selArgs) {
    int uriType = sURIMatcher.match(uri);
    int rowsDeleted = 0;
    SQLiteDatabase wDB = database.getWritableDatabase();

    switch (uriType) {
    case SRS:/*  w ww  .ja  v a 2s. c o m*/
        rowsDeleted = wDB.delete(SRTable.TABLE_NAME, selection, selArgs);
        break;
    case SR_ID:
        rowsDeleted = deleteIdTypeUri(uri, selection, selArgs, wDB, SRTable.TABLE_NAME);
        break;
    case DAILIES:
        rowsDeleted = wDB.delete(DailyTable.TABLE_NAME, selection, selArgs);
        break;
    case DAILY_ID:
        rowsDeleted = deleteIdTypeUri(uri, selection, selArgs, wDB, DailyTable.TABLE_NAME);
        break;
    case PARTS:
        rowsDeleted = wDB.delete(PartTable.TABLE_NAME, selection, selArgs);
        break;
    case PART_ID:
        rowsDeleted = deleteIdTypeUri(uri, selection, selArgs, wDB, PartTable.TABLE_NAME);
        break;
    default:
        throw new IllegalArgumentException("Unknown URI: " + uri);
    }
    getContext().getContentResolver().notifyChange(uri, null);
    return rowsDeleted;
}

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

private void search(final String string, boolean cache) {
    try {//from  w ww .j  a  v  a  2s  .  c  om
        RequestQueue requestQueue = Volley.newRequestQueue(mContext);

        String apiUri = getString(R.string.project_website_uri) + "api/1/interactions/?search="
                + URLEncoder.encode(string.toLowerCase(), "utf-8");

        if (!cache)
            requestQueue.getCache().remove(apiUri);

        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(apiUri, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {
                mProgressBar.setVisibility(View.GONE);
                mSwipeRefreshLayout.setRefreshing(false);

                if (response.length() == 0) {
                    mSwipeRefreshLayout.setVisibility(View.GONE);
                    mNoInteractionsLayout.setVisibility(View.VISIBLE);
                } else {
                    if (mTools.isTablet()) {
                        int spanCount = (response.length() == 1) ? 1 : 2;

                        mRecyclerView.setLayoutManager(
                                new StaggeredGridLayoutManager(spanCount, StaggeredGridLayoutManager.VERTICAL));
                    }

                    mRecyclerView.setAdapter(new InteractionsCardsAdapter(mContext, mProgressBar, response));

                    ContentValues contentValues = new ContentValues();
                    contentValues.put(InteractionsSQLiteHelper.COLUMN_STRING, string);

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

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

                    sqLiteDatabase.close();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                mProgressBar.setVisibility(View.GONE);
                mSwipeRefreshLayout.setRefreshing(false);

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

                finish();

                Log.e("InteractionsCards", error.toString());
            }
        });

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

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

private void search(final String string, boolean cache) {
    try {//from  www .  j  a  v a2s  .  c  o m
        RequestQueue requestQueue = Volley.newRequestQueue(mContext);

        String apiUri = getString(R.string.project_website_uri) + "api/1/poisonings/?search="
                + URLEncoder.encode(string.toLowerCase(), "utf-8");

        if (!cache)
            requestQueue.getCache().remove(apiUri);

        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(apiUri, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {
                mProgressBar.setVisibility(View.GONE);
                mSwipeRefreshLayout.setRefreshing(false);

                if (response.length() == 0) {
                    mSwipeRefreshLayout.setVisibility(View.GONE);
                    mNoPoisoningsLayout.setVisibility(View.VISIBLE);
                } else {
                    if (mTools.isTablet()) {
                        int spanCount = (response.length() == 1) ? 1 : 2;

                        mRecyclerView.setLayoutManager(
                                new StaggeredGridLayoutManager(spanCount, StaggeredGridLayoutManager.VERTICAL));
                    }

                    mRecyclerView.setAdapter(new PoisoningsCardsAdapter(mContext, response));

                    ContentValues contentValues = new ContentValues();
                    contentValues.put(PoisoningsSQLiteHelper.COLUMN_STRING, string);

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

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

                    sqLiteDatabase.close();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                mProgressBar.setVisibility(View.GONE);
                mSwipeRefreshLayout.setRefreshing(false);

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

                finish();

                Log.e("PoisoningsCardsActivity", error.toString());
            }
        });

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

        requestQueue.add(jsonArrayRequest);
    } catch (Exception e) {
        Log.e("PoisoningsCardsActivity", Log.getStackTraceString(e));
    }
}

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

private void search(final String string, boolean cache) {
    try {//from w w w.  j a  v  a  2  s .  com
        RequestQueue requestQueue = Volley.newRequestQueue(mContext);

        String apiUri = getString(R.string.project_website_uri) + "api/1/clinicaltrials/?search="
                + URLEncoder.encode(string.toLowerCase(), "utf-8");

        if (!cache)
            requestQueue.getCache().remove(apiUri);

        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(apiUri, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {
                mProgressBar.setVisibility(View.GONE);
                mSwipeRefreshLayout.setRefreshing(false);

                if (response.length() == 0) {
                    mSwipeRefreshLayout.setVisibility(View.GONE);
                    mNoClinicalTrialsLayout.setVisibility(View.VISIBLE);
                } else {
                    if (mTools.isTablet()) {
                        int spanCount = (response.length() == 1) ? 1 : 2;

                        mRecyclerView.setLayoutManager(
                                new StaggeredGridLayoutManager(spanCount, StaggeredGridLayoutManager.VERTICAL));
                    }

                    mRecyclerView.setAdapter(new ClinicalTrialsCardsAdapter(mContext, response));

                    ContentValues contentValues = new ContentValues();
                    contentValues.put(ClinicalTrialsSQLiteHelper.COLUMN_STRING, string);

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

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

                    sqLiteDatabase.close();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                mProgressBar.setVisibility(View.GONE);
                mSwipeRefreshLayout.setRefreshing(false);

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

                finish();

                Log.e("ClinicalTrialsCards", error.toString());
            }
        });

        jsonArrayRequest.setRetryPolicy(new DefaultRetryPolicy(30000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

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

From source file:project.cs.lisa.database.IODatabase.java

/**
 * Deletes the information object corresponding to 
 * the specified hash value from the database.
 * /*from   ww w .jav  a  2  s.  com*/
 * @param hash   The hash value identifying the information object.
 */
public void deleteIO(String hash) {
    Log.d(TAG, "Deleting io corresponding to the following hash: " + hash);
    SQLiteDatabase db = getWritableDatabase();

    db.delete(TABLE_IO, KEY_HASH + " = ?", new String[] { hash });
    db.close();
}