Example usage for android.content ContentResolver insert

List of usage examples for android.content ContentResolver insert

Introduction

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

Prototype

public final @Nullable Uri insert(@RequiresPermission.Write @NonNull Uri url, @Nullable ContentValues values) 

Source Link

Document

Inserts a row into a table at the given URL.

Usage

From source file:com.dwdesign.tweetings.fragment.SearchTweetsFragment.java

@Override
public boolean onOptionsItemSelected(final MenuItem item) {
    switch (item.getItemId()) {
    case MENU_SAVE: {
        final TweetingsApplication application = getApplication();
        application.getServiceInterface().createSavedSearch(mAccountId, mQuery);
        break;//from   ww  w  . j  a  va2  s.  c o  m
    }
    case MENU_DELETE: {
        final TweetingsApplication application = getApplication();
        application.getServiceInterface().destroySavedSearch(mAccountId, mSearchId);
        break;
    }
    case MENU_ADD_TAB: {
        CustomTabsAdapter mAdapter;
        mAdapter = new CustomTabsAdapter(getActivity());
        ContentResolver mResolver;
        mResolver = getContentResolver();
        final String tabName = mQuery;
        final String tabType = AUTHORITY_SEARCH_TWEETS;
        final String tabIcon = "search";
        final long account_id = mAccountId;
        final String tabArguments = "{\"account_id\":" + account_id + ",\"query\":" + JSONObject.quote(mQuery)
                + "}";
        final ContentValues values = new ContentValues();
        values.put(Tabs.ARGUMENTS, tabArguments);
        values.put(Tabs.NAME, tabName);
        values.put(Tabs.POSITION, mAdapter.getCount());
        values.put(Tabs.TYPE, tabType);
        values.put(Tabs.ICON, tabIcon);
        mResolver.insert(Tabs.CONTENT_URI, values);
        Toast.makeText(this.getActivity(), R.string.search_tab_added, Toast.LENGTH_SHORT).show();
        break;
    }
    }
    return super.onOptionsItemSelected(item);
}

From source file:com.jaspersoft.android.jaspermobile.util.ProfileHelper.java

public void seedProfilesIfNeed() {
    ContentResolver contentResolver = context.getContentResolver();
    Cursor cursor = contentResolver.query(JasperMobileDbProvider.SERVER_PROFILES_CONTENT_URI,
            new String[] { ServerProfilesTable._ID }, null, null, null);
    if (cursor != null) {
        try {//from w w w. j a  v a2  s.c o m
            if (cursor.getCount() == 0) {
                ServerProfiles testProfile = new ServerProfiles();

                testProfile.setAlias(DEFAULT_ALIAS);
                testProfile.setServerUrl(DEFAULT_SERVER_URL);
                testProfile.setOrganization(DEFAULT_ORGANIZATION);
                testProfile.setUsername(DEFAULT_USERNAME);
                testProfile.setPassword(DEFAULT_PASS);

                contentResolver.insert(JasperMobileDbProvider.SERVER_PROFILES_CONTENT_URI,
                        testProfile.getContentValues());
                populateTestInstances(contentResolver);
            }
        } finally {
            cursor.close();
        }
    }
}

From source file:com.dwdesign.tweetings.fragment.BaseStatusesListFragment.java

@Override
public boolean onMenuItemClick(final MenuItem item) {
    final ParcelableStatus status = mSelectedStatus;
    if (status == null)
        return false;
    final long account_id = getDefaultAccountId(mApplication);
    switch (item.getItemId()) {
    case MENU_VIEW: {
        openStatus(getActivity(), status);
        break;/*from  w  w w  .jav a  2  s  .c o m*/
    }
    case MENU_SHARE: {
        final Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_TEXT, "@" + status.screen_name + ": " + status.text_plain);
        startActivity(Intent.createChooser(intent, getString(R.string.share)));
        break;
    }
    case MENU_TRANSLATE: {
        translate(status);
        break;
    }
    case MENU_RETWEET: {
        if (isMyRetweet(status)) {
            mService.destroyStatus(status.account_id, status.status_id);
        } else {
            final long id_to_retweet = mSelectedStatus.is_retweet && mSelectedStatus.retweet_id > 0
                    ? mSelectedStatus.retweet_id
                    : mSelectedStatus.status_id;
            mService.retweetStatus(status.account_id, id_to_retweet);
        }
        break;
    }
    case MENU_QUOTE: {
        final Intent intent = new Intent(INTENT_ACTION_COMPOSE);
        final Bundle bundle = new Bundle();
        bundle.putLong(INTENT_KEY_ACCOUNT_ID, status.account_id);
        bundle.putBoolean(INTENT_KEY_IS_QUOTE, true);
        bundle.putString(INTENT_KEY_TEXT, getQuoteStatus(getActivity(), status.screen_name, status.text_plain));
        intent.putExtras(bundle);
        startActivity(intent);
        break;
    }
    case MENU_QUOTE_REPLY: {
        final Intent intent = new Intent(INTENT_ACTION_COMPOSE);
        final Bundle bundle = new Bundle();
        bundle.putLong(INTENT_KEY_ACCOUNT_ID, status.account_id);
        bundle.putLong(INTENT_KEY_IN_REPLY_TO_ID, status.status_id);
        bundle.putString(INTENT_KEY_IN_REPLY_TO_SCREEN_NAME, status.screen_name);
        bundle.putString(INTENT_KEY_IN_REPLY_TO_NAME, status.name);
        bundle.putBoolean(INTENT_KEY_IS_QUOTE, true);
        bundle.putString(INTENT_KEY_TEXT, getQuoteStatus(getActivity(), status.screen_name, status.text_plain));
        intent.putExtras(bundle);
        startActivity(intent);
        break;
    }
    case MENU_ADD_TO_BUFFER: {
        final Intent intent = new Intent(INTENT_ACTION_COMPOSE);
        final Bundle bundle = new Bundle();
        bundle.putLong(INTENT_KEY_ACCOUNT_ID, status.account_id);
        bundle.putBoolean(INTENT_KEY_IS_BUFFER, true);
        bundle.putString(INTENT_KEY_TEXT, getQuoteStatus(getActivity(), status.screen_name, status.text_plain));
        intent.putExtras(bundle);
        startActivity(intent);
        break;
    }
    case MENU_REPLY: {
        final Intent intent = new Intent(INTENT_ACTION_COMPOSE);
        final Bundle bundle = new Bundle();
        final List<String> mentions = new Extractor().extractMentionedScreennames(status.text_plain);
        mentions.remove(status.screen_name);
        mentions.add(0, status.screen_name);
        bundle.putStringArray(INTENT_KEY_MENTIONS, mentions.toArray(new String[mentions.size()]));
        bundle.putLong(INTENT_KEY_ACCOUNT_ID, status.account_id);
        bundle.putLong(INTENT_KEY_IN_REPLY_TO_ID, status.status_id);
        bundle.putString(INTENT_KEY_IN_REPLY_TO_TWEET, status.text_plain);
        bundle.putString(INTENT_KEY_IN_REPLY_TO_SCREEN_NAME, status.screen_name);
        bundle.putString(INTENT_KEY_IN_REPLY_TO_NAME, status.name);
        intent.putExtras(bundle);
        startActivity(intent);
        break;
    }
    case MENU_FAV: {
        if (mSelectedStatus.is_favorite) {
            mService.destroyFavorite(status.account_id, status.status_id);
        } else {
            mService.createFavorite(status.account_id, status.status_id);
        }
        break;
    }
    case MENU_CONVERSATION: {
        openConversation(getActivity(), status.account_id, status.status_id);
        break;
    }
    case MENU_DELETE: {
        mService.destroyStatus(status.account_id, status.status_id);
        break;
    }
    case MENU_EXTENSIONS: {
        final Intent intent = new Intent(INTENT_ACTION_EXTENSION_OPEN_STATUS);
        final Bundle extras = new Bundle();
        extras.putParcelable(INTENT_KEY_STATUS, status);
        intent.putExtras(extras);
        startActivity(Intent.createChooser(intent, getString(R.string.open_with_extensions)));
        break;
    }
    case MENU_MULTI_SELECT: {
        if (!mApplication.isMultiSelectActive()) {
            mApplication.startMultiSelect();
        }
        final NoDuplicatesLinkedList<Object> list = mApplication.getSelectedItems();
        if (!list.contains(status)) {
            list.add(status);
        }
        break;
    }
    case MENU_BLOCK: {
        mService.createBlock(account_id, status.user_id);
        break;
    }
    case MENU_REPORT_SPAM: {
        mService.reportSpam(account_id, status.user_id);
        break;
    }
    case MENU_MUTE_USER: {
        final String screen_name = status.screen_name;
        final Uri uri = Filters.Users.CONTENT_URI;
        final ContentValues values = new ContentValues();
        final SharedPreferences.Editor editor = getSharedPreferences(SHARED_PREFERENCES_NAME,
                Context.MODE_PRIVATE).edit();
        final ContentResolver resolver = getContentResolver();
        values.put(Filters.Users.TEXT, screen_name);
        resolver.delete(uri, Filters.Users.TEXT + " = '" + screen_name + "'", null);
        resolver.insert(uri, values);
        editor.putBoolean(PREFERENCE_KEY_ENABLE_FILTER, true).commit();
        Toast.makeText(getActivity(), R.string.user_muted, Toast.LENGTH_SHORT).show();
        break;
    }
    case MENU_MAKE_GAP: {
        Uri uri = Statuses.CONTENT_URI;
        final Uri query_uri = buildQueryUri(uri, false);
        ContentResolver mResolver = getContentResolver();
        final ContentValues values = new ContentValues();
        values.put(Statuses.IS_GAP, 1);
        final StringBuilder where = new StringBuilder();
        where.append(Statuses.ACCOUNT_ID + "=" + account_id);
        where.append(" AND " + Statuses.STATUS_ID + "=" + status.status_id);
        mResolver.update(query_uri, values, where.toString(), null);
        getActivity().sendBroadcast(new Intent(BROADCAST_FILTERS_UPDATED).putExtra(INTENT_KEY_SUCCEED, true));
        break;
    }
    case MENU_COPY: {
        final CharSequence text = Html.fromHtml(status.text_html);
        if (ClipboardUtils.setText(getActivity(), text)) {
            Toast.makeText(getActivity(), R.string.text_copied, Toast.LENGTH_SHORT).show();
        }
        break;
    }
    }
    return true;
}

From source file:org.androidpn.demoapp.MessageListActivity.java

private void saveData(ArrayList<SingleMessage> list) {
    for (SingleMessage message : list) {
        String Id = message.getId();
        String apiKey = "1234567890";
        String title = message.getTitle();
        String messageBody = message.getMessage();
        String time = message.getTimes();
        String isReply = message.getIsReply();
        String options = message.getOptions();
        // save/*from  www.  j  a  v a  2 s . c  om*/
        ContentResolver contentResolver = getContentResolver();
        ContentValues contentValues = new ContentValues();
        contentValues.put(MESSAGE_SUMMARY_PROJECTION[1], Id);
        contentValues.put(MESSAGE_SUMMARY_PROJECTION[2], apiKey);
        contentValues.put(MESSAGE_SUMMARY_PROJECTION[3], title);
        contentValues.put(MESSAGE_SUMMARY_PROJECTION[4], messageBody);
        contentValues.put(MESSAGE_SUMMARY_PROJECTION[5], isReply);
        contentValues.put(MESSAGE_SUMMARY_PROJECTION[6], 0);
        contentValues.put(MESSAGE_SUMMARY_PROJECTION[7], time);
        contentValues.put(MESSAGE_SUMMARY_PROJECTION[8], options);
        contentResolver.insert(ServerMessage.CONTENT_URI, contentValues);
    }
}

From source file:com.dileepindia.cordova.sms.SMSPlugin.java

private PluginResult restoreSMS(JSONArray array, CallbackContext callbackContext) {
    ContentResolver resolver = this.cordova.getActivity().getContentResolver();
    Uri uri = Uri.parse("content://sms/inbox");

    int n = array.length();
    int m = 0;/* w w w. ja  va  2  s  . c  o  m*/

    for (int i = 0; i < n; i++) {
        JSONObject json = array.optJSONObject(i);
        if (json != null) {
            String str = json.toString();
            Log.d("SMSPlugin", str);

            Uri newuri = resolver.insert(uri, getContentValuesFromJson(json));
            Log.d("SMSPlugin", "inserted: " + newuri.toString());

            m++;
        }
    }

    if (callbackContext != null)
        callbackContext.success(m);
    return null;
}

From source file:com.jaspersoft.android.jaspermobile.util.ProfileHelper.java

/**
 * Remove method when testing needs will be fulfilled
 * @param contentResolver//from   w  ww . j  a va 2  s .  c  o  m
 */
private void populateTestInstances(ContentResolver contentResolver) {
    InputStream is = context.getResources().openRawResource(R.raw.profiles);
    try {
        String json = IOUtils.toString(is);
        Gson gson = new Gson();
        Profiles profiles = gson.fromJson(json, Profiles.class);
        for (ServerProfiles profile : profiles.getData()) {
            // We need populate content values manually ;(
            profile.setAlias(profile.getAlias());
            profile.setServerUrl(profile.getServerUrl());
            profile.setOrganization(profile.getOrganization());
            profile.setUsername(profile.getUsername());
            profile.setPassword(profile.getPassword());

            ContentValues contentValues = profile.getContentValues();
            contentResolver.insert(JasperMobileDbProvider.SERVER_PROFILES_CONTENT_URI, contentValues);
        }
    } catch (IOException e) {
        Log.w(TAG, "Ignoring population of data");
        throw new RuntimeException(e);
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:net.etuldan.sparss.fragment.EditFeedsListFragment.java

@Override
public boolean onOptionsItemSelected(final MenuItem item) {
    switch (item.getItemId()) {
    case R.id.menu_add_feed: {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle(R.string.menu_add_feed).setItems(new CharSequence[] {
                getString(R.string.add_custom_feed), getString(R.string.google_news_title) },
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        if (which == 0) {
                            startActivity(new Intent(Intent.ACTION_INSERT).setData(FeedColumns.CONTENT_URI));
                        } else {
                            startActivity(new Intent(getActivity(), AddGoogleNewsActivity.class));
                        }//from   w  w w.j ava 2  s  . c om
                    }
                });
        builder.show();
        return true;
    }
    case R.id.menu_add_group: {
        final EditText input = new EditText(getActivity());
        input.setSingleLine(true);
        new AlertDialog.Builder(getActivity()) //
                .setTitle(R.string.add_group_title) //
                .setView(input) //
                // .setMessage(R.string.add_group_sentence) //
                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        new Thread() {
                            @Override
                            public void run() {
                                String groupName = input.getText().toString();
                                if (!groupName.isEmpty()) {
                                    ContentResolver cr = getActivity().getContentResolver();
                                    ContentValues values = new ContentValues();
                                    values.put(FeedColumns.IS_GROUP, true);
                                    values.put(FeedColumns.NAME, groupName);
                                    cr.insert(FeedColumns.GROUPS_CONTENT_URI, values);
                                }
                            }
                        }.start();
                    }
                }).setNegativeButton(android.R.string.cancel, null).show();
        return true;
    }
    case R.id.menu_export:
    case R.id.menu_import: {
        if (ContextCompat.checkSelfPermission(getActivity(),
                Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            // Should we explain?
            if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
                    Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(
                        getActivity());
                builder.setMessage(R.string.storage_request_explanation)
                        .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialogInterface, int id) {
                                if (item.getItemId() == R.id.menu_export) {
                                    ActivityCompat.requestPermissions(getActivity(),
                                            new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
                                            PERMISSIONS_REQUEST_EXPORT_TO_OPML);
                                } else if (item.getItemId() == R.id.menu_import) {
                                    ActivityCompat.requestPermissions(getActivity(),
                                            new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
                                            PERMISSIONS_REQUEST_IMPORT_FROM_OPML);
                                }
                            }
                        }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialogInterface, int id) {
                                //Canceled Dialog
                            }
                        });
                builder.show();
            } else {
                if (item.getItemId() == R.id.menu_export) {
                    ActivityCompat.requestPermissions(getActivity(),
                            new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
                            PERMISSIONS_REQUEST_EXPORT_TO_OPML);
                } else if (item.getItemId() == R.id.menu_import) {
                    ActivityCompat.requestPermissions(getActivity(),
                            new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
                            PERMISSIONS_REQUEST_IMPORT_FROM_OPML);
                }
            }
        } else {
            if (item.getItemId() == R.id.menu_export) {
                exportToOpml();
            } else if (item.getItemId() == R.id.menu_import) {
                importFromOpml();
            }
        }
        return true;
    }
    }

    return super.onOptionsItemSelected(item);
}

From source file:com.viktorrudometkin.burramys.fragment.EditFeedsListFragment.java

@Override
public boolean onOptionsItemSelected(final MenuItem item) {
    switch (item.getItemId()) {
    case R.id.menu_add_feed: {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle(R.string.menu_add_feed).setItems(new CharSequence[] {
                getString(R.string.add_custom_feed), getString(R.string.google_news_title) },
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        if (which == 0) {
                            startActivity(new Intent(Intent.ACTION_INSERT).setData(FeedColumns.CONTENT_URI));
                        } else {
                            startActivity(new Intent(getActivity(), AddGoogleNewsActivity.class));
                        }/*  w w  w.  ja  v  a  2 s .  co  m*/
                    }
                });
        builder.show();
        return true;
    }
    case R.id.menu_add_group: {
        final EditText input = new EditText(getActivity());
        input.setSingleLine(true);
        new AlertDialog.Builder(getActivity()) //
                .setTitle(R.string.add_group_title) //
                .setView(input) //
                // .setMessage(R.string.add_group_sentence) //
                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        new Thread() {
                            @Override
                            public void run() {
                                String groupName = input.getText().toString();
                                if (!groupName.isEmpty()) {
                                    ContentResolver cr = getActivity().getContentResolver();
                                    ContentValues values = new ContentValues();
                                    values.put(FeedColumns.IS_GROUP, true);
                                    values.put(FeedColumns.NAME, groupName);
                                    cr.insert(FeedColumns.GROUPS_CONTENT_URI, values);
                                }
                            }
                        }.start();
                    }
                }).setNegativeButton(android.R.string.cancel, null).show();
        return true;
    }
    case R.id.menu_export:
    case R.id.menu_import: {
        if (ContextCompat.checkSelfPermission(getActivity(),
                Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
                    Manifest.permission.WRITE_EXTERNAL_STORAGE)) {

                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.setMessage(R.string.storage_request_explanation)
                        .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                if (item.getItemId() == R.id.menu_export) {
                                    ActivityCompat.requestPermissions(getActivity(),
                                            new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
                                            PERMISSIONS_REQUEST_EXPORT_TO_OPML);
                                } else if (item.getItemId() == R.id.menu_import) {
                                    ActivityCompat.requestPermissions(getActivity(),
                                            new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
                                            PERMISSIONS_REQUEST_IMPORT_FROM_OPML);
                                }
                            }
                        }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                // User cancelled the dialog
                            }
                        });
                builder.show();
            } else {
                // No explanation needed, we can request the permission.
                if (item.getItemId() == R.id.menu_export) {
                    ActivityCompat.requestPermissions(getActivity(),
                            new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
                            PERMISSIONS_REQUEST_EXPORT_TO_OPML);
                } else if (item.getItemId() == R.id.menu_import) {
                    ActivityCompat.requestPermissions(getActivity(),
                            new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
                            PERMISSIONS_REQUEST_IMPORT_FROM_OPML);
                }
            }
        } else {
            if (item.getItemId() == R.id.menu_export) {
                exportToOpml();
            } else if (item.getItemId() == R.id.menu_import) {
                importFromOpml();
            }
        }

        return true;
    }
    }

    return super.onOptionsItemSelected(item);
}

From source file:com.adkdevelopment.earthquakesurvival.data.syncadapter.SyncAdapter.java

@Override
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider,
        SyncResult syncResult) {/*from w ww .j  a v  a2 s  .c o m*/

    Context context = getContext();

    App.getApiManager().getEarthquakeService().getData().enqueue(new Callback<EarthquakeObject>() {
        @Override
        public void onResponse(Call<EarthquakeObject> call, Response<EarthquakeObject> response) {
            EarthquakeObject earthquake = response.body();

            Vector<ContentValues> cVVector = new Vector<>(earthquake.getFeatures().size());

            double currentBiggest = 0.0;
            ContentValues notifyValues = null;

            for (Feature each : earthquake.getFeatures()) {

                ContentValues earthquakeValues = new ContentValues();

                earthquakeValues.put(EarthquakeColumns.PLACE, each.getProperties().getPlace());
                earthquakeValues.put(EarthquakeColumns.ID_EARTH, each.getId());
                earthquakeValues.put(EarthquakeColumns.MAG, each.getProperties().getMag());
                earthquakeValues.put(EarthquakeColumns.TYPE, each.getProperties().getType());
                earthquakeValues.put(EarthquakeColumns.ALERT, each.getProperties().getAlert());
                earthquakeValues.put(EarthquakeColumns.TIME, each.getProperties().getTime());
                earthquakeValues.put(EarthquakeColumns.URL, each.getProperties().getUrl());
                earthquakeValues.put(EarthquakeColumns.DETAIL, each.getProperties().getDetail());
                earthquakeValues.put(EarthquakeColumns.DEPTH, each.getGeometry().getCoordinates().get(2));
                earthquakeValues.put(EarthquakeColumns.LONGITUDE, each.getGeometry().getCoordinates().get(0));
                earthquakeValues.put(EarthquakeColumns.LATITUDE, each.getGeometry().getCoordinates().get(1));

                LatLng latLng = new LatLng(each.getGeometry().getCoordinates().get(1),
                        each.getGeometry().getCoordinates().get(0));
                LatLng location = LocationUtils.getLocation(context);
                earthquakeValues.put(EarthquakeColumns.DISTANCE, LocationUtils.getDistance(latLng, location));

                cVVector.add(earthquakeValues);

                if (each.getProperties().getMag() != null && each.getProperties().getMag() > currentBiggest) {
                    currentBiggest = each.getProperties().getMag();
                    notifyValues = new ContentValues(earthquakeValues);
                    notifyValues.put(EarthquakeColumns.PLACE,
                            Utilities.formatEarthquakePlace(each.getProperties().getPlace()));
                }
            }

            int inserted = 0;
            // add to database
            ContentResolver resolver = context.getContentResolver();

            if (cVVector.size() > 0) {
                ContentValues[] cvArray = new ContentValues[cVVector.size()];
                cVVector.toArray(cvArray);
                inserted = resolver.bulkInsert(EarthquakeColumns.CONTENT_URI, cvArray);
            }

            // Set the date to day minus one to delete old data from the database
            Date date = new Date();
            date.setTime(date.getTime() - DateUtils.DAY_IN_MILLIS);

            int deleted = resolver.delete(EarthquakeColumns.CONTENT_URI, EarthquakeColumns.TIME + " <= ?",
                    new String[] { String.valueOf(date.getTime()) });
            Log.v(TAG, "Service Complete. " + inserted + " Inserted, " + deleted + " deleted");
            sendNotification(notifyValues);
        }

        @Override
        public void onFailure(Call<EarthquakeObject> call, Throwable t) {
            Log.e(TAG, "onFailure: " + t.toString());
        }
    });

    App.getNewsManager().getNewsService().getNews().enqueue(new Callback<Rss>() {
        @Override
        public void onResponse(Call<Rss> call, Response<Rss> response) {
            Channel news = response.body().getChannel();

            Vector<ContentValues> cVVector = new Vector<>(news.getItem().size());

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z",
                    Locale.getDefault());
            Date date = new Date();

            for (Item each : news.getItem()) {

                ContentValues weatherValues = new ContentValues();

                try {
                    date = simpleDateFormat.parse(each.getPubDate());
                } catch (ParseException e) {
                    Log.e(TAG, "e:" + e);
                }

                weatherValues.put(NewsColumns.DATE, date.getTime());
                weatherValues.put(NewsColumns.TITLE, each.getTitle());
                weatherValues.put(NewsColumns.DESCRIPTION,
                        Html.toHtml(new SpannedString(each.getDescription())));
                weatherValues.put(NewsColumns.URL, each.getLink());
                weatherValues.put(NewsColumns.GUID, each.getGuid().getContent());

                cVVector.add(weatherValues);
            }

            int inserted = 0;
            // add to database
            ContentResolver resolver = getContext().getContentResolver();

            if (cVVector.size() > 0) {

                // Student: call bulkInsert to add the weatherEntries to the database here
                ContentValues[] cvArray = new ContentValues[cVVector.size()];
                cVVector.toArray(cvArray);
                inserted = resolver.bulkInsert(NewsColumns.CONTENT_URI, cvArray);
            }

            // Set the date to day minus two to delete old data from the database
            date = new Date();
            date.setTime(date.getTime() - DateUtils.DAY_IN_MILLIS * 3);

            int deleted = resolver.delete(NewsColumns.CONTENT_URI, NewsColumns.DATE + " <= ?",
                    new String[] { String.valueOf(date.getTime()) });
        }

        @Override
        public void onFailure(Call<Rss> call, Throwable t) {
            Log.e(TAG, "onFailure: " + t.toString());
        }
    });

    // TODO: 4/22/16 possible refactoring 
    //checking the last update and notify if it' the first of the day
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    String lastNotificationKey = context.getString(R.string.sharedprefs_key_last_countupdate);
    long lastSync = prefs.getLong(lastNotificationKey, DateUtils.DAY_IN_MILLIS);

    if (System.currentTimeMillis() - lastSync >= Utilities.getSyncIntervalPrefs(context)
            * DateUtils.SECOND_IN_MILLIS) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
        Date date = new Date(System.currentTimeMillis());

        String startTime[] = new String[] { simpleDateFormat.format(date.getTime() - DateUtils.YEAR_IN_MILLIS),
                simpleDateFormat.format(date.getTime() - DateUtils.DAY_IN_MILLIS * 30),
                simpleDateFormat.format(date.getTime() - DateUtils.WEEK_IN_MILLIS),
                simpleDateFormat.format(date.getTime() - DateUtils.DAY_IN_MILLIS) };

        String endTime = simpleDateFormat.format(date);

        int iterator = 1;
        while (iterator < CountColumns.ALL_COLUMNS.length) {
            final int round = iterator;

            App.getApiManager().getEarthquakeService().getEarthquakeStats(startTime[round - 1], endTime)
                    .enqueue(new Callback<CountEarthquakes>() {
                        @Override
                        public void onResponse(Call<CountEarthquakes> call,
                                Response<CountEarthquakes> response) {
                            ContentValues count = new ContentValues();
                            count.put(CountColumns.ALL_COLUMNS[round], response.body().getCount());

                            ContentResolver contentResolver = context.getContentResolver();

                            Cursor cursor = contentResolver.query(CountColumns.CONTENT_URI, null, null, null,
                                    null);

                            if (cursor != null) {
                                if (cursor.getCount() < 1) {
                                    long inserted = ContentUris
                                            .parseId(contentResolver.insert(CountColumns.CONTENT_URI, count));
                                    //Log.d(TAG, "inserted:" + inserted);
                                } else {
                                    int updated = contentResolver.update(CountColumns.CONTENT_URI, count,
                                            CountColumns._ID + " = ?", new String[] { "1" });
                                    //Log.d(TAG, "updated: " + updated);
                                }
                                cursor.close();
                            }

                        }

                        @Override
                        public void onFailure(Call<CountEarthquakes> call, Throwable t) {
                            Log.e(TAG, "Error: " + t);
                        }
                    });
            iterator++;
        }

        //refreshing last sync
        prefs.edit().putLong(lastNotificationKey, System.currentTimeMillis()).apply();
    }

    // notify PagerActivity that data has been updated
    context.getContentResolver().notifyChange(EarthquakeColumns.CONTENT_URI, null, false);
    context.getContentResolver().notifyChange(NewsColumns.CONTENT_URI, null, false);
    context.getContentResolver().notifyChange(CountColumns.CONTENT_URI, null, false);

    updateWidgets();
}