Example usage for android.content ContentResolver notifyChange

List of usage examples for android.content ContentResolver notifyChange

Introduction

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

Prototype

public void notifyChange(@NonNull Uri uri, @Nullable ContentObserver observer) 

Source Link

Document

Notify registered observers that a row was updated and attempt to sync changes to the network.

Usage

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

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_edit_feed_list, container, false);

    mListView = (DragNDropExpandableListView) rootView.findViewById(android.R.id.list);
    mListView.setFastScrollEnabled(true);
    mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
    mListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
        @Override/*from   w  ww. j ava  2  s  .  c o  m*/
        public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition,
                long id) {
            startActivity(new Intent(Intent.ACTION_EDIT).setData(FeedColumns.CONTENT_URI(id)));
            return true;
        }
    });
    mListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
        @Override
        public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
            if (v.findViewById(R.id.indicator).getVisibility() != View.VISIBLE) { // This is no a real group
                startActivity(new Intent(Intent.ACTION_EDIT).setData(FeedColumns.CONTENT_URI(id)));
                return true;
            }
            return false;
        }
    });
    mListView.setOnItemLongClickListener(new OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
            AppCompatActivity activity = (AppCompatActivity) getActivity();
            if (activity != null) {
                String title = ((TextView) view.findViewById(android.R.id.text1)).getText().toString();
                Matcher m = Pattern.compile("(.*) \\([0-9]+\\)$").matcher(title);
                if (m.matches()) {
                    title = m.group(1);
                }

                long feedId = mListView.getItemIdAtPosition(position);
                ActionMode actionMode;
                if (view.findViewById(R.id.indicator).getVisibility() == View.VISIBLE) { // This is a group
                    actionMode = activity.startSupportActionMode(mGroupActionModeCallback);
                } else { // This is a feed
                    actionMode = activity.startSupportActionMode(mFeedActionModeCallback);
                }
                actionMode.setTag(new Pair<>(feedId, title));

                mListView.setItemChecked(position, true);
            }
            return true;
        }
    });

    mListView.setAdapter(new FeedsCursorAdapter(getActivity(), FeedColumns.GROUPS_CONTENT_URI));

    mListView.setDragNDropListener(new DragNDropListener() {
        boolean fromHasGroupIndicator = false;

        @Override
        public void onStopDrag(View itemView) {
        }

        @Override
        public void onStartDrag(View itemView) {
            fromHasGroupIndicator = itemView.findViewById(R.id.indicator).getVisibility() == View.VISIBLE;
        }

        @Override
        public void onDrop(final int flatPosFrom, final int flatPosTo) {
            final boolean fromIsGroup = ExpandableListView.getPackedPositionType(mListView
                    .getExpandableListPosition(flatPosFrom)) == ExpandableListView.PACKED_POSITION_TYPE_GROUP;
            final boolean toIsGroup = ExpandableListView.getPackedPositionType(mListView
                    .getExpandableListPosition(flatPosTo)) == ExpandableListView.PACKED_POSITION_TYPE_GROUP;

            final boolean fromIsFeedWithoutGroup = fromIsGroup && !fromHasGroupIndicator;

            View toView = mListView.getChildAt(flatPosTo - mListView.getFirstVisiblePosition());
            boolean toIsFeedWithoutGroup = toIsGroup
                    && toView.findViewById(R.id.indicator).getVisibility() != View.VISIBLE;

            final long packedPosTo = mListView.getExpandableListPosition(flatPosTo);
            final int packedGroupPosTo = ExpandableListView.getPackedPositionGroup(packedPosTo);

            if ((fromIsFeedWithoutGroup || !fromIsGroup) && toIsGroup && !toIsFeedWithoutGroup) {
                new AlertDialog.Builder(getActivity()) //
                        .setTitle(R.string.to_group_title) //
                        .setMessage(R.string.to_group_message) //
                        .setPositiveButton(R.string.to_group_into, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                ContentValues values = new ContentValues();
                                values.put(FeedColumns.PRIORITY, 1);
                                values.put(FeedColumns.GROUP_ID, mListView.getItemIdAtPosition(flatPosTo));

                                ContentResolver cr = getActivity().getContentResolver();
                                cr.update(FeedColumns.CONTENT_URI(mListView.getItemIdAtPosition(flatPosFrom)),
                                        values, null, null);
                                cr.notifyChange(FeedColumns.GROUPS_CONTENT_URI, null);
                            }
                        }).setNegativeButton(R.string.to_group_above, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                moveItem(fromIsGroup, toIsGroup, fromIsFeedWithoutGroup, packedPosTo,
                                        packedGroupPosTo, flatPosFrom);
                            }
                        }).show();
            } else {
                moveItem(fromIsGroup, toIsGroup, fromIsFeedWithoutGroup, packedPosTo, packedGroupPosTo,
                        flatPosFrom);
            }
        }

        @Override
        public void onDrag(int x, int y, ListView listView) {
        }
    });

    return rootView;
}

From source file:co.nerdart.ourss.fragment.FeedsListFragment.java

@Override
public boolean onOptionsItemSelected(final MenuItem item) {
    setFeedSortEnabled(false);/*from w w  w . j a  v a  2s  .co m*/

    switch (item.getItemId()) {
    case R.id.menu_add_feed: {
        startActivity(new Intent(Intent.ACTION_INSERT).setData(FeedColumns.CONTENT_URI));
        return true;
    }
    case R.id.menu_refresh: {
        if (!FetcherService.isRefreshingFeeds) {
            getActivity().startService(
                    new Intent(getActivity(), FetcherService.class).setAction(Constants.ACTION_REFRESH_FEEDS));
        }
        return true;
    }
    case R.id.menu_settings: {
        startActivity(new Intent(getActivity(), GeneralPrefsActivity.class));
        return true;
    }
    case R.id.menu_all_read: {
        new Thread() {
            @Override
            public void run() {
                ContentResolver cr = getActivity().getContentResolver();
                if (cr.update(EntryColumns.CONTENT_URI, FeedData.getReadContentValues(),
                        EntryColumns.WHERE_UNREAD, null) > 0) {
                    cr.notifyChange(FeedColumns.CONTENT_URI, null);
                    cr.notifyChange(FeedColumns.GROUPS_CONTENT_URI, null);
                    cr.notifyChange(EntryColumns.FAVORITES_CONTENT_URI, null);
                }
            }
        }.start();
        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_import: {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)
                || Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
            final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

            builder.setTitle(R.string.select_file);

            try {
                final String[] fileNames = Environment.getExternalStorageDirectory().list(new FilenameFilter() {
                    @Override
                    public boolean accept(File dir, String filename) {
                        return new File(dir, filename).isFile();
                    }
                });
                builder.setItems(fileNames, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, final int which) {
                        new Thread(new Runnable() { // To not block the UI
                            @Override
                            public void run() {
                                try {
                                    OPML.importFromFile(Environment.getExternalStorageDirectory().toString()
                                            + File.separator + fileNames[which]);
                                } catch (Exception e) {
                                    getActivity().runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Crouton.makeText(getActivity(), R.string.error_feed_import,
                                                    Style.INFO);
                                        }
                                    });
                                }
                            }
                        }).start();
                    }
                });
                builder.show();
            } catch (Exception e) {
                Crouton.makeText(getActivity(), R.string.error_feed_import, Style.INFO);
            }
        } else {
            Crouton.makeText(getActivity(), R.string.error_external_storage_not_available, Style.INFO);
        }

        return true;
    }
    case R.id.menu_export: {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)
                || Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {

            new Thread(new Runnable() { // To not block the UI
                @Override
                public void run() {
                    try {
                        final String filename = Environment.getExternalStorageDirectory().toString() + "/OURSS_"
                                + System.currentTimeMillis() + ".opml";

                        OPML.exportToFile(filename);
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                //Toast.makeText(getActivity(),
                                //      String.format
                                //  (getString(R.string.message_exported_to),
                                //    filename),Toast.LENGTH_LONG).show();
                                Crouton.makeText(getActivity(),
                                        String.format(getString(R.string.message_exported_to), filename),
                                        Style.INFO);
                            }
                        });
                    } catch (Exception e) {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                //Toast.makeText(getActivity(),
                                //      R.string.error_feed_export,
                                //    Toast.LENGTH_LONG).show();
                                Crouton.makeText(getActivity(), R.string.error_feed_export, Style.INFO);
                            }
                        });
                    }
                }
            }).start();
        } else {
            //Toast.makeText(getActivity(), R.string.error_external_storage_not_available,
            //      Toast.LENGTH_LONG).show();
            Crouton.makeText(getActivity(), R.string.error_external_storage_not_available, Style.INFO);
        }
        break;
    }
    case R.id.menu_enable_feed_sort: {
        setFeedSortEnabled(true);
        return true;
    }
    case R.id.menu_disable_feed_sort: {
        // do nothing as the feed sort gets disabled anyway
        return true;
    }
    }

    return super.onOptionsItemSelected(item);
}

From source file:de.vanita5.twittnuker.provider.TwidereDataProvider.java

private void notifyContentObserver(final Uri uri) {
    final ContentResolver cr = getContentResolver();
    if (uri == null || cr == null)
        return;/*from w w w .  j  av a 2 s.  c o  m*/
    cr.notifyChange(uri, null);
}

From source file:com.akop.bach.parser.PsnParser.java

private void parseAccountSummary(PsnAccount account) throws ParserException, IOException {
    ContentValues cv = parseSummaryData(account);
    ContentResolver cr = mContext.getContentResolver();

    long accountId = account.getId();
    boolean newRecord = true;

    long started = System.currentTimeMillis();
    Cursor c = cr.query(Profiles.CONTENT_URI, new String[] { Profiles._ID },
            Profiles.ACCOUNT_ID + "=" + accountId, null, null);

    if (c != null) {
        if (c.moveToFirst())
            newRecord = false;/*from   w  w w.  j a  v a 2s .c o  m*/
        c.close();
    }

    if (newRecord) {
        cv.put(Profiles.ACCOUNT_ID, account.getId());
        cv.put(Profiles.UUID, account.getUuid());

        cr.insert(Profiles.CONTENT_URI, cv);
    } else {
        cr.update(Profiles.CONTENT_URI, cv, Profiles.ACCOUNT_ID + "=" + accountId, null);
    }

    cr.notifyChange(Profiles.CONTENT_URI, null);

    if (App.getConfig().logToConsole())
        displayTimeTaken("Summary update", started);

    account.refresh(Preferences.get(mContext));
    account.setOnlineId(cv.getAsString(Profiles.ONLINE_ID));
    account.setIconUrl(cv.getAsString(Profiles.ICON_URL));
    account.setLastSummaryUpdate(System.currentTimeMillis());
    account.save(Preferences.get(mContext));
}

From source file:com.google.android.apps.muzei.provider.MuzeiProvider.java

@NonNull
@Override/* w  w w .ja va  2s .c o m*/
public ContentProviderResult[] applyBatch(@NonNull final ArrayList<ContentProviderOperation> operations)
        throws OperationApplicationException {
    holdNotifyChange = true;
    try {
        return super.applyBatch(operations);
    } finally {
        holdNotifyChange = false;
        boolean broadcastSourceChanged = false;
        Context context = getContext();
        if (context != null) {
            ContentResolver contentResolver = context.getContentResolver();
            synchronized (pendingNotifyChange) {
                Iterator<Uri> iterator = pendingNotifyChange.iterator();
                while (iterator.hasNext()) {
                    Uri uri = iterator.next();
                    contentResolver.notifyChange(uri, null);
                    if (MuzeiContract.Artwork.CONTENT_URI.equals(uri)) {
                        context.sendBroadcast(new Intent(MuzeiContract.Artwork.ACTION_ARTWORK_CHANGED));
                    } else if (MuzeiProvider.uriMatcher.match(uri) == SOURCES
                            || MuzeiProvider.uriMatcher.match(uri) == SOURCE_ID) {
                        broadcastSourceChanged = true;
                    }
                    iterator.remove();
                }
            }
            if (broadcastSourceChanged) {
                context.sendBroadcast(new Intent(MuzeiContract.Sources.ACTION_SOURCE_CHANGED));
            }
        }
    }
}

From source file:mobisocial.musubi.service.AddressBookUpdateHandler.java

@Override
public void onChange(boolean selfChange) {
    final DatabaseManager dbManager = new DatabaseManager(mContext);
    if (!dbManager.getIdentitiesManager().hasConnectedAccounts()) {
        Log.w(TAG, "no connected accounts, skipping friend import");
        return;/*from  w  ww  .  j a v a 2s. co m*/
    }

    //a new meta contact appears (and the previous ones disappear) if the user merges
    //or if a new entry is added, we can detect the ones that have changed by
    //this condition
    long highestContactIdAlreadySeen = dbManager.getContactDataVersionManager().getMaxContactIdSeen();
    //a new data item corresponds with a new contact, but its possible
    //that a users just adds a new contact method to an existing contact
    //and we need to detect that
    long highestDataIdAlreadySeen = dbManager.getContactDataVersionManager().getMaxDataIdSeen();

    // BJD -- this didn't end up being faster once all import features were added.
    /*if (highestContactIdAlreadySeen == -1) {
       importFullAddressBook(mContext);
       return;
    }*/
    long now = System.currentTimeMillis();
    if (mLastRun + ONCE_PER_PERIOD > now) {
        //wake up when the period expires
        if (!mScheduled) {
            new Handler(mThread.getLooper()).postDelayed(new Runnable() {
                @Override
                public void run() {
                    mScheduled = false;
                    dispatchChange(false);
                }
            }, ONCE_PER_PERIOD - (now - mLastRun) + 1);
        }
        mScheduled = true;
        //skip this update
        return;
    }
    Log.i(TAG, "waking up to handle contact changes...");
    boolean identityAdded = false, profileDataChanged = false;
    Date start = new Date();

    assert (SYNC_EMAIL);
    String account_type_selection = getAccountSelectionString();

    Cursor c = mContext.getContentResolver().query(
            ContactsContract.Data.CONTENT_URI, new String[] { ContactsContract.Data._ID,
                    ContactsContract.Data.DATA_VERSION, ContactsContract.Data.CONTACT_ID },
            "(" + ContactsContract.Data.DATA_VERSION + ">0 OR " + //maybe updated
                    ContactsContract.Data.CONTACT_ID + ">? OR " + //definitely new or merged
                    ContactsContract.Data._ID + ">? " + //definitely added a data item
                    ") AND (" + ContactsContract.RawContacts.ACCOUNT_TYPE + "<>'" + mAccountType + "'"
                    + ") AND (" + NAME_OR_OTHER_SELECTION + account_type_selection + ")", // All known contacts.
            new String[] { String.valueOf(highestContactIdAlreadySeen),
                    String.valueOf(highestDataIdAlreadySeen) },
            null);

    if (c == null) {
        Log.e(TAG, "no valid cursor", new Throwable());
        mContext.getContentResolver().notifyChange(MusubiService.ADDRESS_BOOK_SCANNED, this);
        return;
    }

    HashMap<Pair<String, String>, MMyAccount> account_mapping = new HashMap<Pair<String, String>, MMyAccount>();
    int max_changes = c.getCount();
    TLongArrayList raw_data_ids = new TLongArrayList(max_changes);
    TLongArrayList versions = new TLongArrayList(max_changes);
    long new_max_data_id = highestDataIdAlreadySeen;
    long new_max_contact_id = highestContactIdAlreadySeen;
    TLongHashSet potentially_changed = new TLongHashSet();
    try {
        //the cursor points to a list of raw contact data items that may have changed
        //the items will include a type specific field that we are interested in updating
        //it is possible that multiple data item entries mention the same identifier
        //so we build a list of contacts to update and then perform synchronization
        //by refreshing given that we know the top level contact id.
        if (DBG)
            Log.d(TAG, "Scanning " + c.getCount() + " contacts...");
        while (c.moveToNext()) {
            if (DBG)
                Log.v(TAG, "check for updates of contact " + c.getLong(0));

            long raw_data_id = c.getLong(0);
            long version = c.getLong(1);
            long contact_id = c.getLong(2);

            //if the contact was split or merged, then we get a higher contact id
            //so if we have a higher id, data version doesnt really matter
            if (contact_id <= highestContactIdAlreadySeen) {
                //the data associated with this contact may not be dirty
                //we just can't do the join against our table because thise
                //api is implmented over the content provider
                if (dbManager.getContactDataVersionManager().getVersion(raw_data_id) == version)
                    continue;
            } else {
                new_max_contact_id = Math.max(new_max_contact_id, contact_id);
            }
            raw_data_ids.add(raw_data_id);
            versions.add(version);
            potentially_changed.add(contact_id);
            new_max_data_id = Math.max(new_max_data_id, raw_data_id);
        }
        if (DBG)
            Log.d(TAG, "Finished iterating over " + c.getCount() + " contacts for " + potentially_changed.size()
                    + " candidates.");
    } finally {
        c.close();
    }
    if (potentially_changed.size() == 0) {
        Log.w(TAG,
                "possible bug, woke up to update contacts, but no change was detected; there are extra wakes so it could be ok");
    }

    final SQLiteDatabase db = dbManager.getDatabase();

    Pattern emailPattern = getEmailPattern();
    Pattern numberPattern = getNumberPattern();
    //slice it up so we don't use too much system resource on keeping a lot of state in memory
    int total = potentially_changed.size();
    sAddressBookTotal = total;
    sAddressBookPosition = 0;

    final TLongArrayList slice_of_changed = new TLongArrayList(BATCH_SIZE);
    final StringBuilder to_fetch = new StringBuilder();
    final HashMap<Pair<String, String>, TLongHashSet> ids_for_account = new HashMap<Pair<String, String>, TLongHashSet>();
    final TLongObjectHashMap<String> names = new TLongObjectHashMap<String>();

    TLongIterator it = potentially_changed.iterator();
    for (int i = 0; i < total && it.hasNext();) {
        sAddressBookPosition = i;

        if (BootstrapActivity.isBootstrapped()) {
            try {
                Thread.sleep(mSleepTime * SLEEP_SCALE);
            } catch (InterruptedException e) {
            }
        }

        slice_of_changed.clear();
        ids_for_account.clear();
        names.clear();

        int max = i + BATCH_SIZE;
        for (; i < max && it.hasNext(); ++i) {
            slice_of_changed.add(it.next());
        }

        if (DBG)
            Log.v(TAG, "looking up names ");
        to_fetch.setLength(0);
        to_fetch.append(ContactsContract.Contacts._ID + " IN ");
        SQLClauseHelper.appendArray(to_fetch, slice_of_changed.iterator());
        //lookup the fields we care about from a user profile perspective
        c = mContext.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,
                new String[] { ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME, },
                to_fetch.toString(), null, null);
        try {
            while (c.moveToNext()) {
                long id = c.getLong(0);
                String name = c.getString(1);
                if (name == null)
                    continue;
                //reject names that are just the email address or are just a number 
                //the default for android is just to propagate this as the name
                //if there is no name
                if (emailPattern.matcher(name).matches() || numberPattern.matcher(name).matches())
                    continue;
                names.put(id, name);
            }
        } finally {
            c.close();
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            db.beginTransactionNonExclusive();
        } else {
            db.beginTransaction();
        }

        long before = SystemClock.elapsedRealtime();
        SliceUpdater updater = new SliceUpdater(dbManager, slice_of_changed, ids_for_account, names,
                account_type_selection);
        long after = SystemClock.elapsedRealtime();
        mSleepTime = (mSleepTime + after - before) / 2;
        slice_of_changed.forEach(updater);
        profileDataChanged |= updater.profileDataChanged;
        identityAdded |= updater.identityAdded;
        db.setTransactionSuccessful();
        db.endTransaction();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            db.beginTransactionNonExclusive();
        } else {
            db.beginTransaction();
        }
        //add all detected members to account feed
        for (Entry<Pair<String, String>, TLongHashSet> e : ids_for_account.entrySet()) {
            Pair<String, String> k = e.getKey();
            TLongHashSet v = e.getValue();
            MMyAccount cached_account = account_mapping.get(k);
            if (cached_account == null) {
                cached_account = lookupOrCreateAccount(dbManager, k.getValue0(), k.getValue1());
                prepareAccountWhitelistFeed(dbManager.getMyAccountManager(), dbManager.getFeedManager(),
                        cached_account);
                account_mapping.put(k, cached_account);
            }

            final MMyAccount account = cached_account;
            v.forEach(new TLongProcedure() {
                @Override
                public boolean execute(long id) {
                    dbManager.getFeedManager().ensureFeedMember(account.feedId_, id);
                    db.yieldIfContendedSafely(75);
                    return true;
                }
            });
        }
        db.setTransactionSuccessful();
        db.endTransaction();
    }

    sAddressBookTotal = sAddressBookPosition = 0;

    //TODO: handle deleted
    //for all android data ids in our table, check if they still exist in the
    //contacts table, probably in batches of 100 or something.  if they don't
    //null them out.  this is annoyingly non-differential.

    //TODO: adding friend should update accepted feed status, however,
    //if a crashe happens for whatever reason, then its possible that this may need to
    //be run for identities which actually exist in the db.  so this update code
    //needs to do the feed accepted status change for all users that were touched
    //by the profile update process

    //update the version ids so we can be faster on subsequent runs
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        db.beginTransactionNonExclusive();
    } else {
        db.beginTransaction();
    }
    int changed_data_rows = raw_data_ids.size();
    for (int i = 0; i < changed_data_rows; ++i) {
        dbManager.getContactDataVersionManager().setVersion(raw_data_ids.get(i), versions.get(i));
    }
    db.setTransactionSuccessful();
    db.endTransaction();

    dbManager.getContactDataVersionManager().setMaxDataIdSeen(new_max_data_id);
    dbManager.getContactDataVersionManager().setMaxContactIdSeen(new_max_contact_id);
    ContentResolver resolver = mContext.getContentResolver();

    Date end = new Date();
    double time = end.getTime() - start.getTime();
    time /= 1000;
    Log.w(TAG, "update address book " + mChangeCount++ + " took " + time + " seconds");
    if (identityAdded) {
        //wake up the profile push
        resolver.notifyChange(MusubiService.WHITELIST_APPENDED, this);
    }
    if (profileDataChanged) {
        //refresh the ui...
        resolver.notifyChange(MusubiService.PRIMARY_CONTENT_CHANGED, this);
    }
    if (identityAdded || profileDataChanged) {
        //update the our musubi address book as needed.
        String accountName = mContext.getString(R.string.account_name);
        String accountType = mContext.getString(R.string.account_type);
        Account account = new Account(accountName, accountType);
        ContentResolver.requestSync(account, ContactsContract.AUTHORITY, new Bundle());
    }

    dbManager.close();
    mLastRun = new Date().getTime();
    resolver.notifyChange(MusubiService.ADDRESS_BOOK_SCANNED, this);
}

From source file:edu.stanford.mobisocial.dungbeetle.DungBeetleContentProvider.java

/**
 * Inserts a message locally that has been received from some agent,
 * typically from a remote device./*  ww  w.  jav  a  2 s  . co m*/
 */
@Override
public Uri insert(Uri uri, ContentValues values) {
    ContentResolver resolver = getContext().getContentResolver();
    if (DBG)
        Log.i(TAG, "Inserting at uri: " + uri + ", " + values);

    final String appId = getCallingActivityId();
    if (appId == null) {
        Log.d(TAG, "No AppId for calling activity. Ignoring query.");
        return null;
    }

    List<String> segs = uri.getPathSegments();
    if (match(uri, "feeds", "me")) {
        if (!appId.equals(SUPER_APP_ID)) {
            return null;
        }

        long objId = mHelper.addToFeed(appId, "friend", values);
        Uri objUri = DbObject.uriForObj(objId);
        resolver.notifyChange(Feed.uriForName("me"), null);
        resolver.notifyChange(Feed.uriForName("friend"), null);
        resolver.notifyChange(objUri, null);
        return objUri;
    } else if (match(uri, "feeds", ".+")) {
        String feedName = segs.get(1);
        String type = values.getAsString(DbObject.TYPE);
        try {
            JSONObject json = new JSONObject(values.getAsString(DbObject.JSON));
            String objHash = null;
            if (feedName.contains(":")) {
                String[] parts = feedName.split(":");
                feedName = parts[0];
                objHash = parts[1];
            }
            if (objHash != null) {
                json.put(DbObjects.TARGET_HASH, Long.parseLong(objHash));
                json.put(DbObjects.TARGET_RELATION, DbRelation.RELATION_PARENT);
                values.put(DbObject.JSON, json.toString());
            }

            String appAuthority = appId;
            if (SUPER_APP_ID.equals(appId)) {
                if (AppObj.TYPE.equals(type)) {
                    if (json.has(AppObj.ANDROID_PACKAGE_NAME)) {
                        appAuthority = json.getString(AppObj.ANDROID_PACKAGE_NAME);
                    }
                }
            }

            long objId = mHelper.addToFeed(appAuthority, feedName, values);
            Uri objUri = DbObject.uriForObj(objId);
            resolver.notifyChange(objUri, null);
            notifyDependencies(mHelper, resolver, segs.get(1));
            if (DBG)
                Log.d(TAG, "just inserted " + values.getAsString(DbObject.JSON));
            return objUri;
        } catch (JSONException e) {
            return null;
        }
    } else if (match(uri, "out")) {
        try {
            JSONObject obj = new JSONObject(values.getAsString("json"));
            long objId = mHelper.addToOutgoing(appId, values.getAsString(DbObject.DESTINATION),
                    values.getAsString(DbObject.TYPE), obj);
            resolver.notifyChange(Uri.parse(CONTENT_URI + "/out"), null);
            return DbObject.uriForObj(objId);
        } catch (JSONException e) {
            return null;
        }
    } else if (match(uri, "contacts")) {
        if (!appId.equals(SUPER_APP_ID)) {
            return null;
        }
        long id = mHelper.insertContact(values);
        resolver.notifyChange(Uri.parse(CONTENT_URI + "/contacts"), null);
        return uriWithId(uri, id);
    } else if (match(uri, "subscribers")) {
        // Question: Should this be restricted?
        // if(!appId.equals(SUPER_APP_ID)) return null;
        long id = mHelper.insertSubscriber(values);
        resolver.notifyChange(Uri.parse(CONTENT_URI + "/subscribers"), null);
        return uriWithId(uri, id);
    } else if (match(uri, "groups")) {
        if (!appId.equals(SUPER_APP_ID))
            return null;
        long id = mHelper.insertGroup(values);
        getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/groups"), null);
        return uriWithId(uri, id);
    } else if (match(uri, "group_members")) {
        if (!appId.equals(SUPER_APP_ID)) {
            return null;
        }
        long id = mHelper.insertGroupMember(values);
        getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/group_members"), null);
        getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/group_contacts"), null);
        return uriWithId(uri, id);
    }

    else if (match(uri, "group_invitations")) {
        if (!appId.equals(SUPER_APP_ID)) {
            return null;
        }
        String groupName = values.getAsString(InviteToGroupObj.GROUP_NAME);
        Uri dynUpdateUri = Uri.parse(values.getAsString(InviteToGroupObj.DYN_UPDATE_URI));
        long gid = values.getAsLong("groupId");
        SQLiteDatabase db = mHelper.getWritableDatabase();
        mHelper.addToOutgoing(db, appId, values.getAsString(InviteToGroupObj.PARTICIPANTS),
                InviteToGroupObj.TYPE, InviteToGroupObj.json(groupName, dynUpdateUri));
        getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/out"), null);
        return uriWithId(uri, gid);
    }

    else if (match(uri, "dynamic_groups")) {
        if (!appId.equals(SUPER_APP_ID)) {
            return null;
        }
        Uri gUri = Uri.parse(values.getAsString("uri"));
        GroupProviders.GroupProvider gp = GroupProviders.forUri(gUri);
        String feedName = gp.feedName(gUri);
        Maybe<Group> mg = mHelper.groupByFeedName(feedName);
        long id = -1;
        try {
            Group g = mg.get();
            id = g.id;
        } catch (Maybe.NoValError e) {
            ContentValues cv = new ContentValues();
            cv.put(Group.NAME, gp.groupName(gUri));
            cv.put(Group.FEED_NAME, feedName);
            cv.put(Group.DYN_UPDATE_URI, gUri.toString());

            String table = DbObject.TABLE;
            String[] columns = new String[] { DbObject.FEED_NAME };
            String selection = DbObject.CHILD_FEED_NAME + " = ?";
            String[] selectionArgs = new String[] { feedName };
            Cursor parent = mHelper.getReadableDatabase().query(table, columns, selection, selectionArgs, null,
                    null, null);
            try {
                if (parent.moveToFirst()) {
                    String parentName = parent.getString(0);
                    table = Group.TABLE;
                    columns = new String[] { Group._ID };
                    selection = Group.FEED_NAME + " = ?";
                    selectionArgs = new String[] { parentName };

                    Cursor parent2 = mHelper.getReadableDatabase().query(table, columns, selection,
                            selectionArgs, null, null, null);
                    try {
                        if (parent2.moveToFirst()) {
                            cv.put(Group.PARENT_FEED_ID, parent2.getLong(0));
                        } else {
                            Log.e(TAG, "Parent feed found but no id for " + parentName);
                        }
                    } finally {
                        parent2.close();
                    }
                } else {
                    Log.w(TAG, "No parent feed for " + feedName);
                }
            } finally {
                parent.close();
            }
            id = mHelper.insertGroup(cv);
            getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/dynamic_groups"), null);
            getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/groups"), null);
        }
        return uriWithId(uri, id);
    }

    else if (match(uri, "dynamic_group_member")) {
        if (!appId.equals(SUPER_APP_ID)) {
            return null;
        }
        SQLiteDatabase db = mHelper.getWritableDatabase();
        db.beginTransaction();
        try {
            ContentValues cv = new ContentValues();
            String pubKeyStr = values.getAsString(Contact.PUBLIC_KEY);
            RSAPublicKey k = RSACrypto.publicKeyFromString(pubKeyStr);
            String personId = mIdent.personIdForPublicKey(k);
            if (!personId.equals(mIdent.userPersonId())) {
                cv.put(Contact.PUBLIC_KEY, values.getAsString(Contact.PUBLIC_KEY));
                cv.put(Contact.NAME, values.getAsString(Contact.NAME));
                cv.put(Contact.EMAIL, values.getAsString(Contact.EMAIL));
                if (values.getAsString(Contact.PICTURE) != null) {
                    cv.put(Contact.PICTURE, values.getAsByteArray(Contact.PICTURE));
                }

                long cid = -1;
                Contact contact = mHelper.contactForPersonId(personId).otherwise(Contact.NA());
                if (contact.id > -1) {
                    cid = contact.id;
                } else {
                    cid = mHelper.insertContact(db, cv);
                }

                if (cid > -1) {

                    ContentValues gv = new ContentValues();
                    gv.put(GroupMember.GLOBAL_CONTACT_ID, values.getAsString(GroupMember.GLOBAL_CONTACT_ID));
                    gv.put(GroupMember.GROUP_ID, values.getAsLong(GroupMember.GROUP_ID));
                    gv.put(GroupMember.CONTACT_ID, cid);
                    mHelper.insertGroupMember(db, gv);
                    getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/group_members"),
                            null);
                    getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/contacts"), null);
                    getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/group_contacts"),
                            null);

                    // Add subscription to this private group feed
                    ContentValues sv = new ContentValues();
                    sv = new ContentValues();
                    sv.put(Subscriber.CONTACT_ID, cid);
                    sv.put(Subscriber.FEED_NAME, values.getAsString(Group.FEED_NAME));
                    mHelper.insertSubscriber(db, sv);

                    ContentValues xv = new ContentValues();
                    xv.put(Subscriber.CONTACT_ID, cid);
                    xv.put(Subscriber.FEED_NAME, "friend");
                    mHelper.insertSubscriber(db, xv);

                    getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/subscribers"),
                            null);

                    db.setTransactionSuccessful();
                }
                return uriWithId(uri, cid);
            } else {
                Log.i(TAG, "Omitting self.");
                return uriWithId(uri, Contact.MY_ID);
            }
        } finally {
            db.endTransaction();
        }
    } else {
        Log.e(TAG, "Failed to insert into " + uri);
        return null;
    }
}

From source file:org.m2x.rssreader.service.FetcherService.java

private void downloadAllImages() {
    ContentResolver cr = MainApplication.getContext().getContentResolver();
    Cursor cursor = cr.query(TaskColumns.CONTENT_URI,
            new String[] { TaskColumns._ID, TaskColumns.ENTRY_ID, TaskColumns.IMG_URL_TO_DL,
                    TaskColumns.NUMBER_ATTEMPT },
            TaskColumns.IMG_URL_TO_DL + Constants.DB_IS_NOT_NULL, null, null);

    ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>();

    while (cursor.moveToNext()) {
        long taskId = cursor.getLong(0);
        long entryId = cursor.getLong(1);
        String imgPath = cursor.getString(2);
        int nbAttempt = 0;
        if (!cursor.isNull(3)) {
            nbAttempt = cursor.getInt(3);
        }/*from  w ww .j  a va  2  s  .  c om*/

        try {
            NetworkUtils.downloadImage(entryId, imgPath);

            // If we are here, everything is OK
            operations.add(ContentProviderOperation.newDelete(TaskColumns.CONTENT_URI(taskId)).build());
            cr.notifyChange(EntryColumns.CONTENT_URI(entryId), null); // To refresh the view
        } catch (Exception e) {
            if (nbAttempt + 1 > MAX_TASK_ATTEMPT) {
                operations.add(ContentProviderOperation.newDelete(TaskColumns.CONTENT_URI(taskId)).build());
            } else {
                ContentValues values = new ContentValues();
                values.put(TaskColumns.NUMBER_ATTEMPT, nbAttempt + 1);
                operations.add(ContentProviderOperation.newUpdate(TaskColumns.CONTENT_URI(taskId))
                        .withValues(values).build());
            }
        }
    }

    cursor.close();

    if (!operations.isEmpty()) {
        try {
            cr.applyBatch(FeedData.AUTHORITY, operations);
        } catch (Throwable ignored) {
        }
    }
}

From source file:co.nerdart.ourss.activity.EditFeedActivity.java

public void onClickOk(View view) {
    // only in insert mode

    String url = mUrlEditText.getText().toString();
    ContentResolver cr = getContentResolver();

    if (!url.startsWith(Constants.HTTP) && !url.startsWith(Constants.HTTPS)) {
        url = Constants.HTTP + url;//from   ww w.  j a  va2 s. c o m
    }

    Cursor cursor = cr.query(FeedColumns.CONTENT_URI, null, FeedColumns.URL + Constants.DB_ARG,
            new String[] { url }, null);

    if (cursor.moveToFirst()) {
        cursor.close();
        Crouton.makeText(EditFeedActivity.this, R.string.error_feed_url_exists, Style.INFO);
    } else {
        cursor.close();
        ContentValues values = new ContentValues();

        values.put(FeedColumns.URL, url);
        values.putNull(FeedColumns.ERROR);

        String name = mNameEditText.getText().toString();

        if (name.trim().length() > 0) {
            values.put(FeedColumns.NAME, name);
        }
        values.put(FeedColumns.RETRIEVE_FULLTEXT, mRetrieveFulltextCb.isChecked() ? 1 : null);
        cr.insert(FeedColumns.CONTENT_URI, values);
        cr.notifyChange(FeedColumns.GROUPS_CONTENT_URI, null);
    }

    setResult(RESULT_OK);
    finish();
}

From source file:cn.edu.nju.dapenti.activity.EditFeedActivity.java

public void onClickOk(View view) {
    // only in insert mode

    String url = mUrlEditText.getText().toString();
    ContentResolver cr = getContentResolver();

    if (!url.startsWith(Constants.HTTP) && !url.startsWith(Constants.HTTPS)) {
        url = Constants.HTTP + url;//from   w  w w. j  av  a  2 s .c o  m
    }

    Cursor cursor = cr.query(FeedColumns.CONTENT_URI, null, FeedColumns.URL + Constants.DB_ARG,
            new String[] { url }, null);

    if (cursor.moveToFirst()) {
        cursor.close();
        Toast.makeText(EditFeedActivity.this, R.string.error_feed_url_exists, Toast.LENGTH_LONG).show();
    } else {
        cursor.close();
        ContentValues values = new ContentValues();

        values.put(FeedColumns.URL, url);
        values.putNull(FeedColumns.ERROR);

        String name = mNameEditText.getText().toString();

        if (name.trim().length() > 0) {
            values.put(FeedColumns.NAME, name);
        }
        values.put(FeedColumns.RETRIEVE_FULLTEXT, mRetrieveFulltextCb.isChecked() ? 1 : null);
        cr.insert(FeedColumns.CONTENT_URI, values);
        cr.notifyChange(FeedColumns.GROUPS_CONTENT_URI, null);
        cr.notifyChange(FeedColumns.GROUPED_FEEDS_CONTENT_URI, null);
    }

    setResult(RESULT_OK);
    finish();
}