Example usage for android.database Cursor moveToPosition

List of usage examples for android.database Cursor moveToPosition

Introduction

In this page you can find the example usage for android.database Cursor moveToPosition.

Prototype

boolean moveToPosition(int position);

Source Link

Document

Move the cursor to an absolute position.

Usage

From source file:com.android.calendar.selectcalendars.SelectCalendarsSimpleAdapter.java

private void initData(Cursor c) {
    if (mCursor != null && c != mCursor) {
        mCursor.close();/* ww  w  . j  a va 2 s .  c om*/
    }
    if (c == null) {
        mCursor = c;
        mRowCount = 0;
        mData = null;
        return;
    }
    // TODO create a broadcast listener for ACTION_PROVIDER_CHANGED to update the cursor
    mCursor = c;
    mIdColumn = c.getColumnIndexOrThrow(Calendars._ID);
    mNameColumn = c.getColumnIndexOrThrow(Calendars.CALENDAR_DISPLAY_NAME);
    mColorColumn = c.getColumnIndexOrThrow(Calendars.CALENDAR_COLOR);
    mVisibleColumn = c.getColumnIndexOrThrow(Calendars.VISIBLE);
    mOwnerAccountColumn = c.getColumnIndexOrThrow(Calendars.OWNER_ACCOUNT);
    mAccountNameColumn = c.getColumnIndexOrThrow(Calendars.ACCOUNT_NAME);
    mAccountTypeColumn = c.getColumnIndexOrThrow(Calendars.ACCOUNT_TYPE);

    mRowCount = c.getCount();
    mData = new CalendarRow[(c.getCount())];
    c.moveToPosition(-1);
    int p = 0;
    while (c.moveToNext()) {
        mData[p] = new CalendarRow();
        mData[p].id = c.getLong(mIdColumn);
        mData[p].displayName = c.getString(mNameColumn);
        mData[p].color = c.getInt(mColorColumn);
        mData[p].selected = c.getInt(mVisibleColumn) != 0;
        mData[p].ownerAccount = c.getString(mOwnerAccountColumn);
        mData[p].accountName = c.getString(mAccountNameColumn);
        mData[p].accountType = c.getString(mAccountTypeColumn);
        p++;
    }
}

From source file:com.battlelancer.seriesguide.service.NotificationService.java

private void onNotify(final Cursor upcomingEpisodes, List<Integer> notifyPositions, long latestAirtime) {
    final Context context = getApplicationContext();

    CharSequence tickerText;//ww  w  . ja  v a 2  s  .c om
    CharSequence contentTitle;
    CharSequence contentText;
    PendingIntent contentIntent;
    // base intent for task stack
    final Intent showsIntent = new Intent(context, ShowsActivity.class);
    showsIntent.putExtra(ShowsActivity.InitBundle.SELECTED_TAB, ShowsActivity.InitBundle.INDEX_TAB_UPCOMING);

    final int count = notifyPositions.size();
    if (count == 1) {
        // notify in detail about one episode
        Timber.d("Notifying about 1 new episode");
        upcomingEpisodes.moveToPosition(notifyPositions.get(0));

        final String showTitle = upcomingEpisodes.getString(NotificationQuery.SHOW_TITLE);
        tickerText = getString(R.string.upcoming_show, showTitle);
        contentTitle = showTitle + " "
                + Utils.getEpisodeNumber(this, upcomingEpisodes.getInt(NotificationQuery.SEASON),
                        upcomingEpisodes.getInt(NotificationQuery.NUMBER));

        // "8:00 PM on Network"
        final String releaseTime = TimeTools.formatToLocalReleaseTime(this, TimeTools.getEpisodeReleaseTime(
                this, upcomingEpisodes.getLong(NotificationQuery.EPISODE_FIRST_RELEASE_MS)));
        final String network = upcomingEpisodes.getString(NotificationQuery.NETWORK);
        contentText = getString(R.string.upcoming_show_detailed, releaseTime, network);

        Intent episodeDetailsIntent = new Intent(context, EpisodesActivity.class);
        episodeDetailsIntent.putExtra(EpisodesActivity.InitBundle.EPISODE_TVDBID,
                upcomingEpisodes.getInt(NotificationQuery._ID));
        episodeDetailsIntent.putExtra(KEY_EPISODE_CLEARED_TIME, latestAirtime);

        contentIntent = TaskStackBuilder.create(context).addNextIntent(showsIntent)
                .addNextIntent(episodeDetailsIntent)
                .getPendingIntent(REQUEST_CODE_SINGLE_EPISODE, PendingIntent.FLAG_CANCEL_CURRENT);
    } else {
        // notify about multiple episodes
        Timber.d("Notifying about " + count + " new episodes");
        tickerText = getString(R.string.upcoming_episodes);
        contentTitle = getString(R.string.upcoming_episodes_number, count);
        contentText = getString(R.string.upcoming_display);

        contentIntent = TaskStackBuilder.create(context)
                .addNextIntent(showsIntent.putExtra(KEY_EPISODE_CLEARED_TIME, latestAirtime))
                .getPendingIntent(REQUEST_CODE_MULTIPLE_EPISODES, PendingIntent.FLAG_CANCEL_CURRENT);
    }

    final NotificationCompat.Builder nb = new NotificationCompat.Builder(context);

    if (AndroidUtils.isJellyBeanOrHigher()) {
        Timber.d("Building rich notification (JB+)");
        // JELLY BEAN and above
        if (count == 1) {
            // single episode
            upcomingEpisodes.moveToPosition(notifyPositions.get(0));
            maybeSetPoster(context, nb, upcomingEpisodes.getString(NotificationQuery.POSTER));

            final String episodeTitle = upcomingEpisodes.getString(NotificationQuery.TITLE);
            final String episodeSummary = upcomingEpisodes.getString(NotificationQuery.OVERVIEW);

            final SpannableStringBuilder bigText = new SpannableStringBuilder();
            bigText.append(TextUtils.isEmpty(episodeTitle) ? "" : episodeTitle);
            bigText.setSpan(new StyleSpan(Typeface.BOLD), 0, bigText.length(), 0);
            bigText.append("\n");
            bigText.append(TextUtils.isEmpty(episodeSummary) ? "" : episodeSummary);

            nb.setStyle(new NotificationCompat.BigTextStyle().bigText(bigText).setSummaryText(contentText));

            // Action button to check in
            Intent checkInActionIntent = new Intent(context, QuickCheckInActivity.class);
            checkInActionIntent.putExtra(QuickCheckInActivity.InitBundle.EPISODE_TVDBID,
                    upcomingEpisodes.getInt(NotificationQuery._ID));
            checkInActionIntent
                    .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
            PendingIntent checkInIntent = PendingIntent.getActivity(context, REQUEST_CODE_ACTION_CHECKIN,
                    checkInActionIntent, PendingIntent.FLAG_CANCEL_CURRENT);
            nb.addAction(R.drawable.ic_action_checkin, getString(R.string.checkin), checkInIntent);
        } else {
            // multiple episodes
            NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();

            // display at most the first five
            for (int displayIndex = 0; displayIndex < Math.min(count, 5); displayIndex++) {
                if (!upcomingEpisodes.moveToPosition(notifyPositions.get(displayIndex))) {
                    // could not go to the desired position (testing just in case)
                    break;
                }

                final SpannableStringBuilder lineText = new SpannableStringBuilder();

                // show title
                String showTitle = upcomingEpisodes.getString(NotificationQuery.SHOW_TITLE);
                lineText.append(TextUtils.isEmpty(showTitle) ? "" : showTitle);
                lineText.setSpan(new StyleSpan(Typeface.BOLD), 0, lineText.length(), 0);

                lineText.append(" ");

                // "8:00 PM on Network"
                String releaseTime = TimeTools.formatToLocalReleaseTime(this, TimeTools.getEpisodeReleaseTime(
                        this, upcomingEpisodes.getLong(NotificationQuery.EPISODE_FIRST_RELEASE_MS)));
                String network = upcomingEpisodes.getString(NotificationQuery.NETWORK);
                lineText.append(getString(R.string.upcoming_show_detailed, releaseTime, network));

                inboxStyle.addLine(lineText);
            }

            // tell if we could not display all episodes
            if (count > 5) {
                inboxStyle.setSummaryText(getString(R.string.more, count - 5));
            }

            nb.setStyle(inboxStyle);
            nb.setContentInfo(String.valueOf(count));
        }
    } else {
        // ICS and below
        if (count == 1) {
            // single episode
            upcomingEpisodes.moveToPosition(notifyPositions.get(0));
            maybeSetPoster(context, nb, upcomingEpisodes.getString(NotificationQuery.POSTER));
        }
    }

    // notification sound
    final String ringtoneUri = NotificationSettings.getNotificationsRingtone(context);
    // If the string is empty, the user chose silent...
    if (ringtoneUri.length() != 0) {
        // ...otherwise set the specified ringtone
        Timber.d("Notification has sound");
        nb.setSound(Uri.parse(ringtoneUri));
    }
    // vibration
    if (NotificationSettings.isNotificationVibrating(context)) {
        Timber.d("Notification vibrates");
        nb.setVibrate(VIBRATION_PATTERN);
    }
    nb.setDefaults(Notification.DEFAULT_LIGHTS);
    nb.setWhen(System.currentTimeMillis());
    nb.setAutoCancel(true);
    nb.setTicker(tickerText);
    nb.setContentTitle(contentTitle);
    nb.setContentText(contentText);
    nb.setContentIntent(contentIntent);
    nb.setSmallIcon(R.drawable.ic_notification);
    nb.setColor(getResources().getColor(R.color.accent_primary));
    nb.setPriority(NotificationCompat.PRIORITY_DEFAULT);
    nb.setCategory(NotificationCompat.CATEGORY_EVENT);

    Timber.d("Setting delete intent with episode time: " + latestAirtime);
    Intent i = new Intent(this, NotificationService.class);
    i.putExtra(KEY_EPISODE_CLEARED_TIME, latestAirtime);
    PendingIntent deleteIntent = PendingIntent.getService(this, REQUEST_CODE_DELETE_INTENT, i,
            PendingIntent.FLAG_CANCEL_CURRENT);
    nb.setDeleteIntent(deleteIntent);

    // build the notification
    Notification notification = nb.build();

    // use string resource id, always unique within app
    final NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    nm.notify(R.string.upcoming_show, notification);
}

From source file:com.money.manager.ex.common.CategoryListFragment.java

public CategoryExpandableListAdapter getAdapter(Cursor data) {
    if (data == null)
        return null;

    mCategories.clear();//from w  w w  . j  a v  a  2  s .c o m
    mSubCategories.clear();
    mPositionToExpand.clear();
    // create core and fixed string filter to highlight
    Core core = new Core(getActivity().getApplicationContext());
    String filter = mCurFilter != null ? mCurFilter.replace("%", "") : "";

    int key = -1;
    List<QueryCategorySubCategory> listSubCategories = null;

    // reset cursor if getting back on the fragment.
    if (data.getPosition() > 0) {
        data.moveToPosition(Constants.NOT_SET);
    }

    while (data.moveToNext()) {
        if (key != data.getInt(data.getColumnIndex(QueryCategorySubCategory.CATEGID))) {
            // check if listCategories > 0
            if (mCategories.size() > 0 && listSubCategories != null) {
                mSubCategories.put(mCategories.get(mCategories.size() - 1), listSubCategories);
            }
            // update key
            key = data.getInt(data.getColumnIndex(QueryCategorySubCategory.CATEGID));

            // create instance category
            Category category = new Category();
            category.setId(data.getInt(data.getColumnIndex(QueryCategorySubCategory.CATEGID)));
            category.setName(core
                    .highlight(filter, data.getString(data.getColumnIndex(QueryCategorySubCategory.CATEGNAME)))
                    .toString());

            // add list
            mCategories.add(category);
            listSubCategories = new ArrayList<>();
        }

        if (data.getInt(data.getColumnIndex(QueryCategorySubCategory.SUBCATEGID)) != Constants.NOT_SET) {
            QueryCategorySubCategory subCategory = new QueryCategorySubCategory(getActivity());
            // subcategory
            subCategory.setSubCategId(data.getInt(data.getColumnIndex(QueryCategorySubCategory.SUBCATEGID)));
            subCategory.setSubcategoryName(core.highlight(filter,
                    data.getString(data.getColumnIndex(QueryCategorySubCategory.SUBCATEGNAME))));
            subCategory.setCategId(data.getInt(data.getColumnIndex(QueryCategorySubCategory.CATEGID)));
            subCategory.setCategName(core.highlight(filter,
                    data.getString(data.getColumnIndex(QueryCategorySubCategory.CATEGNAME))));
            // add to hashmap
            listSubCategories.add(subCategory);
            // check if expand group
            if (!TextUtils.isEmpty(filter)) {
                String normalizedText = Normalizer
                        .normalize(subCategory.getSubcategoryName(), Normalizer.Form.NFD)
                        .replaceAll("\\p{InCombiningDiacriticalMarks}+", "").toLowerCase();
                if ((normalizedText.indexOf(filter) >= 0)
                        && (!mPositionToExpand.contains(mCategories.size() - 1))) {
                    mPositionToExpand.add(mCategories.size() - 1);
                }
            }
        }
    }
    if (mCategories.size() > 0 && listSubCategories != null) {
        mSubCategories.put(mCategories.get(mCategories.size() - 1), listSubCategories);
    }

    boolean showSelector = mAction.equals(Intent.ACTION_PICK);
    CategoryExpandableListAdapter adapter = new CategoryExpandableListAdapter(getActivity(), mLayout,
            mCategories, mSubCategories, showSelector);
    adapter.setIdChildChecked(mIdGroupChecked, mIdChildChecked);
    return adapter;
}

From source file:com.nachiket.titan.LibraryActivity.java

@Override
public boolean onContextItemSelected(MenuItem item) {
    if (item.getGroupId() != 0)
        return super.onContextItemSelected(item);

    Intent intent = item.getIntent();// w  w  w .  j av  a2  s.  co  m

    switch (item.getItemId()) {
    case MENU_EXPAND:
        expand(intent);
        if (mDefaultAction == ACTION_LAST_USED && mLastAction != ACTION_EXPAND) {
            mLastAction = ACTION_EXPAND;
            updateHeaders();
        }
        break;
    case MENU_ENQUEUE:
        pickSongs(intent, ACTION_ENQUEUE);
        break;
    case MENU_PLAY:
        pickSongs(intent, ACTION_PLAY);
        break;
    case MENU_PLAY_ALL:
        pickSongs(intent, ACTION_PLAY_ALL);
        break;
    case MENU_ENQUEUE_ALL:
        pickSongs(intent, ACTION_ENQUEUE_ALL);
        break;
    case MENU_NEW_PLAYLIST: {
        NewPlaylistDialog dialog = new NewPlaylistDialog(this, null, R.string.create, intent);
        dialog.setDismissMessage(mHandler.obtainMessage(MSG_NEW_PLAYLIST, dialog));
        dialog.show();
        break;
    }
    case MENU_RENAME_PLAYLIST: {
        NewPlaylistDialog dialog = new NewPlaylistDialog(this, intent.getStringExtra("title"), R.string.rename,
                intent);
        dialog.setDismissMessage(mHandler.obtainMessage(MSG_RENAME_PLAYLIST, dialog));
        dialog.show();
        break;
    }
    case MENU_DELETE:
        mHandler.sendMessage(mHandler.obtainMessage(MSG_DELETE, intent));
        break;
    case MENU_ADD_TO_PLAYLIST: {
        SubMenu playlistMenu = item.getSubMenu();
        playlistMenu.add(0, MENU_NEW_PLAYLIST, 0, R.string.new_playlist).setIntent(intent);
        Cursor cursor = Playlist.queryPlaylists(getContentResolver());
        if (cursor != null) {
            for (int i = 0, count = cursor.getCount(); i != count; ++i) {
                cursor.moveToPosition(i);
                long id = cursor.getLong(0);
                String name = cursor.getString(1);
                Intent copy = new Intent(intent);
                copy.putExtra("playlist", id);
                copy.putExtra("playlistName", name);
                playlistMenu.add(0, MENU_SELECT_PLAYLIST, 0, name).setIntent(copy);
            }
            cursor.close();
        }
        break;
    }
    case MENU_SELECT_PLAYLIST:
        mHandler.sendMessage(mHandler.obtainMessage(MSG_ADD_TO_PLAYLIST, intent));
        break;
    case MENU_MORE_FROM_ARTIST: {
        String selection;
        if (intent.getIntExtra(LibraryAdapter.DATA_TYPE, -1) == MediaUtils.TYPE_ALBUM) {
            selection = "album_id=";
        } else {
            selection = "_id=";
        }
        selection += intent.getLongExtra(LibraryAdapter.DATA_ID, LibraryAdapter.INVALID_ID);
        setLimiter(MediaUtils.TYPE_ARTIST, selection);
        updateLimiterViews();
        break;
    }
    case MENU_MORE_FROM_ALBUM:
        setLimiter(MediaUtils.TYPE_ALBUM,
                "_id=" + intent.getLongExtra(LibraryAdapter.DATA_ID, LibraryAdapter.INVALID_ID));
        updateLimiterViews();
        break;
    }

    return true;
}

From source file:com.vishwa.pinit.MainActivity.java

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main_action_bar, menu);
    mMenu = menu;//from   w  w  w.  ja v  a  2  s .com
    mSearchMenuItem = menu.findItem(R.id.action_search);
    SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    mSearchView = (SearchView) mSearchMenuItem.getActionView();
    mSearchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
    mSearchView.setQueryHint("Search for locations...");

    mSearchView.setOnSuggestionListener(new OnSuggestionListener() {

        @Override
        public boolean onSuggestionSelect(int position) {
            return false;
        }

        @Override
        public boolean onSuggestionClick(int position) {
            CursorAdapter adapter = mSearchView.getSuggestionsAdapter();
            Cursor cursor = adapter.getCursor();
            if (cursor != null) {
                if (cursor.moveToPosition(position)) {
                    InputMethodManager imm = (InputMethodManager) getSystemService(
                            Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(mSearchView.getWindowToken(), 0);
                    mSearchMenuItem.collapseActionView();
                    String geolocation = cursor
                            .getString(cursor.getColumnIndex(SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID));
                    if (geolocation != null && !geolocation.isEmpty()) {
                        double latitude = Double.parseDouble(geolocation.split(",")[0]);
                        double longitude = Double.parseDouble(geolocation.split(",")[1]);
                        LatLng geopoint = new LatLng(latitude, longitude);
                        mMap.animateCamera(
                                CameraUpdateFactory.newCameraPosition(new CameraPosition(geopoint, 17, 0, 0)));
                    }
                }
            }
            return true;
        }
    });

    mSearchView.setOnQueryTextListener(new OnQueryTextListener() {

        @Override
        public boolean onQueryTextSubmit(String query) {
            CursorAdapter adapter = mSearchView.getSuggestionsAdapter();
            Cursor cursor = adapter.getCursor();
            if (cursor != null) {
                if (cursor.moveToFirst()) {
                    InputMethodManager imm = (InputMethodManager) getSystemService(
                            Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(mSearchView.getWindowToken(), 0);
                    mSearchMenuItem.collapseActionView();
                    String geolocation = cursor
                            .getString(cursor.getColumnIndex(SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID));
                    if (geolocation != null && !geolocation.isEmpty()) {
                        double latitude = Double.parseDouble(geolocation.split(",")[0]);
                        double longitude = Double.parseDouble(geolocation.split(",")[1]);
                        LatLng geopoint = new LatLng(latitude, longitude);
                        mMap.animateCamera(
                                CameraUpdateFactory.newCameraPosition(new CameraPosition(geopoint, 17, 0, 0)));
                    }
                }
            }
            return true;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            return false;
        }
    });

    if (!mHasInternet) {
        hideNonRefreshMenuItems();
    } else {
        showNonRefreshMenuItems();
    }
    return true;
}

From source file:com.bt.download.android.gui.Librarian.java

/**
 * Returns a list of Files.//from  w w w.  j  a v a 2  s .c o m
 * 
 * @param offset
 *            - from where (starting at 0)
 * @param pageSize
 *            - how many results
 * @param fetcher
 *            - An implementation of TableFetcher
 * @param sharedOnly
 *            - if true, retrieves only the fine grained shared files.
 *
 * @return List<FileDescriptor>
 */
private List<FileDescriptor> getFiles(int offset, int pageSize, TableFetcher fetcher, String where,
        String[] whereArgs, boolean sharedOnly) {
    List<FileDescriptor> result = new ArrayList<FileDescriptor>();

    Cursor c = null;
    Set<Integer> sharedIds = getSharedFiles(fetcher.getFileType());

    try {

        ContentResolver cr = context.getContentResolver();

        String[] columns = fetcher.getColumns();
        String sort = fetcher.getSortByExpression();

        c = cr.query(fetcher.getContentUri(), columns, where, whereArgs, sort);

        if (c == null || !c.moveToPosition(offset)) {
            return result;
        }

        fetcher.prepare(c);

        int count = 1;

        do {
            FileDescriptor fd = fetcher.fetch(c);

            fd.shared = sharedIds.contains(fd.id);

            if (sharedOnly && !fd.shared) {
                continue;
            }

            result.add(fd);

        } while (c.moveToNext() && count++ < pageSize);

    } catch (Throwable e) {
        Log.e(TAG, "General failure getting files", e);
    } finally {
        if (c != null) {
            c.close();
        }
    }

    return result;
}

From source file:com.android.messaging.datamodel.MessageNotificationState.java

/**
 * Check for failed messages and post notifications as needed.
 * TODO: Rewrite this as a NotificationState.
 *///from ww  w .j  a  v a2 s  . c  o m
public static void checkFailedMessages() {
    final DatabaseWrapper db = DataModel.get().getDatabase();

    final Cursor messageDataCursor = db.query(DatabaseHelper.MESSAGES_TABLE, MessageData.getProjection(),
            FailedMessageQuery.FAILED_MESSAGES_WHERE_CLAUSE, null /*selectionArgs*/, null /*groupBy*/,
            null /*having*/, FailedMessageQuery.FAILED_ORDER_BY);

    try {
        final Context context = Factory.get().getApplicationContext();
        final Resources resources = context.getResources();
        final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
        if (messageDataCursor != null) {
            final MessageData messageData = new MessageData();

            final HashSet<String> conversationsWithFailedMessages = new HashSet<String>();

            // track row ids in case we want to display something that requires this
            // information
            final ArrayList<Integer> failedMessages = new ArrayList<Integer>();

            int cursorPosition = -1;
            final long when = 0;

            messageDataCursor.moveToPosition(-1);
            while (messageDataCursor.moveToNext()) {
                messageData.bind(messageDataCursor);

                final String conversationId = messageData.getConversationId();
                if (DataModel.get().isNewMessageObservable(conversationId)) {
                    // Don't post a system notification for an observable conversation
                    // because we already show an angry red annotation in the conversation
                    // itself or in the conversation preview snippet.
                    continue;
                }

                cursorPosition = messageDataCursor.getPosition();
                failedMessages.add(cursorPosition);
                conversationsWithFailedMessages.add(conversationId);
            }

            if (LogUtil.isLoggable(TAG, LogUtil.DEBUG)) {
                LogUtil.d(TAG, "Found " + failedMessages.size() + " failed messages");
            }
            if (failedMessages.size() > 0) {
                final NotificationCompat.Builder builder = new NotificationCompat.Builder(context);

                CharSequence line1;
                CharSequence line2;
                final boolean isRichContent = false;
                ConversationIdSet conversationIds = null;
                PendingIntent destinationIntent;
                if (failedMessages.size() == 1) {
                    messageDataCursor.moveToPosition(cursorPosition);
                    messageData.bind(messageDataCursor);
                    final String conversationId = messageData.getConversationId();

                    // We have a single conversation, go directly to that conversation.
                    destinationIntent = UIIntents.get().getPendingIntentForConversationActivity(context,
                            conversationId, null /*draft*/);

                    conversationIds = ConversationIdSet.createSet(conversationId);

                    final String failedMessgeSnippet = messageData.getMessageText();
                    int failureStringId;
                    if (messageData.getStatus() == MessageData.BUGLE_STATUS_INCOMING_DOWNLOAD_FAILED) {
                        failureStringId = R.string.notification_download_failures_line1_singular;
                    } else {
                        failureStringId = R.string.notification_send_failures_line1_singular;
                    }
                    line1 = resources.getString(failureStringId);
                    line2 = failedMessgeSnippet;
                    // Set rich text for non-SMS messages or MMS push notification messages
                    // which we generate locally with rich text
                    // TODO- fix this
                    //                        if (messageData.isMmsInd()) {
                    //                            isRichContent = true;
                    //                        }
                } else {
                    // We have notifications for multiple conversation, go to the conversation
                    // list.
                    destinationIntent = UIIntents.get().getPendingIntentForConversationListActivity(context);

                    int line1StringId;
                    int line2PluralsId;
                    if (messageData.getStatus() == MessageData.BUGLE_STATUS_INCOMING_DOWNLOAD_FAILED) {
                        line1StringId = R.string.notification_download_failures_line1_plural;
                        line2PluralsId = R.plurals.notification_download_failures;
                    } else {
                        line1StringId = R.string.notification_send_failures_line1_plural;
                        line2PluralsId = R.plurals.notification_send_failures;
                    }
                    line1 = resources.getString(line1StringId);
                    line2 = resources.getQuantityString(line2PluralsId, conversationsWithFailedMessages.size(),
                            failedMessages.size(), conversationsWithFailedMessages.size());
                }
                line1 = applyWarningTextColor(context, line1);
                line2 = applyWarningTextColor(context, line2);

                final PendingIntent pendingIntentForDelete = UIIntents.get()
                        .getPendingIntentForClearingNotifications(context, BugleNotifications.UPDATE_ERRORS,
                                conversationIds, 0);

                builder.setContentTitle(line1).setTicker(line1)
                        .setWhen(when > 0 ? when : System.currentTimeMillis())
                        .setSmallIcon(R.drawable.ic_failed_light).setDeleteIntent(pendingIntentForDelete)
                        .setContentIntent(destinationIntent)
                        .setSound(UriUtil.getUriForResourceId(context, R.raw.message_failure));
                if (isRichContent && !TextUtils.isEmpty(line2)) {
                    final NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(builder);
                    if (line2 != null) {
                        inboxStyle.addLine(Html.fromHtml(line2.toString()));
                    }
                    builder.setStyle(inboxStyle);
                } else {
                    builder.setContentText(line2);
                }

                if (builder != null) {
                    notificationManager.notify(BugleNotifications
                            .buildNotificationTag(PendingIntentConstants.MSG_SEND_ERROR, null),
                            PendingIntentConstants.MSG_SEND_ERROR, builder.build());
                }
            } else {
                notificationManager.cancel(
                        BugleNotifications.buildNotificationTag(PendingIntentConstants.MSG_SEND_ERROR, null),
                        PendingIntentConstants.MSG_SEND_ERROR);
            }
        }
    } finally {
        if (messageDataCursor != null) {
            messageDataCursor.close();
        }
    }
}

From source file:com.ute.bihapi.wydarzeniatekstowe.thirdScreenActivities.ContactsListFragment.java

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    // This swaps the new cursor into the adapter.
    if (loader.getId() == ContactsQuery.QUERY_ID) {
        mAdapter.swapCursor(data);/*ww  w. j a  v a2  s.co m*/

        // If this is a two-pane layout and there is a search query then
        // there is some additional work to do around default selected
        // search item.
        if (!TextUtils.isEmpty(mSearchTerm) && mSearchQueryChanged) {
            // Selects the first item in results, unless this fragment has
            // been restored from a saved state (like orientation change)
            // in which case it selects the previously selected search item.
            if (data != null && data.moveToPosition(mPreviouslySelectedSearchItem)) {
                // Creates the content Uri for the previously selected contact by appending the
                // contact's ID to the Contacts table content Uri
                final Uri uri = Uri.withAppendedPath(Contacts.CONTENT_URI,
                        String.valueOf(data.getLong(ContactsQuery.ID)));
                mOnContactSelectedListener.onContactSelected(uri);
                getListView().setItemChecked(mPreviouslySelectedSearchItem, true);
            } else {
                // No results, clear selection.
                onSelectionCleared();
            }
            // Only restore from saved state one time. Next time fall back
            // to selecting first item. If the fragment state is saved again
            // then the currently selected item will once again be saved.
            mPreviouslySelectedSearchItem = 0;
            mSearchQueryChanged = false;
        }
    }
}

From source file:com.sagar.sunshine.ForecastFragment.java

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    mForecastAdapter.swapCursor(data);//from   ww w. j a  v  a  2s.co m
    updateEmptyView();
    if (data.getCount() == 0) {
        getActivity().supportStartPostponedEnterTransition();
    } else {
        mRecyclerView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                if (mRecyclerView.getChildCount() > 0) {
                    mRecyclerView.getViewTreeObserver().removeOnPreDrawListener(this);
                    int position = mForecastAdapter.getSelectedItemPosition();
                    if (position == RecyclerView.NO_POSITION && -1 != mInitialSelectedDate) {
                        Cursor data = mForecastAdapter.getCursor();
                        int count = data.getCount();
                        int dateColumn = data.getColumnIndex(WeatherContract.WeatherEntry.COLUMN_DATE);
                        for (int i = 0; i < count; i++) {
                            data.moveToPosition(i);
                            if (data.getLong(dateColumn) == mInitialSelectedDate) {
                                position = i;
                                break;
                            }
                        }
                    }
                    if (position == RecyclerView.NO_POSITION)
                        position = 0;
                    mRecyclerView.smoothScrollToPosition(position);
                    RecyclerView.ViewHolder vh = mRecyclerView.findViewHolderForAdapterPosition(position);
                    if (null != vh && mAutoSelectView) {
                        mForecastAdapter.selectView(vh);
                    }
                    if (mHoldForTransition) {
                        getActivity().supportStartPostponedEnterTransition();
                    }
                    return true;
                }
                return false;
            }
        });
    }

}

From source file:com.csipsimple.ui.favorites.FavAdapter.java

private void showDialogForGroupSelection(final Context context, final Long profileId, final String groupName) {
    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setTitle(R.string.set_android_group);
    final Cursor choiceCursor = ContactsWrapper.getInstance().getGroups(context);
    int selectedIndex = -1;
    if (choiceCursor != null) {
        if (choiceCursor.moveToFirst()) {
            int i = 0;
            int colIdx = choiceCursor.getColumnIndex(ContactsWrapper.FIELD_GROUP_NAME);
            do {//from   w  w w.j  a  v  a  2s  .  c o m
                String name = choiceCursor.getString(colIdx);
                if (!TextUtils.isEmpty(name) && name.equalsIgnoreCase(groupName)) {
                    selectedIndex = i;
                    break;
                }
                i++;
            } while (choiceCursor.moveToNext());
        }
    }
    builder.setSingleChoiceItems(choiceCursor, selectedIndex, ContactsWrapper.FIELD_GROUP_NAME,
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (choiceCursor != null) {
                        choiceCursor.moveToPosition(which);
                        String name = choiceCursor
                                .getString(choiceCursor.getColumnIndex(ContactsWrapper.FIELD_GROUP_NAME));
                        ContentValues cv = new ContentValues();
                        cv.put(SipProfile.FIELD_ANDROID_GROUP, name);
                        context.getContentResolver().update(
                                ContentUris.withAppendedId(SipProfile.ACCOUNT_ID_URI_BASE, profileId), cv, null,
                                null);
                        choiceCursor.close();
                    }
                    dialog.dismiss();
                }
            });

    builder.setCancelable(true);
    builder.setNeutralButton(R.string.cancel, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            if (choiceCursor != null) {
                choiceCursor.close();
            }
            dialog.dismiss();
        }
    });
    builder.setOnCancelListener(new OnCancelListener() {
        @Override
        public void onCancel(DialogInterface dialog) {
            if (choiceCursor != null) {
                choiceCursor.close();
            }
        }
    });
    final Dialog dialog = builder.create();
    dialog.show();
}