Example usage for android.content.res Resources getString

List of usage examples for android.content.res Resources getString

Introduction

In this page you can find the example usage for android.content.res Resources getString.

Prototype

@NonNull
public String getString(@StringRes int id) throws NotFoundException 

Source Link

Document

Return the string value associated with a particular resource ID.

Usage

From source file:com.android.mail.browse.ConversationItemView.java

private static synchronized void getItemViewResources(Context context) {
    if (sConfigurationChangedReceiver == null) {
        sConfigurationChangedReceiver = new BroadcastReceiver() {
            @Override/*from w  w w.j a v a2 s.  co m*/
            public void onReceive(Context context, Intent intent) {
                STAR_OFF = null;
                getItemViewResources(context);
            }
        };
        context.registerReceiver(sConfigurationChangedReceiver,
                new IntentFilter(Intent.ACTION_CONFIGURATION_CHANGED));
    }
    if (STAR_OFF == null) {
        final Resources res = context.getResources();
        // Initialize static bitmaps.
        STAR_OFF = BitmapFactory.decodeResource(res, R.drawable.ic_star_outline_20dp);
        STAR_ON = BitmapFactory.decodeResource(res, R.drawable.ic_star_20dp);
        ATTACHMENT = BitmapFactory.decodeResource(res, R.drawable.ic_attach_file_18dp);
        ONLY_TO_ME = BitmapFactory.decodeResource(res, R.drawable.ic_email_caret_double);
        TO_ME_AND_OTHERS = BitmapFactory.decodeResource(res, R.drawable.ic_email_caret_single);
        IMPORTANT_ONLY_TO_ME = BitmapFactory.decodeResource(res,
                R.drawable.ic_email_caret_double_important_unread);
        IMPORTANT_TO_ME_AND_OTHERS = BitmapFactory.decodeResource(res,
                R.drawable.ic_email_caret_single_important_unread);
        IMPORTANT = BitmapFactory.decodeResource(res, R.drawable.ic_email_caret_none_important_unread);
        STATE_REPLIED = BitmapFactory.decodeResource(res, R.drawable.ic_badge_reply_holo_light);
        STATE_FORWARDED = BitmapFactory.decodeResource(res, R.drawable.ic_badge_forward_holo_light);
        STATE_REPLIED_AND_FORWARDED = BitmapFactory.decodeResource(res,
                R.drawable.ic_badge_reply_forward_holo_light);
        STATE_CALENDAR_INVITE = BitmapFactory.decodeResource(res, R.drawable.ic_badge_invite_holo_light);
        FOCUSED_CONVERSATION_HIGHLIGHT = res.getDrawable(R.drawable.visible_conversation_highlight);

        // Initialize colors.
        sActivatedTextSpan = CharacterStyle
                .wrap(new ForegroundColorSpan(res.getColor(R.color.senders_text_color)));
        sSendersTextColor = res.getColor(R.color.senders_text_color);
        sSubjectTextUnreadSpan = new TextAppearanceSpan(context, R.style.SubjectAppearanceUnreadStyle);
        sSubjectTextReadSpan = new TextAppearanceSpan(context, R.style.SubjectAppearanceReadStyle);

        sBadgeTextSpan = new TextAppearanceSpan(context, R.style.BadgeTextStyle);
        sBadgeBackgroundSpan = new BackgroundColorSpan(res.getColor(R.color.badge_background_color));
        sDateTextColorRead = res.getColor(R.color.date_text_color_read);
        sDateTextColorUnread = res.getColor(R.color.date_text_color_unread);
        sStarTouchSlop = res.getDimensionPixelSize(R.dimen.star_touch_slop);
        sSenderImageTouchSlop = res.getDimensionPixelSize(R.dimen.sender_image_touch_slop);
        sShrinkAnimationDuration = res.getInteger(R.integer.shrink_animation_duration);
        sSlideAnimationDuration = res.getInteger(R.integer.slide_animation_duration);
        // Initialize static color.
        sSendersSplitToken = res.getString(R.string.senders_split_token);
        sElidedPaddingToken = res.getString(R.string.elided_padding_token);
        sScrollSlop = res.getInteger(R.integer.swipeScrollSlop);
        sFoldersMaxCount = res.getInteger(R.integer.conversation_list_max_folder_count);
        sCabAnimationDuration = res.getInteger(R.integer.conv_item_view_cab_anim_duration);
        sBadgePaddingExtraWidth = res.getDimensionPixelSize(R.dimen.badge_padding_extra_width);
        sBadgeRoundedCornerRadius = res.getDimensionPixelSize(R.dimen.badge_rounded_corner_radius);
        sDividerPaint.setColor(res.getColor(R.color.divider_color));
        sDividerHeight = res.getDimensionPixelSize(R.dimen.divider_height);
    }
}

From source file:com.hichinaschool.flashcards.anki.Reviewer.java

private void showDeleteNoteDialog() {
    Dialog dialog;//from w  w w  .j  a v  a2 s.co m
    Resources res = getResources();
    StyledDialog.Builder builder = new StyledDialog.Builder(this);
    builder.setTitle(res.getString(R.string.delete_card_title));
    builder.setIcon(R.drawable.ic_dialog_alert);
    builder.setMessage(String.format(res.getString(R.string.delete_note_message),
            Utils.stripHTML(mCurrentCard.getQuestion(true))));
    builder.setPositiveButton(res.getString(R.string.yes), new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            setNextCardAnimation(false);
            DeckTask.launchDeckTask(DeckTask.TASK_TYPE_DISMISS_NOTE, mDismissCardHandler,
                    new DeckTask.TaskData(mSched, mCurrentCard, 3));
        }
    });
    builder.setNegativeButton(res.getString(R.string.no), null);
    dialog = builder.create();
    dialog.show();
}

From source file:com.ichi2.anki2.DeckPicker.java

@Override
protected void onPrepareDialog(int id, Dialog dialog) {
    Resources res = getResources();
    StyledDialog ad = (StyledDialog) dialog;
    switch (id) {
    case DIALOG_DELETE_DECK:
        if (!AnkiDroidApp.colIsOpen() || mDeckList == null || mDeckList.size() == 0) {
            return;
        }/*from  w w w  .  ja  v  a2s  .com*/
        boolean isDyn = AnkiDroidApp.getCol().getDecks().isDyn(mCurrentDid);
        if (isDyn) {
            ad.setMessage(String.format(res.getString(R.string.delete_cram_deck_message),
                    "\'" + AnkiDroidApp.getCol().getDecks().name(mCurrentDid) + "\'"));
        } else {
            ad.setMessage(String.format(res.getString(R.string.delete_deck_message),
                    "\'" + AnkiDroidApp.getCol().getDecks().name(mCurrentDid) + "\'"));
        }
        break;

    case DIALOG_CONTEXT_MENU:
        if (!AnkiDroidApp.colIsOpen() || mDeckList == null || mDeckList.size() == 0) {
            return;
        }
        mCurrentDid = Long.parseLong(mDeckList.get(mContextMenuPosition).get("did"));
        try {
            ad.changeListItem(CONTEXT_MENU_COLLAPSE_DECK,
                    getResources()
                            .getString(AnkiDroidApp.getCol().getDecks().get(mCurrentDid).getBoolean("collapsed")
                                    ? R.string.contextmenu_deckpicker_inflate_deck
                                    : R.string.contextmenu_deckpicker_collapse_deck));
        } catch (NotFoundException e) {
            // do nothing
        } catch (JSONException e) {
            // do nothing
        }
        ad.setTitle(AnkiDroidApp.getCol().getDecks().name(mCurrentDid));
        break;

    case DIALOG_IMPORT_LOG:
    case DIALOG_SYNC_LOG:
    case DIALOG_SYNC_SANITY_ERROR:
        ad.setMessage(mDialogMessage);
        break;

    case DIALOG_DB_ERROR:
        mLoadFailed = false;
        ad.getButton(Dialog.BUTTON3).setEnabled(hasErrorFiles());
        break;

    case DIALOG_LOAD_FAILED:
        mLoadFailed = true;
        if (mOpenCollectionDialog != null && mOpenCollectionDialog.isShowing()) {
            mOpenCollectionDialog.setMessage(res.getString(R.string.col_load_failed));
        }
        break;

    case DIALOG_ERROR_HANDLING:
        ArrayList<String> options = new ArrayList<String>();
        ArrayList<Integer> values = new ArrayList<Integer>();
        if (AnkiDroidApp.getCol() == null) {
            // retry
            options.add(res.getString(R.string.backup_retry_opening));
            values.add(0);
        } else {
            // fix integrity
            options.add(res.getString(R.string.check_db));
            values.add(1);
        }
        // repair db with sqlite
        options.add(res.getString(R.string.backup_error_menu_repair));
        values.add(2);
        // // restore from backup
        options.add(res.getString(R.string.backup_restore));
        values.add(3);
        // delete old collection and build new one
        options.add(res.getString(R.string.backup_full_sync_from_server));
        values.add(4);
        // delete old collection and build new one
        options.add(res.getString(R.string.backup_del_collection));
        values.add(5);

        String[] titles = new String[options.size()];
        mRepairValues = new int[options.size()];
        for (int i = 0; i < options.size(); i++) {
            titles[i] = options.get(i);
            mRepairValues[i] = values.get(i);
        }
        ad.setItems(titles, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (mRepairValues[which]) {
                case 0:
                    loadCollection();
                    return;
                case 1:
                    integrityCheck();
                    return;
                case 2:
                    showDialog(DIALOG_REPAIR_COLLECTION);
                    return;
                case 3:
                    showDialog(DIALOG_RESTORE_BACKUP);
                    return;
                case 4:
                    showDialog(DIALOG_FULL_SYNC_FROM_SERVER);
                    return;
                case 5:
                    showDialog(DIALOG_NEW_COLLECTION);
                    return;
                }
            }
        });
        break;

    case DIALOG_IMPORT_SELECT:
        List<File> fileList = Utils.getImportableDecks();
        if (fileList.size() == 0) {
            Themes.showThemedToast(DeckPicker.this,
                    getResources().getString(R.string.upgrade_import_no_file_found), false);
        }
        ad.setEnabled(fileList.size() != 0);
        String[] tts = new String[fileList.size()];
        mImportValues = new String[fileList.size()];
        for (int i = 0; i < tts.length; i++) {
            tts[i] = fileList.get(i).getName().replace(".apkg", "");
            mImportValues[i] = fileList.get(i).getAbsolutePath();
        }
        ad.setItems(tts, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                mImportPath = mImportValues[which];
                switch (mImportMethod) {
                case IMPORT_METHOD_ADD:
                    DeckTask.launchDeckTask(DeckTask.TASK_TYPE_IMPORT, mImportAddListener,
                            new TaskData(AnkiDroidApp.getCol(), mImportPath, false));
                    mImportPath = null;
                    break;
                case IMPORT_METHOD_REPLACE:
                    DeckTask.launchDeckTask(DeckTask.TASK_TYPE_IMPORT_REPLACE, mImportReplaceListener,
                            new TaskData(AnkiDroidApp.getCol(), mImportPath));
                    mImportPath = null;
                    break;
                case IMPORT_METHOD_ASK:
                default:
                    showDialog(DIALOG_IMPORT);
                }
                mImportMethod = IMPORT_METHOD_ASK;
            }
        });
        break;
    }
}

From source file:com.nit.vicky.DeckPicker.java

@Override
protected void onPrepareDialog(int id, Dialog dialog) {
    Resources res = getResources();
    StyledDialog ad = (StyledDialog) dialog;
    switch (id) {
    case DIALOG_DELETE_DECK:
        if (!AnkiDroidApp.colIsOpen() || mDeckList == null || mDeckList.size() == 0) {
            return;
        }//from  w  ww. j  av  a  2 s  .c  o m
        boolean isDyn = AnkiDroidApp.getCol().getDecks().isDyn(mCurrentDid);
        if (isDyn) {
            ad.setMessage(String.format(res.getString(R.string.delete_cram_deck_message),
                    "\'" + AnkiDroidApp.getCol().getDecks().name(mCurrentDid) + "\'"));
        } else {
            ad.setMessage(String.format(res.getString(R.string.delete_deck_message),
                    "\'" + AnkiDroidApp.getCol().getDecks().name(mCurrentDid) + "\'"));
        }
        break;

    case DIALOG_CONTEXT_MENU:
        if (!AnkiDroidApp.colIsOpen() || mDeckList == null || mDeckList.size() == 0) {
            return;
        }
        mCurrentDid = Long.parseLong(mDeckList.get(mContextMenuPosition).get("did"));
        try {
            ad.changeListItem(CONTEXT_MENU_COLLAPSE_DECK,
                    getResources()
                            .getString(AnkiDroidApp.getCol().getDecks().get(mCurrentDid).getBoolean("collapsed")
                                    ? R.string.contextmenu_deckpicker_inflate_deck
                                    : R.string.contextmenu_deckpicker_collapse_deck));
        } catch (NotFoundException e) {
            // do nothing
        } catch (JSONException e) {
            // do nothing
        }
        ad.setTitle(AnkiDroidApp.getCol().getDecks().name(mCurrentDid));
        break;

    case DIALOG_IMPORT_LOG:
    case DIALOG_SYNC_LOG:
    case DIALOG_SYNC_SANITY_ERROR:
        // If both have text, separate them by a new line.
        if (!TextUtils.isEmpty(mDialogMessage) && !TextUtils.isEmpty(mSyncMessage)) {
            ad.setMessage(mDialogMessage + "\n\n" + mSyncMessage);
        } else if (!TextUtils.isEmpty(mDialogMessage)) {
            ad.setMessage(mDialogMessage);
        } else {
            ad.setMessage(mSyncMessage);
        }
        break;

    case DIALOG_DB_ERROR:
        mLoadFailed = false;
        ad.getButton(Dialog.BUTTON3).setEnabled(hasErrorFiles());
        break;

    case DIALOG_LOAD_FAILED:
        mLoadFailed = true;
        if (mOpenCollectionDialog != null && mOpenCollectionDialog.isShowing()) {
            mOpenCollectionDialog.setMessage(res.getString(R.string.col_load_failed));
        }
        break;

    case DIALOG_ERROR_HANDLING:
        ArrayList<String> options = new ArrayList<String>();
        ArrayList<Integer> values = new ArrayList<Integer>();
        if (AnkiDroidApp.getCol() == null) {
            // retry
            options.add(res.getString(R.string.backup_retry_opening));
            values.add(0);
        } else {
            // fix integrity
            options.add(res.getString(R.string.check_db));
            values.add(1);
        }
        // repair db with sqlite
        options.add(res.getString(R.string.backup_error_menu_repair));
        values.add(2);
        // // restore from backup
        options.add(res.getString(R.string.backup_restore));
        values.add(3);
        // delete old collection and build new one
        options.add(res.getString(R.string.backup_full_sync_from_server));
        values.add(4);
        // delete old collection and build new one
        options.add(res.getString(R.string.backup_del_collection));
        values.add(5);

        String[] titles = new String[options.size()];
        mRepairValues = new int[options.size()];
        for (int i = 0; i < options.size(); i++) {
            titles[i] = options.get(i);
            mRepairValues[i] = values.get(i);
        }
        ad.setItems(titles, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (mRepairValues[which]) {
                case 0:
                    loadCollection();
                    return;
                case 1:
                    integrityCheck();
                    return;
                case 2:
                    showDialog(DIALOG_REPAIR_COLLECTION);
                    return;
                case 3:
                    showDialog(DIALOG_RESTORE_BACKUP);
                    return;
                case 4:
                    showDialog(DIALOG_FULL_SYNC_FROM_SERVER);
                    return;
                case 5:
                    showDialog(DIALOG_NEW_COLLECTION);
                    return;
                }
            }
        });
        break;

    case DIALOG_IMPORT_SELECT:
        List<File> fileList = Utils.getImportableDecks();
        if (fileList.size() == 0) {
            Themes.showThemedToast(DeckPicker.this,
                    getResources().getString(R.string.upgrade_import_no_file_found), false);
        }
        ad.setEnabled(fileList.size() != 0);
        String[] tts = new String[fileList.size()];
        mImportValues = new String[fileList.size()];
        for (int i = 0; i < tts.length; i++) {
            tts[i] = fileList.get(i).getName().replace(".apkg", "");
            mImportValues[i] = fileList.get(i).getAbsolutePath();
        }
        ad.setItems(tts, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                mImportPath = mImportValues[which];
                switch (mImportMethod) {
                case IMPORT_METHOD_ADD:
                    DeckTask.launchDeckTask(DeckTask.TASK_TYPE_IMPORT, mImportAddListener,
                            new TaskData(AnkiDroidApp.getCol(), mImportPath, false));
                    mImportPath = null;
                    break;
                case IMPORT_METHOD_REPLACE:
                    DeckTask.launchDeckTask(DeckTask.TASK_TYPE_IMPORT_REPLACE, mImportReplaceListener,
                            new TaskData(AnkiDroidApp.getCol(), mImportPath));
                    mImportPath = null;
                    break;
                case IMPORT_METHOD_ASK:
                default:
                    showDialog(DIALOG_IMPORT);
                }
                mImportMethod = IMPORT_METHOD_ASK;
            }
        });
        break;
    }
}

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

/**
 * Check for failed messages and post notifications as needed.
 * TODO: Rewrite this as a NotificationState.
 *//*w w  w .j a  va 2s .com*/
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.ichi2.anki.NoteEditor.java

private void saveNote() {
    final Resources res = getResources();
    if (mSelectedTags == null) {
        mSelectedTags = new ArrayList<String>();
    }// w  w  w. j  av a2s . co m
    // treat add new note and edit existing note independently
    if (mAddNote) {
        // load all of the fields into the note
        for (FieldEditText f : mEditFields) {
            updateField(f);
        }
        try {
            // Save deck to model
            mEditorNote.model().put("did", mCurrentDid);
            // Save tags to model
            mEditorNote.setTagsFromStr(tagsAsString(mSelectedTags));
            JSONArray ja = new JSONArray();
            for (String t : mSelectedTags) {
                ja.put(t);
            }
            getCol().getModels().current().put("tags", ja);
            getCol().getModels().setChanged();
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
        DeckTask.launchDeckTask(DeckTask.TASK_TYPE_ADD_FACT, mSaveFactHandler,
                new DeckTask.TaskData(mEditorNote));
    } else {
        // Check whether note type has been changed
        final JSONObject newModel = getCurrentlySelectedModel();
        final JSONObject oldModel = mCurrentEditedCard.model();
        if (!newModel.equals(oldModel)) {
            mReloadRequired = true;
            if (mModelChangeCardMap.size() < mEditorNote.cards().size()
                    || mModelChangeCardMap.containsKey(null)) {
                // If cards will be lost via the new mapping then show a confirmation dialog before proceeding with the change
                ConfirmationDialog dialog = new ConfirmationDialog() {
                    @Override
                    public void confirm() {
                        // Bypass the check once the user confirms
                        changeNoteTypeWithErrorHandling(oldModel, newModel);
                    }
                };
                dialog.setArgs(res.getString(R.string.confirm_map_cards_to_nothing));
                showDialogFragment(dialog);
            } else {
                // Otherwise go straight to changing note type
                changeNoteTypeWithErrorHandling(oldModel, newModel);
            }
            return;
        }
        // Regular changes in note content
        boolean modified = false;
        // changed did? this has to be done first as remFromDyn() involves a direct write to the database
        if (mCurrentEditedCard.getDid() != mCurrentDid) {
            mReloadRequired = true;
            // remove card from filtered deck first (if relevant)
            getCol().getSched().remFromDyn(new long[] { mCurrentEditedCard.getId() });
            // refresh the card object to reflect the database changes in remFromDyn()
            mCurrentEditedCard.load();
            // also reload the note object
            mEditorNote = mCurrentEditedCard.note();
            // then set the card ID to the new deck
            mCurrentEditedCard.setDid(mCurrentDid);
            modified = true;
        }
        // now load any changes to the fields from the form
        for (FieldEditText f : mEditFields) {
            modified = modified | updateField(f);
        }
        // added tag?
        for (String t : mSelectedTags) {
            modified = modified || !mEditorNote.hasTag(t);
        }
        // removed tag?
        modified = modified || mEditorNote.getTags().size() > mSelectedTags.size();
        if (modified) {
            mEditorNote.setTagsFromStr(tagsAsString(mSelectedTags));
            // set a flag so that changes to card object will be written to DB later via onActivityResult() in
            // CardBrowser
            mChanged = true;
        }
        closeNoteEditor();
    }
}

From source file:org.witness.ssc.xfer.utils.PublishingUtils.java

public Thread videoUploadToFTPserver(final Activity activity, final Handler handler,
        final String latestVideoFile_filename, final String latestVideoFile_absolutepath,
        final String emailAddress, final long sdrecord_id) {

    Log.d(TAG, "doVideoFTP starting");

    // Make the progress bar view visible.
    ((SSCXferActivity) activity).startedUploading();

    final Resources res = activity.getResources();

    Thread t = new Thread(new Runnable() {
        public void run() {
            // Do background task.
            // FTP; connect preferences here!
            ///*from  w  w w . j  a v a 2s .c  o  m*/
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity.getBaseContext());
            String ftpHostName = prefs.getString("defaultFTPhostPreference", null);
            String ftpUsername = prefs.getString("defaultFTPusernamePreference", null);
            String ftpPassword = prefs.getString("defaultFTPpasswordPreference", null);

            // use name of local file.
            String ftpRemoteFtpFilename = latestVideoFile_filename;

            // FTP
            FTPClient ftpClient = new FTPClient();
            InetAddress uploadhost = null;
            try {

                uploadhost = InetAddress.getByName(ftpHostName);
            } catch (UnknownHostException e1) {
                // If DNS resolution fails then abort immediately - show
                // dialog to
                // inform user first.
                e1.printStackTrace();
                Log.e(TAG, " got exception resolving " + ftpHostName + " - video uploading failed.");
                uploadhost = null;
            }

            if (uploadhost == null) {

                // Use the handler to execute a Runnable on the
                // main thread in order to have access to the
                // UI elements.
                handler.postDelayed(new Runnable() {
                    public void run() {
                        // Update UI

                        // Hide the progress bar
                        ((SSCXferActivity) activity).finishedUploading(false);
                        ((SSCXferActivity) activity)
                                .createNotification(res.getString(R.string.upload_to_ftp_host_failed_));

                        new AlertDialog.Builder(activity).setMessage(R.string.cant_find_upload_host)
                                .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int whichButton) {

                                    }
                                })

                                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int whichButton) {

                                    }
                                }).show();

                    }
                }, 0);

                return;
            }

            boolean connected = false;

            try {
                ftpClient.connect(uploadhost);
                connected = true;

            } catch (SocketException e) {
                e.printStackTrace();
                connected = false;

            } catch (UnknownHostException e) {
                //
                e.printStackTrace();
                connected = false;
            } catch (IOException e) {
                //
                e.printStackTrace();
                connected = false;
            }

            if (!connected) {

                // Use the handler to execute a Runnable on the
                // main thread in order to have access to the
                // UI elements.
                handler.postDelayed(new Runnable() {
                    public void run() {
                        // Update UI

                        // Hide the progress bar
                        ((SSCXferActivity) activity).finishedUploading(false);
                        ((SSCXferActivity) activity)
                                .createNotification(res.getString(R.string.upload_to_ftp_host_failed_));

                        new AlertDialog.Builder(activity).setMessage(R.string.cant_login_upload_host)
                                .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int whichButton) {

                                    }
                                })

                                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int whichButton) {

                                    }
                                }).show();

                    }
                }, 0);

                return;
            }

            boolean reply = false;
            try {

                reply = ftpClient.login(ftpUsername, ftpPassword);
            } catch (IOException e) {
                //
                e.printStackTrace();
                Log.e(TAG, " got exception on ftp.login - video uploading failed.");
            }

            // check the reply code here
            // If we cant login, abort after showing user a dialog.
            if (!reply) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    //
                    e.printStackTrace();
                }

                // Use the handler to execute a Runnable on the
                // main thread in order to have access to the
                // UI elements.
                handler.postDelayed(new Runnable() {
                    public void run() {
                        // Update UI

                        // Hide the progress bar
                        ((SSCXferActivity) activity).finishedUploading(false);
                        ((SSCXferActivity) activity)
                                .createNotification(res.getString(R.string.upload_to_ftp_host_failed_));

                        new AlertDialog.Builder(activity).setMessage(R.string.cant_login_upload_host)
                                .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int whichButton) {

                                    }
                                }).show();
                    }
                }, 0);

                return;
            }

            // Set File type to binary
            try {
                ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            } catch (IOException e) {
                //
                e.printStackTrace();
                // keep going?!
            }

            // BEYOND HERE DONT USE DIALOGS!

            // Construct the input stream to send to Ftp server, from the
            // local
            // video file on the sd card
            BufferedInputStream buffIn = null;
            File file = new File(latestVideoFile_absolutepath);

            try {
                buffIn = new BufferedInputStream(new FileInputStream(file));
            } catch (FileNotFoundException e) {
                //
                e.printStackTrace();
                Log.e(TAG, " got exception on local video file - video uploading failed.");

                // Use the handler to execute a Runnable on the
                // main thread in order to have access to the
                // UI elements.
                handler.postDelayed(new Runnable() {
                    public void run() {
                        // Update UI

                        // Hide the progress bar
                        ((SSCXferActivity) activity).finishedUploading(false);
                        ((SSCXferActivity) activity)
                                .createNotification(res.getString(R.string.upload_to_ftp_host_failed_));

                    }
                }, 0);

                // This is a bad error, lets abort.
                // user dialog ?! shouldnt happen, but still...
                return;
            }

            ftpClient.enterLocalPassiveMode();

            try {
                // UPLOAD THE LOCAL VIDEO FILE.
                ftpClient.storeFile(ftpRemoteFtpFilename, buffIn);
            } catch (IOException e) {
                //
                e.printStackTrace();
                Log.e(TAG, " got exception on storeFile - video uploading failed.");

                // This is a bad error, lets abort.
                // user dialog ?! shouldnt happen, but still...
                // Use the handler to execute a Runnable on the
                // main thread in order to have access to the
                // UI elements.
                handler.postDelayed(new Runnable() {
                    public void run() {
                        // Update UI

                        // Hide the progress bar
                        ((SSCXferActivity) activity).finishedUploading(false);
                        ((SSCXferActivity) activity)
                                .createNotification(res.getString(R.string.upload_to_ftp_host_failed_));

                    }
                }, 0);
                return;
            }
            try {
                buffIn.close();
            } catch (IOException e) {
                //
                e.printStackTrace();
                Log.e(TAG, " got exception on buff.close - video uploading failed.");

                // Use the handler to execute a Runnable on the
                // main thread in order to have access to the
                // UI elements.
                handler.postDelayed(new Runnable() {
                    public void run() {
                        // Update UI

                        // Hide the progress bar
                        ((SSCXferActivity) activity).finishedUploading(false);
                        ((SSCXferActivity) activity)
                                .createNotification(res.getString(R.string.upload_to_ftp_host_failed_));

                    }
                }, 0);
                return;
            }
            try {
                ftpClient.logout();
            } catch (IOException e) {
                //
                e.printStackTrace();
                Log.e(TAG, " got exception on ftp logout - video uploading failed.");

                // Use the handler to execute a Runnable on the
                // main thread in order to have access to the
                // UI elements.
                handler.postDelayed(new Runnable() {
                    public void run() {
                        // Update UI

                        // Hide the progress bar
                        ((SSCXferActivity) activity).finishedUploading(false);
                        ((SSCXferActivity) activity)
                                .createNotification(res.getString(R.string.upload_to_ftp_host_failed_));

                    }
                }, 0);
                return;
            }
            try {
                ftpClient.disconnect();
            } catch (IOException e) {
                //
                e.printStackTrace();
                Log.e(TAG, " got exception on ftp disconnect - video uploading failed.");

                // Use the handler to execute a Runnable on the
                // main thread in order to have access to the
                // UI elements.
                handler.postDelayed(new Runnable() {
                    public void run() {
                        // Update UI

                        // Hide the progress bar
                        ((SSCXferActivity) activity).finishedUploading(false);
                        ((SSCXferActivity) activity)
                                .createNotification(res.getString(R.string.upload_to_ftp_host_failed_));

                    }
                }, 0);
                return;
            }

            if (emailAddress != null && ftpHostName != null) {

                // EmailSender through IR controlled gmail system.
                SSLEmailSender sender = new SSLEmailSender(
                        activity.getString(R.string.automatic_email_username),
                        activity.getString(R.string.automatic_email_password)); // consider
                // this
                // public
                // knowledge.
                try {
                    sender.sendMail(activity.getString(R.string.vidiom_automatic_email), // subject.getText().toString(),
                            activity.getString(R.string.url_of_hosted_video_is_) + " " + ftpHostName, // body.getText().toString(),
                            activity.getString(R.string.automatic_email_from), // from.getText().toString(),
                            emailAddress // to.getText().toString()
                    );
                } catch (Exception e) {
                    Log.e(TAG, e.getMessage(), e);
                }
            }

            // Log record of this URL in POSTs table
            dbutils.creatHostDetailRecordwithNewVideoUploaded(sdrecord_id, ftpHostName, ftpHostName, "");

            // Use the handler to execute a Runnable on the
            // main thread in order to have access to the
            // UI elements.
            handler.postDelayed(new Runnable() {
                public void run() {
                    // Update UI

                    // Indicate back to calling activity the result!
                    // update uploadInProgress state also.

                    ((SSCXferActivity) activity).finishedUploading(true);
                    ((SSCXferActivity) activity)
                            .createNotification(res.getString(R.string.upload_to_ftp_host_succeeded_));

                }
            }, 0);

        }
    });

    t.start();

    return t;
}

From source file:com.ichi2.anki.Info.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    Timber.d("onCreate()");
    Themes.applyTheme(this);
    super.onCreate(savedInstanceState);

    Resources res = getResources();

    mType = getIntent().getIntExtra(TYPE_EXTRA, TYPE_ABOUT);

    setTitle(getTitleString());/*from w  w  w  .  j  a  v a2s . com*/

    setContentView(R.layout.info);

    mWebView = (WebView) findViewById(R.id.info);
    mWebView.setBackgroundColor(res.getColor(Themes.getBackgroundColor()));
    Themes.setWallpaper((View) mWebView.getParent().getParent().getParent());

    TextView termsAndConditionsView = (TextView) findViewById(R.id.info_terms_and_conditions);
    termsAndConditionsView.setMovementMethod(LinkMovementMethod.getInstance());
    Button continueButton = (Button) findViewById(R.id.info_continue);
    continueButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View arg0) {
            if (mType == TYPE_ABOUT) {
                if (AnkiDroidApp.isKindle()) {
                    Intent intent = new Intent("android.intent.action.VIEW",
                            Uri.parse("http://www.amazon.com/gp/mas/dl/android?p=com.ichi2.anki"));
                    startActivity(intent);
                } else {
                    Info.this.startActivity(
                            new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=com.ichi2.anki")));
                }
                return;
            }
            setResult(RESULT_OK);
            switch (mType) {
            case TYPE_NEW_VERSION:
                AnkiDroidApp.getSharedPrefs(Info.this.getBaseContext()).edit()
                        .putString("lastVersion", AnkiDroidApp.getPkgVersionName()).commit();
                break;
            case TYPE_UPGRADE_DECKS:
                break;
            }
            finishWithAnimation();
        }
    });

    StringBuilder sb = new StringBuilder();
    switch (mType) {
    case TYPE_ABOUT:
        String[] content = res.getStringArray(R.array.about_content);
        sb.append("<html><body text=\"#000000\" link=\"#E37068\" alink=\"#E37068\" vlink=\"#E37068\">");
        sb.append(
                String.format(content[0], res.getString(R.string.app_name), res.getString(R.string.link_anki)))
                .append("<br/><br/>");
        sb.append(String.format(content[1], res.getString(R.string.link_issue_tracker),
                res.getString(R.string.link_wiki), res.getString(R.string.link_forum))).append("<br/><br/>");
        sb.append(String.format(content[2], res.getString(R.string.link_wikipedia_open_source),
                res.getString(R.string.link_contribution),
                res.getString(R.string.link_contribution_contributors))).append(" ");
        sb.append(String.format(content[3], res.getString(R.string.link_translation),
                res.getString(R.string.link_donation))).append("<br/><br/>");
        sb.append(String.format(content[4], res.getString(R.string.licence_wiki),
                res.getString(R.string.link_source))).append("<br/><br/>");
        sb.append("</body></html>");
        mWebView.loadDataWithBaseURL("", sb.toString(), "text/html", "utf-8", null);
        ((Button) findViewById(R.id.info_continue)).setText(res.getString(R.string.info_rate));
        Button debugCopy = ((Button) findViewById(R.id.info_later));
        debugCopy.setText(res.getString(R.string.feedback_copy_debug));
        debugCopy.setVisibility(View.VISIBLE);
        debugCopy.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                copyDebugInfo();
            }
        });
        break;

    case TYPE_NEW_VERSION:
        sb.append(res.getString(R.string.new_version_message));
        sb.append("<ul>");
        String[] features = res.getStringArray(R.array.new_version_features);
        for (int i = 0; i < features.length; i++) {
            sb.append("<li>");
            sb.append(features[i]);
            sb.append("</li>");
        }
        sb.append("</ul>");
        sb.append(
                "<br><br><br>A new design is coming in v2.5, <a href=\"https://groups.google.com/d/msg/anki-android/DrMPHn9NQtk/aZYXdIZRCwAJ\">preview it here</a>!");
        sb.append("</body></html>");
        mWebView.loadDataWithBaseURL("", sb.toString(), "text/html", "utf-8", null);

        // reactivating ssl check for every new version
        AnkiDroidApp.getSharedPrefs(Info.this.getBaseContext()).edit().putBoolean("sslAcceptAll", false)
                .commit();
        break;

    case TYPE_SHARED_DECKS:
        mLoadingLayer = (RelativeLayout) findViewById(R.id.info_loading_layer);
        mLoadingLayer.setVisibility(View.VISIBLE);
        try {
            mShareDecksTemplate = Utils.convertStreamToString(getAssets().open("shared_decks_template.html"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        mWebView.setWebViewClient(new MobileAnkiWebview());
        mWebView.loadUrl(res.getString(R.string.shared_decks_url));
        mWebView.getSettings().setJavaScriptEnabled(true);
        termsAndConditionsView.setVisibility(View.VISIBLE);
        continueButton.setText(res.getString(R.string.download_button_return));
        break;

    case TYPE_UPGRADE_DECKS:
        setTitle(R.string.deck_upgrade_title);
        sb.append("<html><body>");

        // add "later" button
        Button but = (Button) findViewById(R.id.info_later);
        but.setVisibility(View.VISIBLE);

        // add sync button
        Button syncButton = (Button) findViewById(R.id.info_sync);
        syncButton.setVisibility(View.VISIBLE);

        mUpgradeStage = getIntent().getIntExtra(TYPE_UPGRADE_STAGE, -1);
        boolean reupgrading = false;

        switch (mUpgradeStage) {
        case UPGRADE_SCREEN_BASIC1:
            sb.append(getString(R.string.deck_upgrade_major_warning));
            but.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    Themes.showThemedToast(Info.this,
                            getString(R.string.deck_upgrade_start_again_to_upgrade_toast), false);
                    setResult(RESULT_CANCELED);
                    finish();
                }
            });
            syncButton.setText(R.string.more_options);
            syncButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    Intent result = new Intent();
                    result.putExtra(TYPE_UPGRADE_STAGE, UPGRADE_SCREEN_MORE_OPTIONS);
                    setResult(RESULT_OK, result);
                    finishWithAnimation();
                }
            });
            continueButton.setText(R.string.now);
            continueButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    Intent result = new Intent();
                    result.putExtra(TYPE_UPGRADE_STAGE, UPGRADE_SCREEN_BASIC2);
                    setResult(RESULT_OK, result);
                    finishWithAnimation();
                }
            });
            break;

        case UPGRADE_SCREEN_BASIC2:
            sb.append(getString(R.string.deck_upgrade_recommended_method));
            but.setText(R.string.back);
            but.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    Intent result = new Intent();
                    result.putExtra(TYPE_UPGRADE_STAGE, UPGRADE_SCREEN_BASIC1);
                    result.putExtra(TYPE_ANIMATION_RIGHT, true);
                    setResult(RESULT_OK, result);
                    finishWithAnimation(false);
                }
            });
            syncButton.setEnabled(false);
            syncButton.setText("N/A");
            syncButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    Intent result = new Intent();
                    result.putExtra(TYPE_UPGRADE_STAGE, UPGRADE_SCREEN_WEB_UPGRADE);
                    setResult(RESULT_OK, result);
                    finishWithAnimation();
                }
            });
            continueButton.setText(getString(R.string.pc));
            continueButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    Intent result = new Intent();
                    result.putExtra(TYPE_UPGRADE_STAGE, UPGRADE_SCREEN_PC_UPGRADE);
                    setResult(RESULT_OK, result);
                    finishWithAnimation();
                }
            });
            break;

        case UPGRADE_SCREEN_MORE_OPTIONS:
            // If re-upgrading a collection exists already, so don't offer to make a new one
            if (new File(AnkiDroidApp.getCollectionPath()).exists()) {
                setTitle(getString(R.string.exit_wizard));
                reupgrading = true;
                sb.append(getString(R.string.deck_upgrade_more_options_exit));
            } else {
                sb.append(getString(R.string.deck_upgrade_more_options_new_collection));
            }
            sb.append(getString(R.string.deck_upgrade_more_options_downgrade));
            but.setText(R.string.upgrade_decks_button);
            but.setText(R.string.back);
            but.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    Intent result = new Intent();
                    result.putExtra(TYPE_UPGRADE_STAGE, UPGRADE_SCREEN_BASIC1);
                    result.putExtra(TYPE_ANIMATION_RIGHT, true);
                    setResult(RESULT_OK, result);
                    finishWithAnimation(false);
                }
            });
            if (reupgrading) {
                syncButton.setText(getString(R.string.upgrade_deck_dont_upgrade));
                syncButton.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View arg0) {
                        Intent result = new Intent();
                        result.putExtra(TYPE_UPGRADE_STAGE, UPGRADE_CONTINUE);
                        setResult(RESULT_OK, result);
                        finishWithAnimation();
                    }
                });
            } else {
                syncButton.setText(R.string.deck_upgrade_create_new_collection_button);
                syncButton.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View arg0) {
                        StyledDialog.Builder builder = new StyledDialog.Builder(Info.this);
                        builder.setTitle(R.string.deck_upgrade_create_new_collection_title);
                        builder.setIcon(R.drawable.ic_dialog_alert);
                        builder.setMessage(R.string.deck_upgrade_not_import_warning);
                        builder.setPositiveButton(R.string.dialog_positive_create,
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        Intent result = new Intent();
                                        result.putExtra(TYPE_UPGRADE_STAGE, UPGRADE_CONTINUE);
                                        setResult(RESULT_OK, result);
                                        finishWithAnimation();
                                    }
                                });
                        builder.setNegativeButton(R.string.dialog_cancel, null);
                        builder.show();
                    }
                });
            }
            continueButton.setVisibility(View.GONE);
            break;

        case UPGRADE_SCREEN_WEB_UPGRADE:
            sb.append(getString(R.string.deck_upgrade_via_web));
            but.setText(R.string.back);
            but.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    Intent result = new Intent();
                    result.putExtra(TYPE_UPGRADE_STAGE, UPGRADE_SCREEN_BASIC2);
                    result.putExtra(TYPE_ANIMATION_RIGHT, true);
                    setResult(RESULT_OK, result);
                    finishWithAnimation(false);
                }
            });
            syncButton.setVisibility(View.GONE);
            continueButton.setText(R.string.dialog_continue);
            continueButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    lockScreenOrientation();
                    Connection.upgradeDecks(mWebUpgradeListener, new Connection.Payload(
                            new Object[] { AnkiDroidApp.getCurrentAnkiDroidDirectory() }));
                }
            });
            break;

        case UPGRADE_SCREEN_PC_UPGRADE:
            sb.append(getString(R.string.deck_upgrade_via_anki_desktop));
            but.setText(R.string.back);
            but.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    Intent result = new Intent();
                    result.putExtra(TYPE_UPGRADE_STAGE, UPGRADE_SCREEN_BASIC2);
                    result.putExtra(TYPE_ANIMATION_RIGHT, true);
                    setResult(RESULT_OK, result);
                    finishWithAnimation(false);
                }
            });
            syncButton.setText(R.string.usb);
            syncButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    Intent result = new Intent();
                    result.putExtra(TYPE_UPGRADE_STAGE, UPGRADE_SCREEN_MANUAL_UPGRADE);
                    setResult(RESULT_OK, result);
                    finishWithAnimation();
                }
            });
            continueButton.setEnabled(false);
            continueButton.setText("N/A");
            continueButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    Intent result = new Intent();
                    result.putExtra(TYPE_UPGRADE_STAGE, UPGRADE_SCREEN_AUTO_UPGRADE);
                    setResult(RESULT_OK, result);
                    finishWithAnimation();
                }
            });
            break;

        case UPGRADE_SCREEN_MANUAL_UPGRADE:
            sb.append(getString(R.string.deck_upgrade_manual));
            but.setText(R.string.back);
            but.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    Intent result = new Intent();
                    result.putExtra(TYPE_UPGRADE_STAGE, UPGRADE_SCREEN_BASIC2);
                    result.putExtra(TYPE_ANIMATION_RIGHT, true);
                    setResult(RESULT_OK, result);
                    finishWithAnimation(false);
                }
            });
            syncButton.setText(R.string._import);
            syncButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    File apkgFile = new File(AnkiDroidApp.getCurrentAnkiDroidDirectory(),
                            DeckPicker.IMPORT_REPLACE_COLLECTION_NAME);
                    List<File> importables = Utils.getImportableDecks();
                    if (importables == null || !importables.contains(apkgFile)) {
                        Themes.showThemedToast(Info.this,
                                getResources().getString(R.string.upgrade_import_no_file_found,
                                        DeckPicker.IMPORT_REPLACE_COLLECTION_NAME),
                                false);
                    } else {
                        lockScreenOrientation();
                        DeckTask.launchDeckTask(DeckTask.TASK_TYPE_IMPORT_REPLACE, mUpgradeImportListener,
                                new DeckTask.TaskData(AnkiDroidApp.getCol(), apkgFile.getAbsolutePath()));
                    }
                }
            });
            continueButton.setVisibility(View.GONE);
            break;

        case UPGRADE_SCREEN_AUTO_UPGRADE:
            sb.append(getString(R.string.deck_upgrade_auto_upgrade));
            but.setText(R.string.back);
            but.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    Intent result = new Intent();
                    result.putExtra(TYPE_UPGRADE_STAGE, UPGRADE_SCREEN_PC_UPGRADE);
                    result.putExtra(TYPE_ANIMATION_RIGHT, true);
                    setResult(RESULT_OK, result);
                    finishWithAnimation(false);
                }
            });
            syncButton.setText(getString(R.string.upgrade_deck_sync_from_ankiweb));
            syncButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    StyledDialog.Builder builder = new StyledDialog.Builder(Info.this);
                    builder.setTitle(R.string.upgrade_deck_sync_from_ankiweb);
                    builder.setIcon(R.drawable.ic_dialog_alert);
                    builder.setMessage(getString(R.string.upgrade_deck_have_you_synced));
                    builder.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            lockScreenOrientation();
                            downloadCollection();
                        }
                    });
                    builder.setNegativeButton(R.string.back, null);
                    builder.show();
                }
            });
            continueButton.setVisibility(View.GONE);
            break;
        }

        // File[] fileList = (new File(AnkiDroidApp.getCurrentAnkiDroidDirectory())).listFiles(new
        // OldAnkiDeckFilter());
        // StringBuilder fsb = new StringBuilder();
        // fsb.append("<ul>");
        // for (File f : fileList) {
        // fsb.append("<li>").append(f.getName().replace(".anki", "")).append("</li>");
        // }
        // fsb.append("</ul>");
        // sb.append(res.getString(R.string.upgrade_decks_message, fsb.toString()));
        // sb.append("<ul><li>");
        // sb.append(res.getString(R.string.upgrade_decks_message_pos1,
        // AnkiDroidApp.getCurrentAnkiDroidDirectory()));
        // sb.append("</li><li>");
        // sb.append(res.getString(R.string.upgrade_decks_message_pos2, res.getString(R.string.link_anki)));
        // sb.append("</li><li>");
        // sb.append(res.getString(R.string.upgrade_decks_message_pos3));
        // sb.append("</li></ul>");
        // sb.append(res.getString(R.string.upgrade_decks_message_finish));
        sb.append("</body></html>");
        mWebView.loadDataWithBaseURL("", sb.toString(), "text/html", "utf-8", null);

        StyledDialog.Builder builder2 = new StyledDialog.Builder(this);
        // builder2.setTitle(res.getString(R.string.connection_error_title));
        builder2.setIcon(R.drawable.ic_dialog_alert);
        builder2.setMessage(res.getString(R.string.youre_offline));
        builder2.setPositiveButton(res.getString(R.string.dialog_ok), null);
        mNoConnectionAlert = builder2.create();
        break;

    default:
        finish();
        break;
    }
}

From source file:com.ichi2.anki2.DeckPicker.java

/** Handles item selections */
@Override//  w  w  w . j  a v a  2  s  . c om
public boolean onOptionsItemSelected(MenuItem item) {
    Resources res = getResources();

    switch (item.getItemId()) {

    case MENU_HELP:
        showDialog(DIALOG_SELECT_HELP);
        return true;

    case MENU_SYNC:
        sync();
        return true;

    case MENU_ADD_NOTE:
        addNote();
        return true;

    case MENU_STATISTICS:
        showDialog(DIALOG_SELECT_STATISTICS_TYPE);
        return true;

    case MENU_CARDBROWSER:
        openCardBrowser();
        return true;

    case MENU_CREATE_DECK:
        StyledDialog.Builder builder2 = new StyledDialog.Builder(DeckPicker.this);
        builder2.setTitle(res.getString(R.string.new_deck));

        mDialogEditText = (EditText) new EditText(DeckPicker.this);
        // mDialogEditText.setFilters(new InputFilter[] { mDeckNameFilter });
        builder2.setView(mDialogEditText, false, false);
        builder2.setPositiveButton(res.getString(R.string.create), new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                String deckName = mDialogEditText.getText().toString().replaceAll("[\'\"\\n\\r\\[\\]\\(\\)]",
                        "");
                Log.i(AnkiDroidApp.TAG, "Creating deck: " + deckName);
                AnkiDroidApp.getCol().getDecks().id(deckName, true);
                loadCounts();
            }
        });
        builder2.setNegativeButton(res.getString(R.string.cancel), null);
        builder2.create().show();
        return true;

    case MENU_CREATE_DYNAMIC_DECK:
        StyledDialog.Builder builder3 = new StyledDialog.Builder(DeckPicker.this);
        builder3.setTitle(res.getString(R.string.new_deck));

        mDialogEditText = (EditText) new EditText(DeckPicker.this);
        ArrayList<String> names = AnkiDroidApp.getCol().getDecks().allNames();
        int n = 1;
        String cramDeckName = "Cram 1";
        while (names.contains(cramDeckName)) {
            n++;
            cramDeckName = "Cram " + n;
        }
        mDialogEditText.setText(cramDeckName);
        // mDialogEditText.setFilters(new InputFilter[] { mDeckNameFilter });
        builder3.setView(mDialogEditText, false, false);
        builder3.setPositiveButton(res.getString(R.string.create), new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                long id = AnkiDroidApp.getCol().getDecks().newDyn(mDialogEditText.getText().toString());
                openStudyOptions(id, new Bundle());
            }
        });
        builder3.setNegativeButton(res.getString(R.string.cancel), null);
        builder3.create().show();
        return true;

    case MENU_ABOUT:
        startActivity(new Intent(DeckPicker.this, Info.class));
        if (AnkiDroidApp.SDK_VERSION > 4) {
            ActivityTransitionAnimation.slide(DeckPicker.this, ActivityTransitionAnimation.RIGHT);
        }
        return true;

    case MENU_ADD_SHARED_DECK:
        if (AnkiDroidApp.getCol() != null) {
            SharedPreferences preferences = AnkiDroidApp.getSharedPrefs(getBaseContext());
            String hkey = preferences.getString("hkey", "");
            if (hkey.length() == 0) {
                showDialog(DIALOG_USER_NOT_LOGGED_IN_ADD_SHARED_DECK);
            } else {
                addSharedDeck();
            }
        }
        return true;

    case MENU_IMPORT:
        showDialog(DIALOG_IMPORT_HINT);
        return true;

    case MENU_PREFERENCES:
        startActivityForResult(new Intent(DeckPicker.this, Preferences.class), PREFERENCES_UPDATE);
        return true;

    case MENU_FEEDBACK:
        Intent i = new Intent(DeckPicker.this, Feedback.class);
        i.putExtra("request", REPORT_FEEDBACK);
        startActivityForResult(i, REPORT_FEEDBACK);
        if (AnkiDroidApp.SDK_VERSION > 4) {
            ActivityTransitionAnimation.slide(this, ActivityTransitionAnimation.RIGHT);
        }
        return true;

    case CHECK_DATABASE:
        integrityCheck();
        return true;

    case StudyOptionsActivity.MENU_ROTATE:
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        } else {
            this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
        return true;

    case StudyOptionsActivity.MENU_NIGHT:
        SharedPreferences preferences = AnkiDroidApp.getSharedPrefs(this);
        if (preferences.getBoolean("invertedColors", false)) {
            preferences.edit().putBoolean("invertedColors", false).commit();
            item.setIcon(R.drawable.ic_menu_night);
        } else {
            preferences.edit().putBoolean("invertedColors", true).commit();
            item.setIcon(R.drawable.ic_menu_night_checked);
        }
        return true;

    case MENU_REUPGRADE:
        restartUpgradeProcess();
        return true;

    default:
        return super.onOptionsItemSelected(item);
    }
}

From source file:com.hichinaschool.flashcards.anki.DeckPicker.java

private void updateDecksList(TreeSet<Object[]> decks, int eta, int count) {
    if (decks == null) {
        Log.e(AnkiDroidApp.TAG, "updateDecksList: empty decks list");
        return;//from   ww w.java 2  s . c  o  m
    }

    ArrayList<String> deckTitles = new ArrayList<String>();
    String currentName = null;
    Object[] defaultDeck = null;
    for (Object[] d : decks) {
        currentName = readableDeckName(((String[]) d[0]));
        if (!currentName.equals("Default"))
            deckTitles.add(currentName);
        else
            defaultDeck = d;
    }

    decks.remove(defaultDeck);

    if (!deckTitles.contains("HSK 1 Vocabulary")) {
        String[] strings = { "HSK 1 Vocabulary" };
        decks.add(new Object[] { strings, Long.valueOf(-10), 0, 0, 0, false,
                "https://s3.amazonaws.com/s3.hichinaschool.com.br/HSK+1+Vocabulary.apkg" });
    }

    if (!deckTitles.contains("HSK 2 Vocabulary")) {
        String[] strings = { "HSK 2 Vocabulary" };
        decks.add(new Object[] { strings, Long.valueOf(-20), 0, 0, 0, false,
                "https://s3.amazonaws.com/s3.hichinaschool.com.br/HSK+2+Vocabulary.apkg" });
    }

    if (!deckTitles.contains("HSK 3 Vocabulary")) {
        String[] strings = { "HSK 3 Vocabulary" };
        decks.add(new Object[] { strings, Long.valueOf(-30), 0, 0, 0, false,
                "https://s3.amazonaws.com/s3.hichinaschool.com.br/HSK+3+Vocabulary.apkg" });
    }

    if (!deckTitles.contains("HSK 4 Vocabulary")) {
        String[] strings = { "HSK 4 Vocabulary" };
        decks.add(new Object[] { strings, Long.valueOf(-40), 0, 0, 0, false,
                "https://s3.amazonaws.com/s3.hichinaschool.com.br/HSK+4+Vocabulary.apkg" });
    }

    if (!deckTitles.contains("HSK 5 Vocabulary")) {
        String[] strings = { "HSK 5 Vocabulary" };
        decks.add(new Object[] { strings, Long.valueOf(-50), 0, 0, 0, false,
                "https://s3.amazonaws.com/s3.hichinaschool.com.br/HSK+5+Vocabulary.apkg" });
    }

    mDeckList.clear();
    int due = 0;
    for (Object[] d : decks) {
        HashMap<String, String> m = new HashMap<String, String>();
        String[] name = ((String[]) d[0]);
        m.put("name", readableDeckName(name));
        m.put("did", ((Long) d[1]).toString());
        m.put("new", ((Integer) d[2]).toString());
        m.put("lrn", ((Integer) d[3]).toString());
        m.put("rev", ((Integer) d[4]).toString());
        m.put("dyn", ((Boolean) d[5]) ? "d1" : "d0");
        if (d.length > 6)
            m.put("url", ((String) d[6].toString()));
        // m.put("complMat", ((Float)d[5]).toString());
        // m.put("complAll", ((Float)d[6]).toString());
        if (name.length == 1) {
            due += Integer.parseInt(m.get("new")) + Integer.parseInt(m.get("lrn"))
                    + Integer.parseInt(m.get("rev"));
            // top position
            m.put("sep", "top");
            // correct previous deck
            if (mDeckList.size() > 0) {
                HashMap<String, String> map = mDeckList.get(mDeckList.size() - 1);
                if (map.get("sep").equals("top")) {
                    map.put("sep", "ful");
                } else {
                    map.put("sep", "bot");
                }
            }
        } else {
            // center position
            m.put("sep", "cen");
        }
        if (mDeckList.size() > 0 && mDeckList.size() == decks.size() - 1) {
            // bottom position
            if (name.length == 1) {
                m.put("sep", "ful");
            } else {
                m.put("sep", "bot");
            }
        }
        mDeckList.add(m);
    }

    mDeckListAdapter.notifyDataSetChanged();

    // set title
    Resources res = getResources();
    //        if (count != -1) {
    //            String time = "-";
    //            if (eta != -1) {
    //                time = res.getQuantityString(R.plurals.deckpicker_title_minutes, eta, eta);
    //            }
    //            AnkiDroidApp.getCompat().setSubtitle(this, res.getQuantityString(R.plurals.deckpicker_title, due, due, count, time));
    //        }
    setTitle(res.getString(R.string.app_name));

    // update widget
    WidgetStatus.update(this, decks);
}