Example usage for android.content ContentResolver delete

List of usage examples for android.content ContentResolver delete

Introduction

In this page you can find the example usage for android.content ContentResolver delete.

Prototype

public final int delete(@RequiresPermission.Write @NonNull Uri url, @Nullable String where,
        @Nullable String[] selectionArgs) 

Source Link

Document

Deletes row(s) specified by a content URI.

Usage

From source file:org.odk.collect.android.utilities.MediaUtils.java

public static final int deleteImagesInFolderFromMediaProvider(File folder) {
    ContentResolver cr = Collect.getInstance().getContentResolver();
    // images/*from   www . j a v a  2s  .  c  o  m*/
    int count = 0;
    Cursor imageCursor = null;
    try {
        String select = Images.Media.DATA + " like ? escape '!'";
        String[] selectArgs = { escapePath(folder.getAbsolutePath()) };

        String[] projection = { Images.ImageColumns._ID };
        imageCursor = cr.query(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection,
                select, selectArgs, null);
        if (imageCursor.getCount() > 0) {
            imageCursor.moveToFirst();
            List<Uri> imagesToDelete = new ArrayList<Uri>();
            do {
                String id = imageCursor.getString(imageCursor.getColumnIndex(Images.ImageColumns._ID));

                imagesToDelete.add(Uri
                        .withAppendedPath(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id));
            } while (imageCursor.moveToNext());

            for (Uri uri : imagesToDelete) {
                Log.i(t, "attempting to delete: " + uri);
                count += cr.delete(uri, null, null);
            }
        }
    } catch (Exception e) {
        Log.e(t, e.toString());
    } finally {
        if (imageCursor != null) {
            imageCursor.close();
        }
    }
    return count;
}

From source file:com.amrutpatil.makeanote.NotesActivity.java

private void delete(View view, int position) {
    ContentResolver cr = this.getContentResolver();
    //Get the ID of the note that is to be deleted
    String _ID = ((TextView) view.findViewById(R.id.id_note_custom_home)).getText().toString();
    Uri uri = NotesContract.Notes.buildNoteUri(_ID);
    cr.delete(uri, null, null);
    mNotesAdapter.delete(position);/*from   ww w .j  a  v  a 2  s. c om*/
    changeNoItemTag();

}

From source file:com.jefftharris.passwdsafe.file.PasswdFileUri.java

/** Delete a file */
public void delete(Context context) throws IOException {
    switch (itsType) {
    case FILE: {//from   w w  w .  j a v  a 2  s  .  com
        if (!itsFile.delete()) {
            throw new IOException("Could not delete file: " + toString());
        }
        break;
    }
    case SYNC_PROVIDER: {
        ContentResolver cr = context.getContentResolver();
        int rc = cr.delete(itsUri, null, null);
        if (rc != 1) {
            throw new IOException("Could not delete file: " + toString());
        }
        break;
    }
    case GENERIC_PROVIDER: {
        ContentResolver cr = context.getContentResolver();
        if (!ApiCompat.documentsContractDeleteDocument(cr, itsUri)) {
            throw new IOException("Could not delete file: " + toString());
        }
        break;
    }
    case EMAIL: {
        throw new IOException("Delete not supported for " + toString());
    }
    }
}

From source file:org.flerda.android.honeypad.NoteListFragment.java

@Override
public void onClick(View v) {
    switch (v.getId()) {
    case R.id.checkbox:
        Integer position = (Integer) v.getTag(R.id.list);
        if (null != position) {
            ListView lv = getListView();
            int pos = position;
            boolean isChecked = !lv.isItemChecked(pos);
            lv.setItemChecked(pos, isChecked);
            if (!mIsV11) {
                showMultiPanel();/*from w w w .j ava 2s  .  co  m*/
            }
        }
        break;
    case R.id.btn_multi_delete: {
        Activity a = getActivity();
        ContentResolver cr = a.getContentResolver();
        ListView lv = mLV;
        int deletedCount = 0;
        /** Badness. Don't loop a delete operation on the UI thread **/
        /** We also assume that the ID's and positions are constant **/
        for (long id : lv.getCheckItemIds()) {
            deletedCount += cr.delete(ContentUris.withAppendedId(NotesProvider.CONTENT_URI, id), null, null);
        }
        // clear any selections
        lv.clearChoices();

        // update container
        mContainerCallback.onNoteDeleted();

        // show a toast to confirm delete
        Toast.makeText(a,
                String.format(getString(R.string.num_deleted), deletedCount, (deletedCount == 1 ? "" : "s")),
                Toast.LENGTH_SHORT).show();
        showMultiPanel();
        break;
    }
    }
}

From source file:th.in.ffc.person.visit.VisitDiagActivity.java

public void doSave() {

    boolean finishable = true;

    for (String code : getDeleteList()) {
        Uri uri = VisitDiag.getContentUriId(Long.parseLong(getVisitNo()), code);
        ContentResolver cr = getContentResolver();
        int count = cr.delete(uri, null, null);
        Log.d(TAG, "deleted diag count=" + count + " uri=" + uri.toString());
    }//  w  ww.ja  v  a2  s.  c  o m

    ArrayList<String> codeList = new ArrayList<String>();
    boolean check = mCheck.isChecked();
    for (String tag : getEditList()) {
        Log.d(TAG, "tag=" + tag);
        DiagFragment f = (DiagFragment) getSupportFragmentManager().findFragmentByTag(tag);
        if (f != null) {
            EditTransaction et = beginTransaction();
            f.onSave(et);

            if (!et.canCommit()) {
                finishable = false;
                break;
            }
            System.out.println("do add code");
            String code = et.getContentValues().getAsString(VisitDiag.CODE);
            if (isAddedCode(codeList, code)) {
                finishable = false;
                Toast.makeText(this, R.string.duplicate_drug, Toast.LENGTH_SHORT).show();
                break;
            } else
                codeList.add(code);

            ContentValues cv = et.getContentValues();
            cv.put(VisitDiag.NO, getVisitNo());
            cv.put(VisitDiag.CLINIC, mClinic.getSelectId());
            cv.put(VisitDiag.PCUCODE, getPcuCode());
            cv.put(VisitDiag.DATEUPDATE, DateTime.getCurrentDateTime());
            cv.put(VisitDiag.DOCTOR, getUser());
            if (check) {
                cv.put(VisitDiag.APPOINT_DATE, mAppoint.getDate().toString());
                cv.put(VisitDiag.APPOINT_TYPE, mAppointType.getSelectedItemPosition());
                check = false;
            }

            String action = f.action;
            if (action.equals(Action.INSERT)) {
                Uri insert = et.commit(VisitDiag.CONTENT_URI);
                f.action = Action.EDIT;
                f.key = code;
                Log.d(TAG, "insert diag=" + insert.toString());

                Answers.getInstance()
                        .logCustom(new CustomEvent("Diagnosis").putCustomAttribute("code", code)
                                .putCustomAttribute("type", cv.getAsString(VisitDiag.TYPE))
                                .putCustomAttribute("continue", f.conti ? "yes" : "no")
                                .putCustomAttribute("pcu", getPcuCode()).putCustomAttribute("user", getUser()));
            } else if (action.equals(Action.EDIT)) {
                Uri updateUri = VisitDiag.getContentUriId(Long.parseLong(getVisitNo()), f.key);
                int update = et.commit(updateUri, null, null);
                Log.d(TAG, "update drug=" + update + " uri=" + updateUri.toString());
            }
        }
    }
    if (finishable) {
        checkVisit506();
    }
}

From source file:org.jsharkey.sky.webservice.WebserviceHelper.java

/**
 * Perform a webservice query to retrieve and store the forecast for the
 * given widget. This call blocks until request is finished and
 * {@link Forecasts#CONTENT_URI} has been updated.
 *//* w ww .j  av a 2  s. co m*/
public static void updateForecasts(Context context, Uri appWidgetUri, int days) throws ParseException {

    if (sUserAgent == null) {
        prepareUserAgent(context);
    }

    Uri appWidgetForecasts = Uri.withAppendedPath(appWidgetUri, AppWidgets.TWIG_FORECASTS);

    ContentResolver resolver = context.getContentResolver();

    Cursor cursor = null;
    double lat = Double.NaN;
    double lon = Double.NaN;
    String countryCode = null;

    // Pull exact forecast location from database
    try {
        cursor = resolver.query(appWidgetUri, PROJECTION_APPWIDGET, null, null, null);
        if (cursor != null && cursor.moveToFirst()) {
            lat = cursor.getDouble(COL_LAT);
            lon = cursor.getDouble(COL_LON);
            countryCode = cursor.getString(COL_COUNTRY_CODE);
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }

    Log.d(TAG, "using country code=" + countryCode);

    // Query webservice for this location
    List<Forecast> forecasts = null;
    if (COUNTRY_US.equals(countryCode)) {
        forecasts = new NoaaSource().getForecasts(lat, lon, days);
    } else {
        forecasts = new MetarSource().getForecasts(lat, lon, days);
    }

    if (forecasts == null || forecasts.size() == 0) {
        throw new ParseException("No forecasts found from webservice query");
    }

    // Purge existing forecasts covered by incoming data, and anything
    // before today
    long lastMidnight = ForecastUtils.getLastMidnight();
    long earliest = Long.MAX_VALUE;
    for (Forecast forecast : forecasts) {
        earliest = Math.min(earliest, forecast.validStart);
    }

    resolver.delete(appWidgetForecasts, ForecastsColumns.VALID_START + " >= " + earliest + " OR "
            + ForecastsColumns.VALID_START + " <= " + lastMidnight, null);

    // Insert any new forecasts found
    ContentValues values = new ContentValues();
    for (Forecast forecast : forecasts) {
        Log.d(TAG, "inserting forecast with validStart=" + forecast.validStart);
        values.clear();
        values.put(ForecastsColumns.VALID_START, forecast.validStart);
        values.put(ForecastsColumns.TEMP_HIGH, forecast.tempHigh);
        values.put(ForecastsColumns.TEMP_LOW, forecast.tempLow);
        values.put(ForecastsColumns.CONDITIONS, forecast.conditions);
        values.put(ForecastsColumns.URL, forecast.url);
        if (forecast.alert) {
            values.put(ForecastsColumns.ALERT, ForecastsColumns.ALERT_TRUE);
        }
        resolver.insert(appWidgetForecasts, values);
    }

    // Mark widget cache as being updated
    values.clear();
    values.put(AppWidgetsColumns.LAST_UPDATED, System.currentTimeMillis());
    resolver.update(appWidgetUri, values, null, null);
}

From source file:com.jackie.sunshine.app.sync.SunshineSyncAdapter.java

/**
 * Take the String representing the complete forecast in JSON Format and
 * pull out the data we need to construct the Strings needed for the wireframes.
 * <p>// w w w.j a v  a  2s.c o  m
 * Fortunately parsing is easy:  constructor takes the JSON string and converts it
 * into an Object hierarchy for us.
 */
private void getWeatherDataFromJson(String forecastJsonStr, String locationSetting) throws JSONException {

    // Now we have a String representing the complete forecast in JSON Format.
    // Fortunately parsing is easy:  constructor takes the JSON string and converts it
    // into an Object hierarchy for us.

    // These are the names of the JSON objects that need to be extracted.

    // Location information
    final String OWM_CITY = "city";
    final String OWM_CITY_NAME = "name";
    final String OWM_COORD = "coord";

    // Location coordinate
    final String OWM_LATITUDE = "lat";
    final String OWM_LONGITUDE = "lon";

    // Weather information.  Each day's forecast info is an element of the "list" array.
    final String OWM_LIST = "list";

    final String OWM_PRESSURE = "pressure";
    final String OWM_HUMIDITY = "humidity";
    final String OWM_WINDSPEED = "speed";
    final String OWM_WIND_DIRECTION = "deg";

    // All temperatures are children of the "temp" object.
    final String OWM_TEMPERATURE = "temp";
    final String OWM_MAX = "max";
    final String OWM_MIN = "min";

    final String OWM_WEATHER = "weather";
    final String OWM_DESCRIPTION = "main";
    final String OWM_WEATHER_ID = "id";

    try {
        JSONObject forecastJson = new JSONObject(forecastJsonStr);
        JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);

        JSONObject cityJson = forecastJson.getJSONObject(OWM_CITY);
        String cityName = cityJson.getString(OWM_CITY_NAME);

        JSONObject cityCoord = cityJson.getJSONObject(OWM_COORD);
        double cityLatitude = cityCoord.getDouble(OWM_LATITUDE);
        double cityLongitude = cityCoord.getDouble(OWM_LONGITUDE);

        long locationId = addLocation(locationSetting, cityName, cityLatitude, cityLongitude);

        // Insert the new weather information into the database
        Vector<ContentValues> cVVector = new Vector<>(weatherArray.length());

        // OWM returns daily forecasts based upon the local time of the city that is being
        // asked for, which means that we need to know the GMT offset to translate this data
        // properly.

        // Since this data is also sent in-order and the first day is always the
        // current day, we're going to take advantage of that to get a nice
        // normalized UTC date for all of our weather.

        GregorianCalendar calendar = new GregorianCalendar();
        Time dayTime = new Time();
        dayTime.setToNow();

        // we start at the day returned by local time. Otherwise this is a mess.
        int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff);

        // now we work exclusively in UTC
        dayTime = new Time();

        for (int i = 0; i < weatherArray.length(); i++) {
            // These are the values that will be collected.
            long dateTime;
            double pressure;
            int humidity;
            double windSpeed;
            double windDirection;

            double high;
            double low;

            String description;
            int weatherId;

            // Get the JSON object representing the day
            JSONObject dayForecast = weatherArray.getJSONObject(i);

            // Cheating to convert this to UTC time, which is what we want anyhow
            dateTime = dayTime.setJulianDay(julianStartDay + i);

            pressure = dayForecast.getDouble(OWM_PRESSURE);
            humidity = dayForecast.getInt(OWM_HUMIDITY);
            windSpeed = dayForecast.getDouble(OWM_WINDSPEED);
            windDirection = dayForecast.getDouble(OWM_WIND_DIRECTION);

            // Description is in a child array called "weather", which is 1 element long.
            // That element also contains a weather code.
            JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
            description = weatherObject.getString(OWM_DESCRIPTION);
            weatherId = weatherObject.getInt(OWM_WEATHER_ID);

            // Temperatures are in a child object called "temp".  Try not to name variables
            // "temp" when working with temperature.  It confuses everybody.
            JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
            high = temperatureObject.getDouble(OWM_MAX);
            low = temperatureObject.getDouble(OWM_MIN);

            ContentValues weatherValues = new ContentValues();

            weatherValues.put(WeatherEntry.COLUMN_LOC_KEY, locationId);
            weatherValues.put(WeatherEntry.COLUMN_DATE, dateTime);
            weatherValues.put(WeatherEntry.COLUMN_HUMIDITY, humidity);
            weatherValues.put(WeatherEntry.COLUMN_PRESSURE, pressure);
            weatherValues.put(WeatherEntry.COLUMN_WIND_SPEED, windSpeed);
            weatherValues.put(WeatherEntry.COLUMN_DEGREES, windDirection);
            weatherValues.put(WeatherEntry.COLUMN_MAX_TEMP, high);
            weatherValues.put(WeatherEntry.COLUMN_MIN_TEMP, low);
            weatherValues.put(WeatherEntry.COLUMN_SHORT_DESC, description);
            weatherValues.put(WeatherEntry.COLUMN_WEATHER_ID, weatherId);

            cVVector.add(weatherValues);
        }

        int inserted = 0;
        // add to database
        if (cVVector.size() > 0) {
            // Student: call bulkInsert to add the weatherEntries to the database here
            ContentValues[] cvArray = new ContentValues[cVVector.size()];
            cVVector.toArray(cvArray);

            ContentResolver contentResolver = getContext().getContentResolver();
            inserted = contentResolver.bulkInsert(WeatherEntry.CONTENT_URI, cvArray);
            contentResolver.delete(WeatherEntry.CONTENT_URI, WeatherEntry.COLUMN_DATE + "<= " + "?",
                    new String[] { Long.toString(dayTime.setJulianDay(julianStartDay - 1)) });

            notifyWeather();
        }
        Log.d(TAG, "getWeatherDataFromJson: " + inserted + " inserted");
    } catch (JSONException e) {
        Log.e(TAG, e.getMessage(), e);
        e.printStackTrace();
    }
}

From source file:th.in.ffc.person.visit.VisitMainActivity.java

public void doDiscardVisit() {
    if (!TextUtils.isEmpty(mVisitNo)) {
        String where = "visitno=? and pcucode=?";
        String[] selectionArgs = new String[] { mVisitNo, getPcuCode() };
        ContentResolver cr = getContentResolver();

        String wheres = "visitno=?";
        String[] selectionArgss = new String[] { mVisitNo };
        // remove ffcmap506radius
        cr.delete(FFC506RADIUS.CONTENT_URI, wheres, selectionArgss);

        // remove default visit
        cr.delete(Visit.CONTENT_URI, where, selectionArgs);
        // remove visit Diagnosis
        cr.delete(VisitDiag.CONTENT_URI, where, selectionArgs);
        // remove visit Drug
        cr.delete(VisitDrug.CONTENT_URI, where, selectionArgs);
        // remove Visit Anc
        cr.delete(VisitAnc.CONTENT_URI, where, selectionArgs);
        // remove Visit Epi
        cr.delete(VisitEpi.CONTENT_URI, where, selectionArgs);
        // remove Visit Individual
        cr.delete(VisitIndividual.CONTENT_URI, where, selectionArgs);
        // remove Visit FP
        cr.delete(VisitFamilyplan.CONTENT_URI, where, selectionArgs);
        // remove Visit Labcancer
        cr.delete(VisitLabcancer.CONTENT_URI, where, selectionArgs);
        // remove Visit Babycare
        cr.delete(VisitBabycare.CONTENT_URI, where, selectionArgs);
        // remove Visit Diag506
        cr.delete(VisitDiag506address.CONTENT_URI, where, selectionArgs);
        // //remove Visit Specialpeson
        // cr.delete(VisitSpecialperson.CONTENT_URI,
        // "pid = ? AND pcucode =?", new String[]{mPid,mPcuCodePerson});
        // //remove Visit Persongrow
        // cr.delete(VisitPersongrow.CONTENT_URI,
        // "pid =? AND pcucodeperson=?", new String[]{mPid,mPcuCodePerson});
        // remove Visit Screenspecialdisease
        cr.delete(VisitScreenspecialdisease.CONTENT_URI, where, selectionArgs);
        // remove Visit AncDeliver
        cr.delete(VisitAncDeliver.CONTENT_URI, where, selectionArgs);
        // remove Visit AncMothercare
        cr.delete(VisitAncMotherCare.CONTENT_URI, where, selectionArgs);
        // remove Visit Oldter
        cr.delete(VisitOldter.CONTENT_URI, where, selectionArgs);
        // remove Visit Nutrition
        cr.delete(VisitNutrition.CONTENT_URI, where, selectionArgs);
        // remove Visit DiagAppoint
        cr.delete(VisitDiagAppoint.CONTENT_URI, where, selectionArgs);
        // remove Visit DentalCheck
        cr.delete(VisitDentalCheck.CONTENT_URI, where, selectionArgs);
        // remove Visit Drugdental
        cr.delete(VisitDrugDental.CONTENT_URI, where, selectionArgs);
        cr.delete(VisitDrugDentalDiag.CONTENT_URI, where, selectionArgs);
    }//  www.  j  a v  a2 s .c o m
}

From source file:org.ohmage.db.DbHelper.java

public boolean removeCampaign(String urn) {
    ContentResolver cr = mContext.getContentResolver();
    return cr.delete(Campaigns.CONTENT_URI, Campaigns.CAMPAIGN_URN + "='" + urn + "'", null) > 0;
}

From source file:org.ohmage.db.DbHelper.java

/**
 * Removes survey responses (and their associated prompts) for the given
 * campaign.//from   ww w.jav a2s .c o  m
 * 
 * @param campaignUrn
 *            the campaign URN for which to remove the survey responses
 * @return
 */
public boolean removeResponseRows(String campaignUrn) {
    ContentResolver cr = mContext.getContentResolver();
    return cr.delete(Responses.CONTENT_URI, Responses.CAMPAIGN_URN + "='" + campaignUrn + "'", null) > 0;
}