List of usage examples for android.database.sqlite SQLiteDatabase delete
public int delete(String table, String whereClause, String[] whereArgs)
From source file:com.jefftharris.passwdsafe.NotificationMgr.java
/** * Clear all notifications after being confirmed *//*from w w w .j a v a2s . co m*/ public void handleClearAllConfirmed() { try { SQLiteDatabase db = itsDbHelper.getWritableDatabase(); try { db.beginTransaction(); db.delete(DB_TABLE_EXPIRYS, null, null); db.delete(DB_TABLE_URIS, null, null); loadEntries(db); db.setTransactionSuccessful(); } finally { db.endTransaction(); } } catch (SQLException e) { Log.e(TAG, "Database error", e); } }
From source file:com.wheelermarine.android.publicAccesses.Updater.java
@Override protected Integer doInBackground(URL... urls) { try {//ww w .j a v a2s . com final DatabaseHelper db = new DatabaseHelper(context); SQLiteDatabase database = db.getWritableDatabase(); if (database == null) throw new IllegalStateException("Unable to open database!"); database.beginTransaction(); try { // Clear out the old data. database.delete(DatabaseHelper.PublicAccessEntry.TABLE_NAME, null, null); // Connect to the web server and locate the FTP download link. Log.v(TAG, "Finding update: " + urls[0]); activity.runOnUiThread(new Runnable() { @Override public void run() { progress.setMessage("Locating update..."); progress.setIndeterminate(true); } }); Document doc = Jsoup.connect(urls[0].toString()).timeout(timeout * 1000).userAgent(userAgent).get(); URL dataURL = null; for (Element element : doc.select("a")) { if (element.hasAttr("href") && element.attr("href").startsWith("ftp://ftp.dnr.state.mn.us")) { dataURL = new URL(element.attr("href")); } } // Make sure the download URL was fund. if (dataURL == null) throw new FileNotFoundException("Unable to locate data URL."); // Connect to the FTP server and download the update. Log.v(TAG, "Downloading update: " + dataURL); activity.runOnUiThread(new Runnable() { @Override public void run() { progress.setMessage("Downloading update..."); progress.setIndeterminate(true); } }); FTPClient ftp = new FTPClient(); try { ftp.setConnectTimeout(timeout * 1000); ftp.setDefaultTimeout(timeout * 1000); ftp.connect(dataURL.getHost()); ftp.enterLocalPassiveMode(); // After connection attempt, you should check the reply code // to verify success. if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { ftp.disconnect(); throw new IOException("FTP server refused connection: " + ftp.getReplyString()); } // Login using the standard anonymous credentials. if (!ftp.login("anonymous", "anonymous")) { ftp.disconnect(); throw new IOException("FTP Error: " + ftp.getReplyString()); } Map<Integer, Location> locations = null; // Download the ZIP archive. Log.v(TAG, "Downloading: " + dataURL.getFile()); ftp.setFileType(FTP.BINARY_FILE_TYPE); InputStream in = ftp.retrieveFileStream(dataURL.getFile()); if (in == null) throw new FileNotFoundException(dataURL.getFile() + " was not found!"); try { ZipInputStream zin = new ZipInputStream(in); try { // Locate the .dbf entry in the ZIP archive. ZipEntry entry; while ((entry = zin.getNextEntry()) != null) { if (entry.getName().endsWith(entryName)) { readDBaseFile(zin, database); } else if (entry.getName().endsWith(shapeEntryName)) { locations = readShapeFile(zin); } } } finally { try { zin.close(); } catch (Exception e) { // Ignore this error. } } } finally { in.close(); } if (locations != null) { final int recordCount = locations.size(); activity.runOnUiThread(new Runnable() { @Override public void run() { progress.setIndeterminate(false); progress.setMessage("Updating locations..."); progress.setMax(recordCount); } }); int progress = 0; for (int recordNumber : locations.keySet()) { PublicAccess access = db.getPublicAccessByRecordNumber(recordNumber); Location loc = locations.get(recordNumber); access.setLatitude(loc.getLatitude()); access.setLongitude(loc.getLongitude()); db.updatePublicAccess(access); publishProgress(++progress); } } } finally { if (ftp.isConnected()) ftp.disconnect(); } database.setTransactionSuccessful(); return db.getPublicAccessesCount(); } finally { database.endTransaction(); } } catch (Exception e) { error = e; Log.e(TAG, "Error loading data: " + e.getLocalizedMessage(), e); return -1; } }
From source file:net.olejon.mdapp.DiseasesAndTreatmentsSearchActivity.java
private void search(final String language, final String string, final boolean cache) { mFirstPubMedPosition = 0;//from w w w .j ava 2 s .c o m mFirstWebOfSciencePosition = 0; mFirstMedlinePlusPosition = 0; mFirstWikipediaPosition = 0; mFirstUpToDatePosition = 0; mFirstBmjPosition = 0; mFirstNhiPosition = 0; mFirstSmlPosition = 0; mFirstForskningPosition = 0; mFirstHelsebiblioteketPosition = 0; mFirstTidsskriftetPosition = 0; mFirstOncolexPosition = 0; mFirstBrukerhandbokenPosition = 0; mFirstHelsenorgePosition = 0; try { RequestQueue requestQueue = Volley.newRequestQueue(mContext); String apiUri = getString(R.string.project_website_uri) + "api/1/diseases-and-treatments/" + language + "/?search=" + URLEncoder.encode(string, "utf-8"); if (!cache) requestQueue.getCache().remove(apiUri); JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(apiUri, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { for (int i = 0; i < response.length(); i++) { try { JSONObject jsonObject = response.getJSONObject(i); String type = jsonObject.getString("type"); if (mFirstPubMedPosition == 0 && type.equals("pubmed")) mFirstPubMedPosition = i; if (mFirstWebOfSciencePosition == 0 && type.equals("webofscience")) mFirstWebOfSciencePosition = i; if (mFirstMedlinePlusPosition == 0 && type.equals("medlineplus")) mFirstMedlinePlusPosition = i; if (mFirstWikipediaPosition == 0 && type.equals("wikipedia")) mFirstWikipediaPosition = i; if (mFirstUpToDatePosition == 0 && type.equals("uptodate")) mFirstUpToDatePosition = i; if (mFirstBmjPosition == 0 && type.equals("bmj")) mFirstBmjPosition = i; if (mFirstNhiPosition == 0 && type.equals("nhi")) mFirstNhiPosition = i; if (mFirstSmlPosition == 0 && type.equals("sml")) mFirstSmlPosition = i; if (mFirstForskningPosition == 0 && type.equals("forskning")) mFirstForskningPosition = i; if (mFirstHelsebiblioteketPosition == 0 && type.equals("helsebiblioteket")) mFirstHelsebiblioteketPosition = i; if (mFirstTidsskriftetPosition == 0 && type.equals("tidsskriftet")) mFirstTidsskriftetPosition = i; if (mFirstOncolexPosition == 0 && type.equals("oncolex")) mFirstOncolexPosition = i; if (mFirstBrukerhandbokenPosition == 0 && type.equals("brukerhandboken")) mFirstBrukerhandbokenPosition = i; if (mFirstHelsenorgePosition == 0 && type.equals("helsenorge")) mFirstHelsenorgePosition = i; } catch (Exception e) { Log.e("DiseasesAndTreatments", Log.getStackTraceString(e)); } } mProgressBar.setVisibility(View.GONE); mSwipeRefreshLayout.setRefreshing(false); if (mTools.isTablet()) mRecyclerView.setLayoutManager( new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)); mRecyclerView.setAdapter(new DiseasesAndTreatmentsSearchAdapter(mContext, response, string)); ContentValues contentValues = new ContentValues(); contentValues.put(DiseasesAndTreatmentsSQLiteHelper.COLUMN_STRING, string); SQLiteDatabase sqLiteDatabase = new DiseasesAndTreatmentsSQLiteHelper(mContext) .getWritableDatabase(); sqLiteDatabase.delete(DiseasesAndTreatmentsSQLiteHelper.TABLE, DiseasesAndTreatmentsSQLiteHelper.COLUMN_STRING + " = " + mTools.sqe(string) + " COLLATE NOCASE", null); sqLiteDatabase.insert(DiseasesAndTreatmentsSQLiteHelper.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.diseases_and_treatments_search_could_not_search), 1); Log.e("DiseasesAndTreatments", error.toString()); finish(); } }); jsonArrayRequest.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); requestQueue.add(jsonArrayRequest); } catch (Exception e) { Log.e("DiseasesAndTreatments", Log.getStackTraceString(e)); } }
From source file:cn.edu.wyu.documentviewer.RecentsProvider.java
@Override public Uri insert(Uri uri, ContentValues values) { final SQLiteDatabase db = mHelper.getWritableDatabase(); final ContentValues key = new ContentValues(); switch (sMatcher.match(uri)) { case URI_RECENT: values.put(RecentColumns.TIMESTAMP, System.currentTimeMillis()); db.insert(TABLE_RECENT, null, values); final long cutoff = System.currentTimeMillis() - MAX_HISTORY_IN_MILLIS; db.delete(TABLE_RECENT, RecentColumns.TIMESTAMP + "<" + cutoff, null); return uri; case URI_STATE: final String authority = uri.getPathSegments().get(1); final String rootId = uri.getPathSegments().get(2); final String documentId = uri.getPathSegments().get(3); key.put(StateColumns.AUTHORITY, authority); key.put(StateColumns.ROOT_ID, rootId); key.put(StateColumns.DOCUMENT_ID, documentId); // Ensure that row exists, then update with changed values db.insertWithOnConflict(TABLE_STATE, null, key, SQLiteDatabase.CONFLICT_IGNORE); db.update(TABLE_STATE, values, StateColumns.AUTHORITY + "=? AND " + StateColumns.ROOT_ID + "=? AND " + StateColumns.DOCUMENT_ID + "=?", new String[] { authority, rootId, documentId }); return uri; case URI_RESUME: values.put(ResumeColumns.TIMESTAMP, System.currentTimeMillis()); final String packageName = uri.getPathSegments().get(1); key.put(ResumeColumns.PACKAGE_NAME, packageName); // Ensure that row exists, then update with changed values db.insertWithOnConflict(TABLE_RESUME, null, key, SQLiteDatabase.CONFLICT_IGNORE); db.update(TABLE_RESUME, values, ResumeColumns.PACKAGE_NAME + "=?", new String[] { packageName }); return uri; default:/* www. j a va 2 s .co m*/ throw new UnsupportedOperationException("Unsupported Uri " + uri); } }
From source file:com.maxwen.wallpaper.board.databases.Database.java
public void deleteCategories(@NonNull List<Category> categories) { SQLiteDatabase db = this.getWritableDatabase(); for (int i = 0; i < categories.size(); i++) { db.delete(TABLE_CATEGORIES, KEY_NAME + " = ?", new String[] { categories.get(i).getName() }); }//from ww w . j a va 2s. c o m db.close(); }
From source file:com.triarc.sync.SyncAdapter.java
private void deleteRow(SQLiteDatabase db, String id, SyncType type) throws IOException { db.delete(type.getName(), "_id=" + id, null); }
From source file:ru.orangesoftware.financisto2.db.MyEntityManager.java
public void deleteAttribute(long id) { SQLiteDatabase db = db(); db.beginTransaction();//from w w w .jav a2 s .com try { Attribute attr = get(Attribute.class, id); String key = attr.remoteKey; String[] p = new String[] { String.valueOf(id) }; db.delete(ATTRIBUTES_TABLE, DatabaseHelper.AttributeColumns.ID + "=?", p); db.delete(CATEGORY_ATTRIBUTE_TABLE, DatabaseHelper.CategoryAttributeColumns.ATTRIBUTE_ID + "=?", p); db.delete(TRANSACTION_ATTRIBUTE_TABLE, DatabaseHelper.TransactionAttributeColumns.ATTRIBUTE_ID + "=?", p); db.setTransactionSuccessful(); writeDeleteLog(ATTRIBUTES_TABLE, key); } finally { db.endTransaction(); } }
From source file:net.olejon.mdapp.DiseasesAndTreatmentsSearchActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Connected? if (!mTools.isDeviceConnected()) { mTools.showToast(getString(R.string.device_not_connected), 1); finish();// w w w .jav a2 s. co m return; } // Intent final Intent intent = getIntent(); mSearchLanguage = intent.getStringExtra("language"); final String searchString = intent.getStringExtra("string"); // Layout setContentView(R.layout.activity_diseases_and_treatments_search); // Toolbar mToolbar = (Toolbar) findViewById(R.id.diseases_and_treatments_search_toolbar); mToolbar.setTitle(getString(R.string.diseases_and_treatments_search_search) + ": \"" + searchString + "\""); setSupportActionBar(mToolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); // Progress bar mProgressBar = (ProgressBar) findViewById(R.id.diseases_and_treatments_search_toolbar_progressbar); mProgressBar.setVisibility(View.VISIBLE); // Spinner mSpinner = (Spinner) findViewById(R.id.diseases_and_treatments_search_spinner); ArrayAdapter<CharSequence> arrayAdapter; if (mSearchLanguage.equals("")) { arrayAdapter = ArrayAdapter.createFromResource(mContext, R.array.diseases_and_treatments_search_spinner_items_english, R.layout.activity_diseases_and_treatments_search_spinner_header); } else { arrayAdapter = ArrayAdapter.createFromResource(mContext, R.array.diseases_and_treatments_search_spinner_items_norwegian, R.layout.activity_diseases_and_treatments_search_spinner_header); } arrayAdapter.setDropDownViewResource(R.layout.activity_diseases_and_treatments_search_spinner_item); mSpinner.setAdapter(arrayAdapter); mSpinner.setOnItemSelectedListener(this); // Refresh mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById( R.id.diseases_and_treatments_search_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(mSearchLanguage, searchString, false); } }); // Recycler view mRecyclerView = (RecyclerView) findViewById(R.id.diseases_and_treatments_search_cards); mRecyclerView.setHasFixedSize(true); mRecyclerView.setAdapter(new DiseasesAndTreatmentsSearchAdapter(mContext, new JSONArray(), "")); mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext)); // Search search(mSearchLanguage, 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( DiseasesAndTreatmentsSQLiteHelper.COLUMN_STRING, correctSearchString); SQLiteDatabase sqLiteDatabase = new DiseasesAndTreatmentsSQLiteHelper( mContext).getWritableDatabase(); sqLiteDatabase.delete(DiseasesAndTreatmentsSQLiteHelper.TABLE, DiseasesAndTreatmentsSQLiteHelper.COLUMN_STRING + " = " + mTools.sqe(searchString) + " COLLATE NOCASE", null); sqLiteDatabase.insert(DiseasesAndTreatmentsSQLiteHelper.TABLE, null, contentValues); sqLiteDatabase.close(); mToolbar.setTitle(getString( R.string.diseases_and_treatments_search_search) + ": \"" + correctSearchString + "\""); mProgressBar.setVisibility(View.VISIBLE); search(mSearchLanguage, correctSearchString, true); } }).contentColorRes(R.color.black).positiveColorRes(R.color.dark_blue) .negativeColorRes(R.color.black).show(); } } catch (Exception e) { Log.e("DiseasesAndTreatments", Log.getStackTraceString(e)); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e("DiseasesAndTreatments", error.toString()); } }); jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); requestQueue.add(jsonObjectRequest); } catch (Exception e) { Log.e("DiseasesAndTreatments", Log.getStackTraceString(e)); } }
From source file:com.snt.bt.recon.database.DBHandler.java
public <T> void updateSyncStatus(Class<T> cl, JSONObject obj) throws InstantiationException, IllegalAccessException, JSONException { T inst = cl.newInstance();// w w w . ja v a2 s . co m SQLiteDatabase database = this.getWritableDatabase(); String updateQuery = ""; if (inst instanceof Trip) { if (obj.get("status").toString().equals("yes")) database.delete(TABLE_TRIPS, KEY_SESSION_ID + "=" + "'" + UUID.fromString(obj.get("session_id").toString()) + "'", null); else { updateQuery = "UPDATE " + TABLE_TRIPS + " set " + KEY_UPLOAD_STATUS + " = '" + obj.get("status").toString() + "' where " + KEY_SESSION_ID + "=" + "'" + UUID.fromString(obj.get("session_id").toString()) + "'"; database.execSQL(updateQuery); } } else if (inst instanceof GPSLocation) if (obj.get("status").toString().equals("yes")) database.delete(TABLE_LOCATIONS, KEY_LOCATION_ID + "=" + "'" + UUID.fromString(obj.get("location_id").toString()) + "'", null); else { updateQuery = "UPDATE " + TABLE_LOCATIONS + " set " + KEY_UPLOAD_STATUS + " = '" + obj.get("status").toString() + "' where " + KEY_LOCATION_ID + "=" + "'" + UUID.fromString(obj.get("location_id").toString()) + "'"; database.execSQL(updateQuery); } else if (inst instanceof BluetoothClassicEntry) if (obj.get("status").toString().equals("yes")) database.delete(TABLE_BC, "id=" + obj.getInt("id") + "", null); else { updateQuery = "UPDATE " + TABLE_BC + " set " + KEY_UPLOAD_STATUS + " = '" + obj.get("status").toString() + "' where id=" + obj.getInt("id") + ""; database.execSQL(updateQuery); } else if (inst instanceof BluetoothLowEnergyEntry) if (obj.get("status").toString().equals("yes")) database.delete(TABLE_BLE, "id=" + obj.getInt("id") + "", null); else { updateQuery = "UPDATE " + TABLE_BLE + " set " + KEY_UPLOAD_STATUS + " = '" + obj.get("status").toString() + "' where id=" + obj.getInt("id") + ""; database.execSQL(updateQuery); } //Log.d("DatabaseTest", updateQuery); database.close(); }
From source file:at.bitfire.davdroid.DavService.java
@SuppressLint("MissingPermission") void cleanupAccounts() { App.log.info("Cleaning up orphaned accounts"); final OpenHelper dbHelper = new OpenHelper(this); try {//www . j a v a 2 s . c o m SQLiteDatabase db = dbHelper.getWritableDatabase(); List<String> sqlAccountNames = new LinkedList<>(); AccountManager am = AccountManager.get(this); for (Account account : am.getAccountsByType(Constants.ACCOUNT_TYPE)) sqlAccountNames.add(DatabaseUtils.sqlEscapeString(account.name)); if (sqlAccountNames.isEmpty()) db.delete(Services._TABLE, null, null); else db.delete(Services._TABLE, Services.ACCOUNT_NAME + " NOT IN (" + TextUtils.join(",", sqlAccountNames) + ")", null); } finally { dbHelper.close(); } }