Example usage for android.content ContentResolver query

List of usage examples for android.content ContentResolver query

Introduction

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

Prototype

public final @Nullable Cursor query(@RequiresPermission.Read @NonNull Uri uri, @Nullable String[] projection,
        @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) 

Source Link

Document

Query the given URI, returning a Cursor over the result set.

Usage

From source file:com.app.uafeed.fragment.EntryFragment.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (mEntriesIds != null) {
        Activity activity = getActivity();

        switch (item.getItemId()) {
        case R.id.menu_star: {
            mFavorite = !mFavorite;//from  w w  w .  j a  va2  s  . c om

            if (mFavorite) {
                item.setTitle(R.string.menu_unstar).setIcon(R.drawable.rating_important);
            } else {
                item.setTitle(R.string.menu_star).setIcon(R.drawable.rating_not_important);
            }

            final Uri uri = ContentUris.withAppendedId(mBaseUri, mEntriesIds[mCurrentPagerPos]);
            new Thread() {
                @Override
                public void run() {
                    ContentValues values = new ContentValues();
                    values.put(EntryColumns.IS_FAVORITE, mFavorite ? 1 : 0);
                    ContentResolver cr = MainApplication.getContext().getContentResolver();
                    cr.update(uri, values, null, null);

                    // Update the cursor
                    Cursor updatedCursor = cr.query(uri, null, null, null, null);
                    updatedCursor.moveToFirst();
                    mEntryPagerAdapter.setUpdatedCursor(mCurrentPagerPos, updatedCursor);
                }
            }.start();
            break;
        }
        case R.id.menu_share: {
            Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos);
            String link = cursor.getString(mLinkPos);
            if (link != null) {
                String title = cursor.getString(mTitlePos);
                startActivity(Intent.createChooser(
                        new Intent(Intent.ACTION_SEND).putExtra(Intent.EXTRA_SUBJECT, title)
                                .putExtra(Intent.EXTRA_TEXT, link).setType(Constants.MIMETYPE_TEXT_PLAIN),
                        getString(R.string.menu_share)));
            }
            break;
        }
        case R.id.menu_full_screen: {
            toggleFullScreen();
            break;
        }
        case R.id.menu_copy_clipboard: {
            Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos);
            String link = cursor.getString(mLinkPos);
            ClipboardManager clipboard = (ClipboardManager) activity
                    .getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData clip = ClipData.newPlainText("Copied Text", link);
            clipboard.setPrimaryClip(clip);

            Toast.makeText(activity, R.string.copied_clipboard, Toast.LENGTH_SHORT).show();
            break;
        }
        case R.id.menu_mark_as_unread: {
            final Uri uri = ContentUris.withAppendedId(mBaseUri, mEntriesIds[mCurrentPagerPos]);
            new Thread() {
                @Override
                public void run() {
                    ContentResolver cr = MainApplication.getContext().getContentResolver();
                    cr.update(uri, FeedData.getUnreadContentValues(), null, null);
                }
            }.start();
            activity.finish();
            break;
        }
        }
    }

    return true;
}

From source file:com.ichi2.anki.tests.ContentProviderTest.java

/**
 * Check that querying the current model gives a valid result
 *//*from w  w w  .  j  av  a2 s  .  c o  m*/
public void testQueryCurrentModel() {
    final ContentResolver cr = getContext().getContentResolver();
    Uri uri = Uri.withAppendedPath(FlashCardsContract.Model.CONTENT_URI,
            FlashCardsContract.Model.CURRENT_MODEL_ID);
    final Cursor modelCursor = cr.query(uri, null, null, null, null);
    assertNotNull(modelCursor);
    try {
        assertEquals("Check that there is exactly one result", 1, modelCursor.getCount());
        assertTrue("Move to beginning of cursor", modelCursor.moveToFirst());
        assertNotNull("Check non-empty field names",
                modelCursor.getString(modelCursor.getColumnIndex(FlashCardsContract.Model.FIELD_NAMES)));
        assertTrue("Check at least one template",
                modelCursor.getInt(modelCursor.getColumnIndex(FlashCardsContract.Model.NUM_CARDS)) > 0);
    } finally {
        modelCursor.close();
    }
}

From source file:edu.cens.loci.ui.VisitDetailActivity.java

private void updateData(Uri visitUri) {
    ContentResolver resolver = getContentResolver();
    Cursor visitCursor = resolver.query(visitUri, VISIT_LOG_PROJECTION, null, null, null);
    try {//from   w  ww . j  av a 2  s.  c o  m
        if (visitCursor != null && visitCursor.moveToFirst()) {
            long placeId = visitCursor.getLong(PLACE_ID_INDEX);
            long enter = visitCursor.getLong(ENTER_INDEX);
            long exit = visitCursor.getLong(EXIT_INDEX);
            int type = visitCursor.getInt(TYPE);
            String extra1 = visitCursor.getString(EXTRA1_INDEX);
            String extra2 = visitCursor.getString(EXTRA2_INDEX);

            MyLog.d(LociConfig.D.UI.DEBUG, TAG,
                    String.format("[updateData] placeId=%d enter=%s exit=%s type=%d extra1=%s extra2=%s",
                            placeId, MyDateUtils.getTimeFormatLong(enter), MyDateUtils.getTimeFormatLong(exit),
                            type, extra1, extra2));

            // Place name
            String place_name = "";
            int place_state = 0;

            if (placeId > 0) {
                String placeSelection = Places._ID + "=" + placeId;
                Uri placeUri = ContentUris.withAppendedId(Places.CONTENT_URI, placeId);
                Cursor placeCursor = resolver.query(placeUri, PLACE_PROJECTION, placeSelection, null, null);

                if (placeCursor != null && placeCursor.moveToFirst()) {
                    place_name = placeCursor.getString(PLACE_NAME_INDEX);
                    place_state = placeCursor.getInt(PLACE_STATE_INDEX);
                    placeCursor.close();
                } else {
                    place_name = "Unknown";
                }
            } else {
                place_name = "Unknown";
            }
            mPlaceName.setText(place_name);

            // Pull out string in format [relative], [date]
            CharSequence dateClause = DateUtils.formatDateRange(this, enter, enter, DateUtils.FORMAT_SHOW_TIME
                    | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_SHOW_YEAR);

            mVisitTime.setText(dateClause);

            // Set the duration
            mVisitDuration.setText(formatDuration((exit - enter) / 1000));

            switch (type) {
            case Visits.TYPE_GPS:
                mPlaceTypeIcon.setImageResource(R.drawable.icon_satellite);
                break;
            case Visits.TYPE_WIFI:
                mPlaceTypeIcon.setImageResource(R.drawable.icon_wifi);
                break;
            }

            List<ViewEntry> actions = new ArrayList<ViewEntry>();

            // View place
            Intent viewPlaceIntent = new Intent(Intent.ACTION_VIEW,
                    ContentUris.withAppendedId(Places.CONTENT_URI, placeId));
            String placeViewLabel = "";

            MyLog.d(LociConfig.D.UI.DEBUG, TAG,
                    String.format("[updateData] placename=%s placestate=%d", place_name, place_state));

            switch (place_state) {
            case Places.STATE_SUGGESTED:
                placeViewLabel = "Handle Suggested Place";
                break;
            case Places.STATE_REGISTERED:
                placeViewLabel = "View " + place_name;
                break;
            default:
                placeViewLabel = null;//place_name + " state " + place_state;
            }

            if (placeViewLabel != null) {
                ViewEntry entry = new ViewEntry(LIST_ACTION_VIEW_PLACE, R.drawable.sym_action_map,
                        placeViewLabel, null, null);
                entry.intent = viewPlaceIntent;
                actions.add(entry);
            }

            // View Wifi APs
            if (type == Visits.TYPE_WIFI && extra1 != null) {

                LociWifiFingerprint wifi;
                String apsAbstract = "Not available";

                try {
                    wifi = new LociWifiFingerprint(extra1);
                    apsAbstract = wifi.getWifiInfoSubstring(5);
                    ViewEntry wifiEntry = new ViewEntry(LIST_ACTION_VIEW_WIFIS, R.drawable.ic_settings_wireless,
                            "View Wi-Fi APs", apsAbstract, null);
                    wifiEntry.extra_string = extra1;

                    actions.add(wifiEntry);
                } catch (JSONException e) {
                    MyLog.e(LociConfig.D.JSON, TAG, "wifi json failed : " + extra1);
                    e.printStackTrace();
                }
            }

            // Additional Actions
            if (placeId > 0) {
                if (place_state == Places.STATE_REGISTERED || place_state == Places.STATE_BLOCKED) {
                    if (type == Visits.TYPE_WIFI && extra1 != null) {
                        ViewEntry entry = new ViewEntry(LIST_ACTION_CHANGE_PLACE,
                                android.R.drawable.ic_menu_edit, "Change Place", null, null);
                        entry.intent = new Intent(Intents.UI.ACTION_INSERT);
                        entry.intent.putExtra(Intents.UI.LIST_ORDER_EXTRA_KEY,
                                PlacesList.LIST_ORDER_TYPE_WIFI_SIMILARITY);
                        entry.intent.putExtra(Intents.UI.LIST_ORDER_EXTRA_WIFI_KEY, extra1);
                        entry.intent.putExtra(Intents.UI.LIST_ORDER_EXTRA_WIFI_TIME_KEY, String.valueOf(enter));
                        entry.intent.putExtra(Intents.UI.PLACE_ENTRY_TYPE_EXTRA_KEY,
                                Places.ENTRY_WIFI_OVERWRITE_WRONG_RECOGNITION);
                        actions.add(entry);
                    }
                }
            } else {
                ViewEntry entry = new ViewEntry(LIST_ACTION_ADD_PLACE, R.drawable.sym_action_add, "Add Place",
                        null, null);
                entry.intent = new Intent(Intents.UI.ACTION_INSERT);
                entry.intent.putExtra(Intents.UI.LIST_ORDER_EXTRA_KEY,
                        PlacesList.LIST_ORDER_TYPE_WIFI_SIMILARITY);
                entry.intent.putExtra(Intents.UI.LIST_ORDER_EXTRA_WIFI_KEY, extra1);
                entry.intent.putExtra(Intents.UI.LIST_ORDER_EXTRA_WIFI_TIME_KEY, String.valueOf(enter));
                entry.intent.putExtra(Intents.UI.PLACE_ENTRY_TYPE_EXTRA_KEY, Places.ENTRY_WIFI_USE_SHORT_VISIT);
                actions.add(entry);
            }

            // View Recognition Results
            //Log.d(TAG, "recog: " + extra2);
            if (extra2 != null && !TextUtils.isEmpty(extra2)) {
                ViewEntry recogEntry = new ViewEntry(LIST_ACTION_VIEW_RECOGNITION,
                        R.drawable.ic_clock_strip_desk_clock, "View Recogntion Results", "", null);
                recogEntry.extra_string = extra2;
                actions.add(recogEntry);
            }

            ViewAdapter adapter = new ViewAdapter(this, actions);
            setListAdapter(adapter);

            //Log.d(TAG, String.format("placeId=%d enter=%s exit=%s", placeId, MyDateUtils.getDateFormatLong(enter), MyDateUtils.getDateFormatLong(exit)));
            //Log.d(TAG, String.format("extra1=%s", extra1));
            //Log.d(TAG, String.format("extra2=%s", extra2));
        }

    } finally {
        if (visitCursor != null) {
            visitCursor.close();
        }
    }
}

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

private void refreshUI(Cursor entryCursor) {
    if (entryCursor != null) {
        String feedTitle = entryCursor.isNull(mFeedNamePos) ? entryCursor.getString(mFeedUrlPos)
                : entryCursor.getString(mFeedNamePos);
        BaseActivity activity = (BaseActivity) getActivity();
        activity.setTitle(feedTitle);/*from   w ww  .ja  v  a  2 s .c  o m*/

        mFavorite = entryCursor.getInt(mIsFavoritePos) == 1;
        activity.invalidateOptionsMenu();

        // Listen the mobilizing task
        if (FetcherService.hasMobilizationTask(mEntriesIds[mCurrentPagerPos])) {
            showSwipeProgress();

            // If the service is not started, start it here to avoid an infinite loading
            if (!PrefUtils.getBoolean(PrefUtils.IS_REFRESHING, false)) {
                MainApplication.getContext()
                        .startService(new Intent(MainApplication.getContext(), FetcherService.class)
                                .setAction(FetcherService.ACTION_MOBILIZE_FEEDS));
            }
        } else {
            hideSwipeProgress();
        }

        // Mark the article as read
        if (entryCursor.getInt(mIsReadPos) != 1) {
            final Uri uri = ContentUris.withAppendedId(mBaseUri, mEntriesIds[mCurrentPagerPos]);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    ContentResolver cr = MainApplication.getContext().getContentResolver();
                    cr.update(uri, FeedData.getReadContentValues(), null, null);

                    // Update the cursor
                    Cursor updatedCursor = cr.query(uri, null, null, null, null);
                    updatedCursor.moveToFirst();
                    mEntryPagerAdapter.setUpdatedCursor(mCurrentPagerPos, updatedCursor);
                }
            }).start();
        }
    }
}

From source file:com.google.samples.apps.iosched.service.SessionAlarmService.java

private void notifySession(final long sessionStart, final long alarmOffset) {
    long currentTime = UIUtils.getCurrentTime(this);
    final long intervalEnd = sessionStart + MILLI_TEN_MINUTES;
    LOGD(TAG, "Considering notifying for time interval.");
    LOGD(TAG, "    Interval start: " + sessionStart + "=" + (new Date(sessionStart)).toString());
    LOGD(TAG, "    Interval end: " + intervalEnd + "=" + (new Date(intervalEnd)).toString());
    LOGD(TAG, "    Current time is: " + currentTime + "=" + (new Date(currentTime)).toString());
    if (sessionStart < currentTime) {
        LOGD(TAG, "Skipping session notification (too late -- time interval already started)");
        return;//  w  w  w .j  a  v  a2  s  .c  o m
    }

    if (!SettingsUtils.shouldShowSessionReminders(this)) {
        // skip if disabled in settings
        LOGD(TAG, "Skipping session notification for sessions. Disabled in settings.");
        return;
    }

    // Avoid repeated notifications.
    if (alarmOffset == UNDEFINED_ALARM_OFFSET && UIUtils.isNotificationFiredForBlock(this,
            ScheduleContract.Blocks.generateBlockId(sessionStart, intervalEnd))) {
        LOGD(TAG, "Skipping session notification (already notified)");
        return;
    }

    final ContentResolver cr = getContentResolver();

    LOGD(TAG, "Looking for sessions in interval " + sessionStart + " - " + intervalEnd);
    Cursor c = null;
    try {
        c = cr.query(ScheduleContract.Sessions.CONTENT_MY_SCHEDULE_URI, SessionDetailQuery.PROJECTION,
                ScheduleContract.Sessions.STARTING_AT_TIME_INTERVAL_SELECTION,
                ScheduleContract.Sessions.buildAtTimeIntervalArgs(sessionStart, intervalEnd), null);
        int starredCount = c.getCount();
        LOGD(TAG, "# starred sessions in that interval: " + c.getCount());
        String singleSessionId = null;
        String singleSessionRoomId = null;
        ArrayList<String> starredSessionTitles = new ArrayList<String>();
        while (c.moveToNext()) {
            singleSessionId = c.getString(SessionDetailQuery.SESSION_ID);
            singleSessionRoomId = c.getString(SessionDetailQuery.ROOM_ID);
            starredSessionTitles.add(c.getString(SessionDetailQuery.SESSION_TITLE));
            LOGD(TAG, "-> Title: " + c.getString(SessionDetailQuery.SESSION_TITLE));
        }
        if (starredCount < 1) {
            return;
        }

        // Generates the pending intent which gets fired when the user taps on the notification.
        // NOTE: Use TaskStackBuilder to comply with Android's design guidelines
        // related to navigation from notifications.
        Intent baseIntent = new Intent(this, MyScheduleActivity.class);
        baseIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        TaskStackBuilder taskBuilder = TaskStackBuilder.create(this).addNextIntent(baseIntent);

        // For a single session, tapping the notification should open the session details (b/15350787)
        if (starredCount == 1) {
            taskBuilder.addNextIntent(
                    new Intent(Intent.ACTION_VIEW, ScheduleContract.Sessions.buildSessionUri(singleSessionId)));
        }

        PendingIntent pi = taskBuilder.getPendingIntent(0, PendingIntent.FLAG_CANCEL_CURRENT);

        final Resources res = getResources();
        String contentText;
        int minutesLeft = (int) (sessionStart - currentTime + 59000) / 60000;
        if (minutesLeft < 1) {
            minutesLeft = 1;
        }

        if (starredCount == 1) {
            contentText = res.getString(R.string.session_notification_text_1, minutesLeft);
        } else {
            contentText = res.getQuantityString(R.plurals.session_notification_text, starredCount - 1,
                    minutesLeft, starredCount - 1);
        }

        NotificationCompat.Builder notifBuilder = new NotificationCompat.Builder(this)
                .setContentTitle(starredSessionTitles.get(0)).setContentText(contentText)
                .setColor(getResources().getColor(R.color.theme_primary))
                .setTicker(res
                        .getQuantityString(R.plurals.session_notification_ticker, starredCount, starredCount))
                .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
                .setLights(SessionAlarmService.NOTIFICATION_ARGB_COLOR,
                        SessionAlarmService.NOTIFICATION_LED_ON_MS, SessionAlarmService.NOTIFICATION_LED_OFF_MS)
                .setSmallIcon(R.drawable.ic_stat_notification).setContentIntent(pi)
                .setPriority(Notification.PRIORITY_MAX).setAutoCancel(true);
        if (minutesLeft > 5) {
            notifBuilder.addAction(R.drawable.ic_alarm_holo_dark,
                    String.format(res.getString(R.string.snooze_x_min), 5),
                    createSnoozeIntent(sessionStart, intervalEnd, 5));
        }
        if (starredCount == 1 && SettingsUtils.isAttendeeAtVenue(this)) {
            notifBuilder.addAction(R.drawable.ic_map_holo_dark, res.getString(R.string.title_map),
                    createRoomMapIntent(singleSessionRoomId));
        }
        String bigContentTitle;
        if (starredCount == 1 && starredSessionTitles.size() > 0) {
            bigContentTitle = starredSessionTitles.get(0);
        } else {
            bigContentTitle = res.getQuantityString(R.plurals.session_notification_title, starredCount,
                    minutesLeft, starredCount);
        }
        NotificationCompat.InboxStyle richNotification = new NotificationCompat.InboxStyle(notifBuilder)
                .setBigContentTitle(bigContentTitle);

        // Adds starred sessions starting at this time block to the notification.
        for (int i = 0; i < starredCount; i++) {
            richNotification.addLine(starredSessionTitles.get(i));
        }
        NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        LOGD(TAG, "Now showing notification.");
        nm.notify(NOTIFICATION_ID, richNotification.build());
    } finally {
        if (c != null) {
            try {
                c.close();
            } catch (Exception ignored) {
            }
        }
    }
}

From source file:com.cttapp.bby.mytlc.layer8apps.CalendarHandler.java

private ArrayList<Shift> checkForDuplicates(ArrayList<Shift> newShifts) {
    Preferences pf = new Preferences(this);
    ArrayList<String> oldShifts = pf.getSavedShifts();

    ContentResolver cr = getContentResolver();

    for (String id : oldShifts) {
        Cursor cursor = cr.query(getEventsUri(), new String[] { "dtstart", "dtend" },
                "CALENDAR_ID = " + calID + " AND _ID = " + id, null, null);

        if (!cursor.moveToFirst()) {
            continue;
        }//w  ww  . jav  a 2 s.  c om

        do {
            Calendar now = Calendar.getInstance();

            Calendar startTime = Calendar.getInstance();
            startTime.setTimeInMillis(cursor.getLong(0));

            Calendar endTime = Calendar.getInstance();
            endTime.setTimeInMillis(cursor.getLong(1));

            if (endTime.compareTo(now) == -1) {
                deleteShift(id);
                continue;
            }

            boolean shiftFound = false;

            for (Shift shift : newShifts) {
                if (shift.getStartDate().get(Calendar.HOUR_OF_DAY) == startTime.get(Calendar.HOUR_OF_DAY)
                        && shift.getEndDate().get(Calendar.MINUTE) == shift.getEndDate().get(Calendar.MINUTE)) {
                    newShifts.remove(shift);
                    shiftFound = true;
                    break;
                }
            }

            if (!shiftFound) {
                cr.delete(getEventsUri(), "CALENDAR_ID = " + calID + " AND _ID = " + String.valueOf(id), null);
            }
        } while (cursor.moveToNext());
    }
    return newShifts;
}

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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (mEntriesIds != null) {
        Activity activity = getActivity();

        switch (item.getItemId()) {
        case R.id.menu_star: {
            mFavorite = !mFavorite;//from   w  w  w .  j  a v  a  2  s . c o m

            if (mFavorite) {
                item.setTitle(R.string.menu_unstar).setIcon(R.drawable.rating_important);
            } else {
                item.setTitle(R.string.menu_star).setIcon(R.drawable.rating_not_important);
            }

            final Uri uri = ContentUris.withAppendedId(mBaseUri, mEntriesIds[mCurrentPagerPos]);
            new Thread() {
                @Override
                public void run() {
                    ContentValues values = new ContentValues();
                    values.put(EntryColumns.IS_FAVORITE, mFavorite ? 1 : 0);
                    ContentResolver cr = MainApplication.getContext().getContentResolver();
                    cr.update(uri, values, null, null);

                    // Update the cursor
                    Cursor updatedCursor = cr.query(uri, null, null, null, null);
                    updatedCursor.moveToFirst();
                    mEntryPagerAdapter.setUpdatedCursor(mCurrentPagerPos, updatedCursor);
                }
            }.start();
            break;
        }
        case R.id.menu_share: {
            Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos);
            if (cursor != null) {
                String link = cursor.getString(mLinkPos);
                if (link != null) {
                    String title = cursor.getString(mTitlePos);
                    startActivity(Intent.createChooser(
                            new Intent(Intent.ACTION_SEND).putExtra(Intent.EXTRA_SUBJECT, title)
                                    .putExtra(Intent.EXTRA_TEXT, link).setType(Constants.MIMETYPE_TEXT_PLAIN),
                            getString(R.string.menu_share)));
                }
            }
            break;
        }
        case R.id.menu_full_screen: {
            setImmersiveFullScreen(true);
            break;
        }
        case R.id.menu_copy_clipboard: {
            Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos);
            String link = cursor.getString(mLinkPos);
            ClipboardManager clipboard = (ClipboardManager) activity
                    .getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData clip = ClipData.newPlainText("Copied Text", link);
            clipboard.setPrimaryClip(clip);

            UiUtils.showMessage(getActivity(), R.string.copied_clipboard);
            break;
        }
        case R.id.menu_mark_as_unread: {
            final Uri uri = ContentUris.withAppendedId(mBaseUri, mEntriesIds[mCurrentPagerPos]);
            new Thread() {
                @Override
                public void run() {
                    ContentResolver cr = MainApplication.getContext().getContentResolver();
                    cr.update(uri, FeedData.getUnreadContentValues(), null, null);
                }
            }.start();
            activity.finish();
            break;
        }
        }
    }

    return true;
}

From source file:com.phonegap.ContactAccessorSdk3_4.java

/**
 * Create a ContactOrganization JSONArray
 * @param cr database access object/*from  w  w w  .  ja v  a  2  s .co  m*/
 * @param contactId the ID to search the database for
 * @return a JSONArray representing a set of ContactOrganization
 */
private JSONArray organizationQuery(ContentResolver cr, String contactId) {
    String orgWhere = ContactMethods.PERSON_ID + " = ?";
    String[] orgWhereParams = new String[] { contactId };
    Cursor cursor = cr.query(Organizations.CONTENT_URI, null, orgWhere, orgWhereParams, null);
    JSONArray organizations = new JSONArray();
    JSONObject organization;
    while (cursor.moveToNext()) {
        organization = new JSONObject();
        try {
            organization.put("id", cursor.getString(cursor.getColumnIndex(Organizations._ID)));
            organization.put("name", cursor.getString(cursor.getColumnIndex(Organizations.COMPANY)));
            organization.put("title", cursor.getString(cursor.getColumnIndex(Organizations.TITLE)));
            // organization.put("department", cursor.getString(cursor.getColumnIndex(Organizations)));
            organizations.put(organization);
        } catch (JSONException e) {
            Log.e(LOG_TAG, e.getMessage(), e);
        }
    }
    return organizations;
}

From source file:com.razza.apps.iosched.service.SessionAlarmService.java

private void notifySession(final long sessionStart, final long alarmOffset) {
    long currentTime = UIUtils.getCurrentTime(this);
    final long intervalEnd = sessionStart + MILLI_TEN_MINUTES;
    LogUtils.LOGD(TAG, "Considering notifying for time interval.");
    LogUtils.LOGD(TAG, "    Interval start: " + sessionStart + "=" + (new Date(sessionStart)).toString());
    LogUtils.LOGD(TAG, "    Interval end: " + intervalEnd + "=" + (new Date(intervalEnd)).toString());
    LogUtils.LOGD(TAG, "    Current time is: " + currentTime + "=" + (new Date(currentTime)).toString());
    if (sessionStart < currentTime) {
        LogUtils.LOGD(TAG, "Skipping session notification (too late -- time interval already started)");
        return;/* ww  w  .  j a  v  a 2 s.c  o  m*/
    }

    if (!SettingsUtils.shouldShowSessionReminders(this)) {
        // skip if disabled in settings
        LogUtils.LOGD(TAG, "Skipping session notification for sessions. Disabled in settings.");
        return;
    }

    // Avoid repeated notifications.
    if (alarmOffset == UNDEFINED_ALARM_OFFSET && UIUtils.isNotificationFiredForBlock(this,
            ScheduleContract.Blocks.generateBlockId(sessionStart, intervalEnd))) {
        LogUtils.LOGD(TAG, "Skipping session notification (already notified)");
        return;
    }

    final ContentResolver cr = getContentResolver();

    LogUtils.LOGD(TAG, "Looking for sessions in interval " + sessionStart + " - " + intervalEnd);
    Cursor c = null;
    try {
        c = cr.query(ScheduleContract.Sessions.CONTENT_MY_SCHEDULE_URI, SessionDetailQuery.PROJECTION,
                ScheduleContract.Sessions.STARTING_AT_TIME_INTERVAL_SELECTION,
                ScheduleContract.Sessions.buildAtTimeIntervalArgs(sessionStart, intervalEnd), null);
        int starredCount = c.getCount();
        LogUtils.LOGD(TAG, "# starred sessions in that interval: " + c.getCount());
        String singleSessionId = null;
        String singleSessionRoomId = null;
        ArrayList<String> starredSessionTitles = new ArrayList<String>();
        while (c.moveToNext()) {
            singleSessionId = c.getString(SessionDetailQuery.SESSION_ID);
            singleSessionRoomId = c.getString(SessionDetailQuery.ROOM_ID);
            starredSessionTitles.add(c.getString(SessionDetailQuery.SESSION_TITLE));
            LogUtils.LOGD(TAG, "-> Title: " + c.getString(SessionDetailQuery.SESSION_TITLE));
        }
        if (starredCount < 1) {
            return;
        }

        // Generates the pending intent which gets fired when the user taps on the notification.
        // NOTE: Use TaskStackBuilder to comply with Android's design guidelines
        // related to navigation from notifications.
        Intent baseIntent = new Intent(this, MyScheduleActivity.class);
        baseIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        TaskStackBuilder taskBuilder = TaskStackBuilder.create(this).addNextIntent(baseIntent);

        // For a single session, tapping the notification should open the session details (b/15350787)
        if (starredCount == 1) {
            taskBuilder.addNextIntent(
                    new Intent(Intent.ACTION_VIEW, ScheduleContract.Sessions.buildSessionUri(singleSessionId)));
        }

        PendingIntent pi = taskBuilder.getPendingIntent(0, PendingIntent.FLAG_CANCEL_CURRENT);

        final Resources res = getResources();
        String contentText;
        int minutesLeft = (int) (sessionStart - currentTime + 59000) / 60000;
        if (minutesLeft < 1) {
            minutesLeft = 1;
        }

        if (starredCount == 1) {
            contentText = res.getString(R.string.session_notification_text_1, minutesLeft);
        } else {
            contentText = res.getQuantityString(R.plurals.session_notification_text, starredCount - 1,
                    minutesLeft, starredCount - 1);
        }

        NotificationCompat.Builder notifBuilder = new NotificationCompat.Builder(this)
                .setContentTitle(starredSessionTitles.get(0)).setContentText(contentText)
                .setColor(getResources().getColor(R.color.theme_primary))
                .setTicker(res
                        .getQuantityString(R.plurals.session_notification_ticker, starredCount, starredCount))
                .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
                .setLights(SessionAlarmService.NOTIFICATION_ARGB_COLOR,
                        SessionAlarmService.NOTIFICATION_LED_ON_MS, SessionAlarmService.NOTIFICATION_LED_OFF_MS)
                .setSmallIcon(R.drawable.ic_stat_notification).setContentIntent(pi)
                .setPriority(Notification.PRIORITY_MAX).setAutoCancel(true);
        if (minutesLeft > 5) {
            notifBuilder.addAction(R.drawable.ic_alarm_holo_dark,
                    String.format(res.getString(R.string.snooze_x_min), 5),
                    createSnoozeIntent(sessionStart, intervalEnd, 5));
        }
        if (starredCount == 1 && SettingsUtils.isAttendeeAtVenue(this)) {
            notifBuilder.addAction(R.drawable.ic_map_holo_dark, res.getString(R.string.title_map),
                    createRoomMapIntent(singleSessionRoomId));
        }
        String bigContentTitle;
        if (starredCount == 1 && starredSessionTitles.size() > 0) {
            bigContentTitle = starredSessionTitles.get(0);
        } else {
            bigContentTitle = res.getQuantityString(R.plurals.session_notification_title, starredCount,
                    minutesLeft, starredCount);
        }
        NotificationCompat.InboxStyle richNotification = new NotificationCompat.InboxStyle(notifBuilder)
                .setBigContentTitle(bigContentTitle);

        // Adds starred sessions starting at this time block to the notification.
        for (int i = 0; i < starredCount; i++) {
            richNotification.addLine(starredSessionTitles.get(i));
        }
        NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        LogUtils.LOGD(TAG, "Now showing notification.");
        nm.notify(NOTIFICATION_ID, richNotification.build());
    } finally {
        if (c != null) {
            try {
                c.close();
            } catch (Exception ignored) {
            }
        }
    }
}

From source file:eu.codeplumbers.cosi.services.CosiContactService.java

private void readContactDatabase() {
    //Fetches the complete call log in descending order. i.e recent calls appears first.
    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
        ContentResolver cr = getContentResolver();
        Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);

        // // TODO: 11/11/16 remove before release
        new Delete().from(ContactDataPoint.class).execute();
        new Delete().from(Contact.class).execute();

        if (cur.getCount() > 0) {
            int cnt = 0, total = cur.getCount();
            while (cur.moveToNext()) {
                EventBus.getDefault().post(new ContactSyncEvent(SYNC_MESSAGE,
                        "Reading local contacts " + (cnt + 1) + "/" + total + "..."));

                String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
                String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                String photo = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.PHOTO_THUMBNAIL_URI));
                System.out.println("name : " + name + ", ID : " + id);

                //Contact contact = Contact.getByName(name);

                //if (contact == null) {
                Contact contact = new Contact();
                contact.setN(name);//from  w  ww .  j a v a 2 s  .c  o m
                contact.setRevision(DateUtils.formatDate(new Date().getTime()));
                contact.setRemoteId("");
                contact.setTags(new JSONArray().toString());

                contact.setFn(name);
                if (photo != null) {
                    contact.setPhotoBase64(FileUtils.uriToBase64(this, photo));
                } else {
                    contact.setPhotoBase64("");
                }
                //} else {
                if ((contact.getPhotoBase64() == null || contact.getPhotoBase64().equalsIgnoreCase(""))
                        && photo != null) {
                    contact.setPhotoBase64(FileUtils.uriToBase64(this, photo));
                }
                //}

                contact.setSystemId(id);
                contact.setDeviceId(contact.getRemoteId().isEmpty() ? Device.registeredDevice().getLogin()
                        : contact.getDeviceId());
                contact.save();

                if (Integer.parseInt(
                        cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                    // get the phone number
                    Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { id },
                            null);
                    while (pCur.moveToNext()) {
                        String phone = pCur
                                .getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        System.out.println("phone " + phone);
                        if (!phone.isEmpty()) {
                            ContactDataPoint contactDataPoint = ContactDataPoint.getByValue(contact, phone);
                            if (contactDataPoint == null) {
                                contactDataPoint = new ContactDataPoint();
                                contactDataPoint.setPref(false);
                                contactDataPoint.setType("tel");
                                contactDataPoint.setValue(phone);
                                contactDataPoint.setName("tel");
                                contactDataPoint.setContact(contact);
                                contactDataPoint.save();
                            }
                        }
                    }
                    pCur.close();

                }
                // get email and type

                Cursor emailCur = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
                        ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", new String[] { id }, null);
                while (emailCur.moveToNext()) {
                    // This would allow you get several email addresses
                    // if the email addresses were stored in an array
                    String email = emailCur
                            .getString(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
                    String emailType = emailCur
                            .getString(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));

                    System.out.println("Email " + email + " Email Type : " + emailType);

                    if (!email.isEmpty()) {
                        ContactDataPoint contactDataPoint = ContactDataPoint.getByValue(contact, email);
                        if (contactDataPoint == null) {
                            contactDataPoint = new ContactDataPoint();
                            contactDataPoint.setPref(false);
                            contactDataPoint.setType(emailType);
                            contactDataPoint.setValue(email);
                            contactDataPoint.setName("email");
                            contactDataPoint.setContact(contact);
                            contactDataPoint.save();
                        }
                    }
                }
                emailCur.close();

                // Get note.......
                String noteWhere = ContactsContract.Data.CONTACT_ID + " = ? AND "
                        + ContactsContract.Data.MIMETYPE + " = ?";
                String[] noteWhereParams = new String[] { id,
                        ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE };
                Cursor noteCur = cr.query(ContactsContract.Data.CONTENT_URI, null, noteWhere, noteWhereParams,
                        null);
                if (noteCur.moveToFirst()) {
                    String note = noteCur
                            .getString(noteCur.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE));
                    System.out.println("Note " + note);

                    if (!note.isEmpty()) {
                        ContactDataPoint contactDataPoint = ContactDataPoint.getByValue(contact, note);
                        if (contactDataPoint == null) {
                            contactDataPoint = new ContactDataPoint();
                            contactDataPoint.setPref(false);
                            contactDataPoint.setType("note");
                            contactDataPoint.setValue(note);
                            contactDataPoint.setName("note");
                            contactDataPoint.setContact(contact);
                            contactDataPoint.save();
                        }
                    }
                }
                noteCur.close();

                //Get Postal Address....

                String addrWhere = ContactsContract.Data.CONTACT_ID + " = ? AND "
                        + ContactsContract.Data.MIMETYPE + " = ?";
                String[] addrWhereParams = new String[] { id,
                        ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE };
                Cursor addrCur = cr.query(ContactsContract.Data.CONTENT_URI, null, null, null, null);
                while (addrCur.moveToNext()) {
                    String poBox = addrCur.getString(
                            addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POBOX));
                    String street = addrCur.getString(
                            addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));
                    String city = addrCur.getString(
                            addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));
                    String state = addrCur.getString(
                            addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION));
                    String postalCode = addrCur.getString(
                            addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE));
                    String country = addrCur.getString(
                            addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY));
                    String type = addrCur.getString(
                            addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.TYPE));

                }
                addrCur.close();

                // Get Instant Messenger.........
                String imWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE
                        + " = ?";
                String[] imWhereParams = new String[] { id,
                        ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE };
                Cursor imCur = cr.query(ContactsContract.Data.CONTENT_URI, null, imWhere, imWhereParams, null);
                if (imCur.moveToFirst()) {
                    String imName = imCur
                            .getString(imCur.getColumnIndex(ContactsContract.CommonDataKinds.Im.DATA));
                    String imType;
                    imType = imCur.getString(imCur.getColumnIndex(ContactsContract.CommonDataKinds.Im.TYPE));

                    if (!imName.isEmpty()) {
                        ContactDataPoint contactDataPoint = ContactDataPoint.getByValue(contact, imName);
                        if (contactDataPoint == null) {
                            contactDataPoint = new ContactDataPoint();
                            contactDataPoint.setPref(false);
                            contactDataPoint.setType(imType);
                            contactDataPoint.setValue(imName);
                            contactDataPoint.setName("chat");
                            contactDataPoint.setContact(contact);
                            contactDataPoint.save();
                        }
                    }

                }
                imCur.close();

                // Get Organizations
                String orgWhere = ContactsContract.Data.CONTACT_ID + " = ? AND "
                        + ContactsContract.Data.MIMETYPE + " = ?";
                String[] orgWhereParams = new String[] { id,
                        ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE };
                Cursor orgCur = cr.query(ContactsContract.Data.CONTENT_URI, null, orgWhere, orgWhereParams,
                        null);
                if (orgCur.moveToFirst()) {
                    String orgName = orgCur.getString(
                            orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.DATA));
                    String title = orgCur.getString(
                            orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.TITLE));
                }
                orgCur.close();

                cnt++;
            }
        }

    } else {
        EventBus.getDefault()
                .post(new ContactSyncEvent(SERVICE_ERROR, getString(R.string.permission_denied_contacts)));
    }
}