Search in sources :

Example 56 with JSONException

use of com.ichi2.utils.JSONException in project AnkiChinaAndroid by ankichinateam.

the class Statistics method selectDropDownItem.

private void selectDropDownItem(int position) {
    mActionBarSpinner.setSelection(position);
    if (position == 0) {
        mDeckId = Stats.ALL_DECKS_ID;
    } else {
        Deck deck = mDropDownDecks.get(position - 1);
        try {
            mDeckId = deck.getLong("id");
        } catch (JSONException e) {
            Timber.e(e, "Could not get ID from deck");
        }
    }
    mTaskHandler.setDeckId(mDeckId);
    mViewPager.getAdapter().notifyDataSetChanged();
}
Also used : Deck(com.ichi2.libanki.Deck) JSONException(com.ichi2.utils.JSONException)

Example 57 with JSONException

use of com.ichi2.utils.JSONException in project AnkiChinaAndroid by ankichinateam.

the class DeckOptions method onCreate.

@Override
// conversion to fragments tracked as #5019 in github
@SuppressWarnings("deprecation")
protected void onCreate(Bundle icicle) {
    Themes.setThemeLegacy(this);
    super.onCreate(icicle);
    mCol = CollectionHelper.getInstance().getCol(this);
    if (mCol == null) {
        finish();
        return;
    }
    Bundle extras = getIntent().getExtras();
    if (extras != null && extras.containsKey("did")) {
        mDeck = mCol.getDecks().get(extras.getLong("did"));
    } else {
        mDeck = mCol.getDecks().current();
    }
    registerExternalStorageListener();
    if (mCol == null) {
        Timber.w("DeckOptions - No Collection loaded");
        finish();
    } else {
        mPref = new DeckPreferenceHack();
        // #6068 - constructor can call finish()
        if (this.isFinishing()) {
            return;
        }
        mPref.registerOnSharedPreferenceChangeListener(this);
        this.addPreferencesFromResource(R.xml.deck_options);
        this.buildLists();
        this.updateSummaries();
        // Set the activity title to include the name of the deck
        String title = getResources().getString(R.string.deckpreferences_title);
        if (title.contains("XXX")) {
            try {
                title = title.replace("XXX", mDeck.getString("name"));
            } catch (JSONException e) {
                title = title.replace("XXX", "???");
            }
        }
        this.setTitle(title);
    }
    // Add a home button to the actionbar
    getSupportActionBar().setHomeButtonEnabled(true);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
Also used : Bundle(android.os.Bundle) JSONException(com.ichi2.utils.JSONException)

Example 58 with JSONException

use of com.ichi2.utils.JSONException in project AnkiChinaAndroid by ankichinateam.

the class DeckPicker method showStartupScreensAndDialogs.

public void showStartupScreensAndDialogs(SharedPreferences preferences, int skip) {
    if (!BackupManager.enoughDiscSpace(CollectionHelper.getCurrentAnkiDroidDirectory(this))) {
        Timber.i("Not enough space to do backup");
        showDialogFragment(DeckPickerNoSpaceLeftDialog.newInstance());
    } else if (preferences.getBoolean("noSpaceLeft", false)) {
        Timber.i("No space left");
        showDialogFragment(DeckPickerBackupNoSpaceLeftDialog.newInstance());
        preferences.edit().remove("noSpaceLeft").apply();
    } else if ("".equals(preferences.getString("lastVersion", ""))) {
        Timber.i("Fresh install");
        preferences.edit().putString("lastVersion", VersionUtils.getPkgVersionName()).apply();
        onFinishedStartup();
    } else if (skip < 2 && !preferences.getString("lastVersion", "").equals(VersionUtils.getPkgVersionName())) {
        Timber.i("AnkiDroid is being updated and a collection already exists.");
        // The user might appreciate us now, see if they will help us get better?
        if (!preferences.contains(UsageAnalytics.ANALYTICS_OPTIN_KEY)) {
            showDialogFragment(DeckPickerAnalyticsOptInDialog.newInstance());
        }
        // For upgrades, we check if we are upgrading
        // to a version that contains additions to the database integrity check routine that we would
        // like to run on all collections. A missing version number is assumed to be a fresh
        // installation of AnkiDroid and we don't run the check.
        long current = VersionUtils.getPkgVersionCode();
        Timber.i("Current AnkiDroid version: %s", current);
        long previous;
        if (preferences.contains(UPGRADE_VERSION_KEY)) {
            // Upgrading currently installed app
            previous = getPreviousVersion(preferences, current);
        } else {
            // Fresh install
            previous = current;
        }
        preferences.edit().putLong(UPGRADE_VERSION_KEY, current).apply();
        // It is rebuilt on the next sync or media check
        if (previous < 20300200) {
            Timber.i("Deleting media database");
            File mediaDb = new File(CollectionHelper.getCurrentAnkiDroidDirectory(this), "collection.media.ad.db2");
            if (mediaDb.exists()) {
                mediaDb.delete();
            }
        }
        // Recommend the user to do a full-sync if they're upgrading from before 2.3.1beta8
        if (previous < 20301208) {
            Timber.i("Recommend the user to do a full-sync");
            mRecommendFullSync = true;
        }
        // Fix "font-family" definition in templates created by AnkiDroid before 2.6alhpa23
        if (previous < 20600123) {
            Timber.i("Fixing font-family definition in templates");
            try {
                Models models = getCol().getModels();
                for (Model m : models.all()) {
                    String css = m.getString("css");
                    if (css.contains("font-familiy")) {
                        m.put("css", css.replace("font-familiy", "font-family"));
                        models.save(m);
                    }
                }
                models.flush();
            } catch (JSONException e) {
                Timber.e(e, "Failed to upgrade css definitions.");
            }
        }
        // Check if preference upgrade or database check required, otherwise go to new feature screen
        int upgradePrefsVersion = AnkiDroidApp.CHECK_PREFERENCES_AT_VERSION;
        int upgradeDbVersion = AnkiDroidApp.CHECK_DB_AT_VERSION;
        // Specifying a checkpoint in the future is not supported, please don't do it!
        if (current < upgradePrefsVersion) {
            Timber.e("Checkpoint in future produced.");
            UIUtils.showSimpleSnackbar(this, "Invalid value for CHECK_PREFERENCES_AT_VERSION", false);
            onFinishedStartup();
            return;
        }
        if (current < upgradeDbVersion) {
            Timber.e("Invalid value for CHECK_DB_AT_VERSION");
            UIUtils.showSimpleSnackbar(this, "Invalid value for CHECK_DB_AT_VERSION", false);
            onFinishedStartup();
            return;
        }
        // Skip full DB check if the basic check is OK
        // TODO: remove this variable if we really want to do the full db check on every user
        boolean skipDbCheck = false;
        // noinspection ConstantConditions
        if ((!skipDbCheck && previous < upgradeDbVersion) || previous < upgradePrefsVersion) {
            if (previous < upgradePrefsVersion) {
                Timber.i("showStartupScreensAndDialogs() running upgradePreferences()");
                upgradePreferences(previous);
            }
            // noinspection ConstantConditions
            if (!skipDbCheck && previous < upgradeDbVersion) {
                Timber.i("showStartupScreensAndDialogs() running integrityCheck()");
                // #5852 - since we may have a warning about disk space, we don't want to force a check database
                // and show a warning before the user knows what is happening.
                new MaterialDialog.Builder(this).title(R.string.integrity_check_startup_title).content(R.string.integrity_check_startup_content).positiveText(R.string.integrity_check_positive).negativeText(R.string.close).onPositive((materialDialog, dialogAction) -> integrityCheck()).onNeutral((materialDialog, dialogAction) -> this.restartActivity()).onNegative((materialDialog, dialogAction) -> this.restartActivity()).canceledOnTouchOutside(false).cancelable(false).build().show();
            } else if (previous < upgradePrefsVersion) {
                Timber.i("Updated preferences with no integrity check - restarting activity");
                // If integrityCheck() doesn't occur, but we did update preferences we should restart DeckPicker to
                // proceed
                this.restartActivity();
            }
        } else {
            // If no changes are required we go to the new features activity
            // There the "lastVersion" is set, so that this code is not reached again
            // if (VersionUtils.isReleaseVersion()) {
            // Timber.i("Displaying new features");
            // Intent infoIntent = new Intent(this, Info.class);
            // infoIntent.putExtra(Info.TYPE_EXTRA, Info.TYPE_NEW_VERSION);
            // 
            // if (skip != 0) {
            // startActivityForResultWithAnimation(infoIntent, SHOW_INFO_NEW_VERSION,
            // ActivityTransitionAnimation.LEFT);
            // } else {
            // startActivityForResultWithoutAnimation(infoIntent, SHOW_INFO_NEW_VERSION);
            // }
            // } else {
            Timber.i("Dev Build - not showing 'new features'");
            // Don't show new features dialog for development builds
            preferences.edit().putString("lastVersion", VersionUtils.getPkgVersionName()).apply();
            String ver = getResources().getString(R.string.updated_version, VersionUtils.getPkgVersionName());
            UIUtils.showSnackbar(this, ver, true, -1, null, findViewById(R.id.root_layout), null);
            showStartupScreensAndDialogs(preferences, 2);
        // }
        }
    } else {
        // this is the main call when there is nothing special required
        Timber.i("No startup screens required");
        onFinishedStartup();
    }
}
Also used : Bundle(android.os.Bundle) NonNull(androidx.annotation.NonNull) Uri(android.net.Uri) ImageView(android.widget.ImageView) ColorDrawable(android.graphics.drawable.ColorDrawable) DialogHandler(com.ichi2.anki.dialogs.DialogHandler) NavigationBarItemView(com.google.android.material.navigation.NavigationBarItemView) Manifest(android.Manifest) Decks(com.ichi2.libanki.Decks) Handler(android.os.Handler) JSONException(com.ichi2.utils.JSONException) Fragment(androidx.fragment.app.Fragment) ForegroundColorSpan(android.text.style.ForegroundColorSpan) ContextCompat(androidx.core.content.ContextCompat) DeckPickerBackupNoSpaceLeftDialog(com.ichi2.anki.dialogs.DeckPickerBackupNoSpaceLeftDialog) IntentFilter(android.content.IntentFilter) StringRes(androidx.annotation.StringRes) Nullable(androidx.annotation.Nullable) Message(android.os.Message) HostNumFactory(com.ichi2.anki.web.HostNumFactory) Consts(com.ichi2.libanki.Consts) OKHttpUtil(com.ichi2.utils.OKHttpUtil) MobclickAgent(com.umeng.analytics.MobclickAgent) DeckPickerExportCompleteDialog(com.ichi2.anki.dialogs.DeckPickerExportCompleteDialog) Models(com.ichi2.libanki.Models) SimpleDateFormat(java.text.SimpleDateFormat) Dialog(android.app.Dialog) SdCardReceiver(com.ichi2.anki.receiver.SdCardReceiver) URL_PRIVATE(com.ichi2.libanki.Consts.URL_PRIVATE) ArrayList(java.util.ArrayList) CustomSyncServerUrlException(com.ichi2.libanki.sync.CustomSyncServerUrlException) SpannableStringBuilder(android.text.SpannableStringBuilder) DeckPickerNoSpaceLeftDialog(com.ichi2.anki.dialogs.DeckPickerNoSpaceLeftDialog) Calendar(java.util.Calendar) Toast(android.widget.Toast) Menu(android.view.Menu) Connection(com.ichi2.async.Connection) Response(okhttp3.Response) AnkiPackageImporter(com.ichi2.libanki.importer.AnkiPackageImporter) Call(okhttp3.Call) CHECK_MEDIA(com.ichi2.async.CollectionTask.TASK_TYPE.CHECK_MEDIA) FragmentManager(androidx.fragment.app.FragmentManager) Beta(com.tencent.bugly.beta.Beta) SpannableString(android.text.SpannableString) ALL_DECKS_ID(com.ichi2.anki.SelfStudyActivity.ALL_DECKS_ID) URL_USER_PROTOCOL(com.ichi2.libanki.Consts.URL_USER_PROTOCOL) TextUtils(android.text.TextUtils) IOException(java.io.IOException) File(java.io.File) Gravity(android.view.Gravity) SharedPreferences(android.content.SharedPreferences) TypedValue(android.util.TypedValue) ActivityTransitionAnimation(com.ichi2.anim.ActivityTransitionAnimation) EditText(android.widget.EditText) AsyncDialogFragment(com.ichi2.anki.dialogs.AsyncDialogFragment) PackageManager(android.content.pm.PackageManager) Date(java.util.Date) WindowManager(android.view.WindowManager) UnderlineSpan(android.text.style.UnderlineSpan) UsageAnalytics(com.ichi2.anki.analytics.UsageAnalytics) ClickableSpan(android.text.style.ClickableSpan) ExportDialog(com.ichi2.anki.dialogs.ExportDialog) DeviceID(com.ichi2.libanki.DeviceID) ConfirmationDialog(com.ichi2.anki.dialogs.ConfirmationDialog) Permissions(com.ichi2.utils.Permissions) AnkiChinaSyncer(com.ichi2.libanki.sync.AnkiChinaSyncer) JSONObject(org.json.JSONObject) NOT_LOGIN_ANKI_CHINA(com.ichi2.anki.MyAccount.NOT_LOGIN_ANKI_CHINA) View(android.view.View) TaskData(com.ichi2.async.TaskData) SyncStatus(com.ichi2.utils.SyncStatus) FIND_EMPTY_CARDS(com.ichi2.async.CollectionTask.TASK_TYPE.FIND_EMPTY_CARDS) ParseException(java.text.ParseException) BottomNavigationView(com.google.android.material.bottomnavigation.BottomNavigationView) BroadcastReceiver(android.content.BroadcastReceiver) DatabaseErrorDialog(com.ichi2.anki.dialogs.DatabaseErrorDialog) DisplayMetrics(android.util.DisplayMetrics) ViewGroup(android.view.ViewGroup) Timber(timber.log.Timber) List(java.util.List) TextView(android.widget.TextView) RelativeLayout(android.widget.RelativeLayout) TaskListenerWithContext(com.ichi2.async.TaskListenerWithContext) ViewPropertyAnimator(android.view.ViewPropertyAnimator) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) Window(android.view.Window) VersionUtils(com.ichi2.utils.VersionUtils) Context(android.content.Context) TaskListener(com.ichi2.async.TaskListener) Spanned(android.text.Spanned) KeyEvent(android.view.KeyEvent) GravityEnum(com.afollestad.materialdialogs.GravityEnum) DeckPickerAnalyticsOptInDialog(com.ichi2.anki.dialogs.DeckPickerAnalyticsOptInDialog) Intent(android.content.Intent) ViewPager2(androidx.viewpager2.widget.ViewPager2) Collection(com.ichi2.libanki.Collection) StyledProgressDialog(com.ichi2.themes.StyledProgressDialog) MenuItem(android.view.MenuItem) FragmentStateAdapter(androidx.viewpager2.adapter.FragmentStateAdapter) CHECK_DATABASE(com.ichi2.async.CollectionTask.TASK_TYPE.CHECK_DATABASE) Lifecycle(androidx.lifecycle.Lifecycle) REPAIR_COLLECTION(com.ichi2.async.CollectionTask.TASK_TYPE.REPAIR_COLLECTION) WidgetStatus(com.ichi2.widget.WidgetStatus) MotionEvent(android.view.MotionEvent) SyncErrorDialog(com.ichi2.anki.dialogs.SyncErrorDialog) Model(com.ichi2.libanki.Model) ConfirmModSchemaException(com.ichi2.anki.exception.ConfirmModSchemaException) Bugly(com.tencent.bugly.Bugly) LOAD_COLLECTION_COMPLETE(com.ichi2.async.CollectionTask.TASK_TYPE.LOAD_COLLECTION_COMPLETE) UMConfigure(com.umeng.commonsdk.UMConfigure) PlatformConfig(com.umeng.socialize.PlatformConfig) ActivityCompat(androidx.core.app.ActivityCompat) CollectionTask(com.ichi2.async.CollectionTask) BottomNavigationMenuView(com.google.android.material.bottomnavigation.BottomNavigationMenuView) Color(android.graphics.Color) MediaCheckDialog(com.ichi2.anki.dialogs.MediaCheckDialog) LOAD_DECK_COUNTS(com.ichi2.async.CollectionTask.TASK_TYPE.LOAD_DECK_COUNTS) VisibleForTesting(androidx.annotation.VisibleForTesting) CustomStyleDialog(com.ichi2.ui.CustomStyleDialog) Resources(android.content.res.Resources) SpannableStringBuilder(android.text.SpannableStringBuilder) Model(com.ichi2.libanki.Model) JSONException(com.ichi2.utils.JSONException) Models(com.ichi2.libanki.Models) SpannableString(android.text.SpannableString) File(java.io.File)

Example 59 with JSONException

use of com.ichi2.utils.JSONException in project AnkiChinaAndroid by ankichinateam.

the class CardBrowser method onOptionsItemSelected.

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // (when another operation will be performed on the model, it will undo the latest operation)
    if (mUndoSnackbar != null && mUndoSnackbar.isShown()) {
        mUndoSnackbar.dismiss();
    }
    switch(item.getItemId()) {
        case android.R.id.home:
            endMultiSelectMode();
            return true;
        case R.id.action_add_note_from_card_browser:
            {
                Intent intent = new Intent(CardBrowser.this, NoteEditor.class);
                intent.putExtra(NoteEditor.EXTRA_CALLER, NoteEditor.CALLER_CARDBROWSER_ADD);
                startActivityForResultWithAnimation(intent, ADD_NOTE, ActivityTransitionAnimation.LEFT);
                return true;
            }
        case R.id.action_save_search:
            {
                String searchTerms = mSearchView.getQuery().toString();
                showDialogFragment(CardBrowserMySearchesDialog.newInstance(null, mMySearchesDialogListener, searchTerms, CardBrowserMySearchesDialog.CARD_BROWSER_MY_SEARCHES_TYPE_SAVE));
                return true;
            }
        case R.id.action_list_my_searches:
            {
                JSONObject savedFiltersObj = getCol().getConf().optJSONObject("savedFilters");
                HashMap<String, String> savedFilters = new HashMap<>();
                if (savedFiltersObj != null) {
                    Iterator<String> it = savedFiltersObj.keys();
                    while (it.hasNext()) {
                        String searchName = it.next();
                        savedFilters.put(searchName, savedFiltersObj.optString(searchName));
                    }
                }
                showDialogFragment(CardBrowserMySearchesDialog.newInstance(savedFilters, mMySearchesDialogListener, "", CardBrowserMySearchesDialog.CARD_BROWSER_MY_SEARCHES_TYPE_LIST));
                return true;
            }
        case R.id.action_sort_by_size:
            showDialogFragment(CardBrowserOrderDialog.newInstance(mOrder, mOrderAsc, mOrderDialogListener));
            return true;
        case R.id.action_show_marked:
            mSearchTerms = "tag:marked";
            mSearchView.setQuery("", false);
            mSearchView.setQueryHint(getResources().getString(R.string.card_browser_show_marked));
            searchCards();
            return true;
        case R.id.action_show_suspended:
            mSearchTerms = "is:suspended";
            mSearchView.setQuery("", false);
            mSearchView.setQueryHint(getResources().getString(R.string.card_browser_show_suspended));
            searchCards();
            return true;
        case R.id.action_search_by_tag:
            showTagsDialog();
            return true;
        case R.id.action_flag_zero:
            flagTask(0);
            return true;
        case R.id.action_flag_one:
            flagTask(1);
            return true;
        case R.id.action_flag_two:
            flagTask(2);
            return true;
        case R.id.action_flag_three:
            flagTask(3);
            return true;
        case R.id.action_flag_four:
            flagTask(4);
            return true;
        case R.id.action_delete_card:
            if (mInMultiSelectMode) {
                CollectionTask.launchCollectionTask(DISMISS_MULTI, mDeleteNoteHandler, new TaskData(new Object[] { getSelectedCardIds(), Collection.DismissType.DELETE_NOTE_MULTI }));
                mCheckedCards.clear();
                endMultiSelectMode();
                mCardsAdapter.notifyDataSetChanged();
            }
            return true;
        case R.id.action_mark_card:
            CollectionTask.launchCollectionTask(DISMISS_MULTI, markCardHandler(), new TaskData(new Object[] { getSelectedCardIds(), Collection.DismissType.MARK_NOTE_MULTI }));
            return true;
        case R.id.action_suspend_card:
            CollectionTask.launchCollectionTask(DISMISS_MULTI, suspendCardHandler(), new TaskData(new Object[] { getSelectedCardIds(), Collection.DismissType.SUSPEND_CARD_MULTI }));
            return true;
        case R.id.action_change_deck:
            {
                AlertDialog.Builder builderSingle = new AlertDialog.Builder(this);
                builderSingle.setTitle(getString(R.string.move_all_to_deck));
                // WARNING: changeDeck depends on this index, so any changes should be reflected there.
                final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, R.layout.dropdown_deck_item);
                for (Deck deck : getValidDecksForChangeDeck()) {
                    try {
                        arrayAdapter.add(deck.getString("name"));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                builderSingle.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builderSingle.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        changeDeck(which);
                    }
                });
                builderSingle.show();
                return true;
            }
        case R.id.action_undo:
            if (getCol().undoAvailable()) {
                CollectionTask.launchCollectionTask(UNDO, mUndoHandler);
            }
            return true;
        case R.id.action_select_none:
            onSelectNone();
            return true;
        case R.id.action_select_all:
            onSelectAll();
            return true;
        case R.id.action_preview:
            {
                Intent previewer = new Intent(CardBrowser.this, Previewer.class);
                if (mInMultiSelectMode && checkedCardCount() > 1) {
                    // Multiple cards have been explicitly selected, so preview only those cards
                    previewer.putExtra("index", 0);
                    previewer.putExtra("cardList", getSelectedCardIds());
                } else {
                    // Preview all cards, starting from the one that is currently selected
                    int startIndex = mCheckedCards.isEmpty() ? 0 : mCheckedCards.iterator().next().getPosition();
                    previewer.putExtra("index", startIndex);
                    previewer.putExtra("cardList", getAllCardIds());
                }
                startActivityForResultWithoutAnimation(previewer, PREVIEW_CARDS);
                return true;
            }
        case R.id.action_reset_cards_progress:
            {
                Timber.i("NoteEditor:: Reset progress button pressed");
                // Show confirmation dialog before resetting card progress
                ConfirmationDialog dialog = new ConfirmationDialog();
                String title = getString(R.string.reset_card_dialog_title);
                String message = getString(R.string.reset_card_dialog_message);
                dialog.setArgs(title, message);
                Runnable confirm = () -> {
                    Timber.i("CardBrowser:: ResetProgress button pressed");
                    CollectionTask.launchCollectionTask(DISMISS_MULTI, resetProgressCardHandler(), new TaskData(new Object[] { getSelectedCardIds(), Collection.DismissType.RESET_CARDS }));
                };
                dialog.setConfirm(confirm);
                showDialogFragment(dialog);
                return true;
            }
        case R.id.action_reschedule_cards:
            {
                Timber.i("CardBrowser:: Reschedule button pressed");
                long[] selectedCardIds = getSelectedCardIds();
                FunctionalInterfaces.Consumer<Integer> consumer = newDays -> CollectionTask.launchCollectionTask(DISMISS_MULTI, rescheduleCardHandler(), new TaskData(new Object[] { selectedCardIds, Collection.DismissType.RESCHEDULE_CARDS, newDays }));
                RescheduleDialog rescheduleDialog;
                if (selectedCardIds.length == 1) {
                    long cardId = selectedCardIds[0];
                    Card selected = getCol().getCard(cardId);
                    rescheduleDialog = RescheduleDialog.rescheduleSingleCard(getResources(), selected, consumer);
                } else {
                    rescheduleDialog = RescheduleDialog.rescheduleMultipleCards(getResources(), consumer, selectedCardIds.length);
                }
                showDialogFragment(rescheduleDialog);
                return true;
            }
        case R.id.action_reposition_cards:
            {
                Timber.i("CardBrowser:: Reposition button pressed");
                // Only new cards may be repositioned
                long[] cardIds = getSelectedCardIds();
                for (int i = 0; i < cardIds.length; i++) {
                    if (getCol().getCard(cardIds[i]).getQueue() != Consts.CARD_TYPE_NEW) {
                        SimpleMessageDialog dialog = SimpleMessageDialog.newInstance(getString(R.string.vague_error), getString(R.string.reposition_card_not_new_error), false);
                        showDialogFragment(dialog);
                        return false;
                    }
                }
                IntegerDialog repositionDialog = new IntegerDialog();
                repositionDialog.setArgs(getString(R.string.reposition_card_dialog_title), getString(R.string.reposition_card_dialog_message), 5);
                repositionDialog.setCallbackRunnable(days -> CollectionTask.launchCollectionTask(DISMISS_MULTI, repositionCardHandler(), new TaskData(new Object[] { cardIds, Collection.DismissType.REPOSITION_CARDS, days })));
                showDialogFragment(repositionDialog);
                return true;
            }
        case R.id.action_edit_note:
            {
                openNoteEditorForCurrentlySelectedNote();
            }
        default:
            return super.onOptionsItemSelected(item);
    }
}
Also used : AlertDialog(android.app.AlertDialog) Arrays(java.util.Arrays) Bundle(android.os.Bundle) TagsDialog(com.ichi2.anki.dialogs.TagsDialog) Deck(com.ichi2.libanki.Deck) NonNull(androidx.annotation.NonNull) WindowManager(android.view.WindowManager) Compat(com.ichi2.compat.Compat) ConfirmationDialog(com.ichi2.anki.dialogs.ConfirmationDialog) Permissions(com.ichi2.utils.Permissions) FunctionalInterfaces(com.ichi2.utils.FunctionalInterfaces) ActionBar(androidx.appcompat.app.ActionBar) Decks(com.ichi2.libanki.Decks) CheckBox(android.widget.CheckBox) Locale(java.util.Locale) Handler(android.os.Handler) Map(java.util.Map) JSONException(com.ichi2.utils.JSONException) View(android.view.View) TaskData(com.ichi2.async.TaskData) AdapterView(android.widget.AdapterView) Media(com.ichi2.libanki.Media) CardBrowserMySearchesDialog(com.ichi2.anki.dialogs.CardBrowserMySearchesDialog) Upgrade(com.ichi2.upgrade.Upgrade) IntentFilter(android.content.IntentFilter) Set(java.util.Set) SearchView(androidx.appcompat.widget.SearchView) JSONObject(com.ichi2.utils.JSONObject) BroadcastReceiver(android.content.BroadcastReceiver) ViewGroup(android.view.ViewGroup) Timber(timber.log.Timber) AlertDialog(android.app.AlertDialog) Objects(java.util.Objects) List(java.util.List) Nullable(androidx.annotation.Nullable) TextView(android.widget.TextView) OnItemSelectedListener(android.widget.AdapterView.OnItemSelectedListener) BaseAdapter(android.widget.BaseAdapter) Consts(com.ichi2.libanki.Consts) CompatHelper(com.ichi2.compat.CompatHelper) Toolbar(androidx.appcompat.widget.Toolbar) TaskListenerWithContext(com.ichi2.async.TaskListenerWithContext) ListView(android.widget.ListView) Pattern(java.util.regex.Pattern) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) Snackbar(com.google.android.material.snackbar.Snackbar) Typeface(android.graphics.Typeface) Context(android.content.Context) Pair(android.util.Pair) Intent(android.content.Intent) SystemClock(android.os.SystemClock) RescheduleDialog(com.ichi2.anki.dialogs.RescheduleDialog) HashMap(java.util.HashMap) SdCardReceiver(com.ichi2.anki.receiver.SdCardReceiver) Collection(com.ichi2.libanki.Collection) Column(com.ichi2.anki.CardBrowser.Column) MenuItem(android.view.MenuItem) ArrayList(java.util.ArrayList) TASK_TYPE(com.ichi2.async.CollectionTask.TASK_TYPE) HashSet(java.util.HashSet) DeckDropDownAdapter(com.ichi2.anki.widgets.DeckDropDownAdapter) WidgetStatus(com.ichi2.widget.WidgetStatus) Menu(android.view.Menu) SimpleMessageDialog(com.ichi2.anki.dialogs.SimpleMessageDialog) Utils(com.ichi2.libanki.Utils) LinkedHashSet(java.util.LinkedHashSet) DialogInterface(android.content.DialogInterface) IntegerDialog(com.ichi2.anki.dialogs.IntegerDialog) CheckResult(androidx.annotation.CheckResult) Iterator(java.util.Iterator) LayoutInflater(android.view.LayoutInflater) TextUtils(android.text.TextUtils) AbsListView(android.widget.AbsListView) CollectionTask(com.ichi2.async.CollectionTask) Themes(com.ichi2.themes.Themes) Spinner(android.widget.Spinner) ArrayAdapter(android.widget.ArrayAdapter) SharedPreferences(android.content.SharedPreferences) TypedValue(android.util.TypedValue) SECONDS_PER_DAY(com.ichi2.libanki.stats.Stats.SECONDS_PER_DAY) LanguageUtil(com.ichi2.utils.LanguageUtil) Card(com.ichi2.libanki.Card) VisibleForTesting(androidx.annotation.VisibleForTesting) ActivityTransitionAnimation(com.ichi2.anim.ActivityTransitionAnimation) Collections(java.util.Collections) CardBrowserOrderDialog(com.ichi2.anki.dialogs.CardBrowserOrderDialog) HashMap(java.util.HashMap) DialogInterface(android.content.DialogInterface) TaskData(com.ichi2.async.TaskData) ConfirmationDialog(com.ichi2.anki.dialogs.ConfirmationDialog) RescheduleDialog(com.ichi2.anki.dialogs.RescheduleDialog) Iterator(java.util.Iterator) SimpleMessageDialog(com.ichi2.anki.dialogs.SimpleMessageDialog) Deck(com.ichi2.libanki.Deck) JSONException(com.ichi2.utils.JSONException) Intent(android.content.Intent) Card(com.ichi2.libanki.Card) JSONObject(com.ichi2.utils.JSONObject) IntegerDialog(com.ichi2.anki.dialogs.IntegerDialog) JSONObject(com.ichi2.utils.JSONObject) ArrayAdapter(android.widget.ArrayAdapter)

Example 60 with JSONException

use of com.ichi2.utils.JSONException in project AnkiChinaAndroid by ankichinateam.

the class AbstractFlashcardViewer method restoreCollectionPreferences.

protected void restoreCollectionPreferences() {
    // These are preferences we pull out of the collection instead of SharedPreferences
    try {
        mShowNextReviewTime = getCol().getConf().getBoolean("estTimes");
        // Dynamic don't have review options; attempt to get deck-specific auto-advance options
        // but be prepared to go with all default if it's a dynamic deck
        JSONObject revOptions = new JSONObject();
        long selectedDid = getCol().getDecks().selected();
        if (!getCol().getDecks().isDyn(selectedDid)) {
            revOptions = getCol().getDecks().confForDid(selectedDid).getJSONObject("rev");
        }
        mOptUseGeneralTimerSettings = revOptions.optBoolean("useGeneralTimeoutSettings", true);
        mOptUseTimer = revOptions.optBoolean("timeoutAnswer", false);
        mOptWaitAnswerSecond = revOptions.optInt("timeoutAnswerSeconds", 20);
        mOptWaitQuestionSecond = revOptions.optInt("timeoutQuestionSeconds", 60);
    } catch (JSONException e) {
        Timber.e(e, "Unable to restoreCollectionPreferences");
        throw new RuntimeException(e);
    } catch (NullPointerException npe) {
        // NPE on collection only happens if the Collection is broken, follow AnkiActivity example
        Intent deckPicker = new Intent(this, DeckPicker.class);
        // don't currently do anything with this
        deckPicker.putExtra("collectionLoadError", true);
        deckPicker.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivityWithAnimation(deckPicker, ActivityTransitionAnimation.LEFT);
    }
}
Also used : JSONObject(com.ichi2.utils.JSONObject) JSONException(com.ichi2.utils.JSONException) Intent(android.content.Intent)

Aggregations

JSONException (com.ichi2.utils.JSONException)54 JSONObject (com.ichi2.utils.JSONObject)41 JSONException (org.json.JSONException)28 Collection (com.ichi2.libanki.Collection)25 ArrayList (java.util.ArrayList)25 JSONObject (org.json.JSONObject)22 JSONArray (com.ichi2.utils.JSONArray)21 SuppressLint (android.annotation.SuppressLint)18 IOException (java.io.IOException)17 File (java.io.File)16 Note (com.ichi2.libanki.Note)14 ConfirmModSchemaException (com.ichi2.anki.exception.ConfirmModSchemaException)12 HashMap (java.util.HashMap)12 Bundle (android.os.Bundle)11 Deck (com.ichi2.libanki.Deck)11 Resources (android.content.res.Resources)10 Model (com.ichi2.libanki.Model)10 Map (java.util.Map)10 List (java.util.List)9 Context (android.content.Context)8