Search in sources :

Example 1 with ConfirmModSchemaException

use of com.ichi2.anki.exception.ConfirmModSchemaException in project AnkiChinaAndroid by ankichinateam.

the class ModelBrowser method deleteModelDialog.

/*
     * Displays a confirmation box asking if you want to delete the note type and then deletes it if confirmed
     */
private void deleteModelDialog() {
    if (mModelIds.size() > 1) {
        Runnable confirm = new Runnable() {

            @Override
            public void run() {
                col.modSchemaNoCheck();
                try {
                    deleteModel();
                } catch (ConfirmModSchemaException e) {
                // This should never be reached because modSchema() didn't throw an exception
                }
                dismissContextMenu();
            }
        };
        Runnable cancel = new Runnable() {

            @Override
            public void run() {
                dismissContextMenu();
            }
        };
        try {
            col.modSchema();
            ConfirmationDialog d = new ConfirmationDialog();
            d.setArgs(getResources().getString(R.string.model_delete_warning));
            d.setConfirm(confirm);
            d.setCancel(cancel);
            ModelBrowser.this.showDialogFragment(d);
        } catch (ConfirmModSchemaException e) {
            ConfirmationDialog c = new ConfirmationDialog();
            c.setArgs(getResources().getString(R.string.full_sync_confirmation));
            c.setConfirm(confirm);
            c.setCancel(cancel);
            showDialogFragment(c);
        }
    } else // Prevent users from deleting last model
    {
        showToast(getString(R.string.toast_last_model));
    }
}
Also used : ConfirmModSchemaException(com.ichi2.anki.exception.ConfirmModSchemaException) ConfirmationDialog(com.ichi2.anki.dialogs.ConfirmationDialog)

Example 2 with ConfirmModSchemaException

use of com.ichi2.anki.exception.ConfirmModSchemaException in project AnkiChinaAndroid by ankichinateam.

the class ModelFieldEditor method deleteFieldDialog.

/*
     * Creates a dialog to delete the currently selected field
     */
private void deleteFieldDialog() {
    Runnable confirm = () -> {
        mCol.modSchemaNoCheck();
        deleteField();
        dismissContextMenu();
    };
    if (mFieldLabels.size() < 2) {
        UIUtils.showThemedToast(this, getResources().getString(R.string.toast_last_field), true);
    } else {
        try {
            mCol.modSchema();
            ConfirmationDialog d = new ConfirmationDialog();
            d.setArgs(getResources().getString(R.string.field_delete_warning));
            d.setConfirm(confirm);
            d.setCancel(mConfirmDialogCancel);
            showDialogFragment(d);
        } catch (ConfirmModSchemaException e) {
            ConfirmationDialog c = new ConfirmationDialog();
            c.setConfirm(confirm);
            c.setCancel(mConfirmDialogCancel);
            c.setArgs(getResources().getString(R.string.full_sync_confirmation));
            showDialogFragment(c);
        }
    }
}
Also used : ConfirmModSchemaException(com.ichi2.anki.exception.ConfirmModSchemaException) ConfirmationDialog(com.ichi2.anki.dialogs.ConfirmationDialog)

Example 3 with ConfirmModSchemaException

use of com.ichi2.anki.exception.ConfirmModSchemaException in project AnkiChinaAndroid by ankichinateam.

the class ModelFieldEditor method addFieldDialog.

// ----------------------------------------------------------------------------
// CONTEXT MENU DIALOGUES
// ----------------------------------------------------------------------------
/*
    * Creates a dialog to create a field
    */
private void addFieldDialog() {
    mFieldNameInput = new EditText(this);
    mFieldNameInput.setSingleLine(true);
    new MaterialDialog.Builder(this).title(R.string.model_field_editor_add).positiveText(R.string.dialog_ok).customView(mFieldNameInput, true).onPositive((dialog, which) -> {
        String fieldName = mFieldNameInput.getText().toString().replaceAll("[\\n\\r]", "");
        if (fieldName.length() == 0) {
            UIUtils.showThemedToast(this, getResources().getString(R.string.toast_empty_name), true);
        } else if (containsField(fieldName)) {
            UIUtils.showThemedToast(this, getResources().getString(R.string.toast_duplicate_field), true);
        } else {
            // Name is valid, now field is added
            changeHandler listener = changeFieldHandler();
            try {
                mCol.modSchema();
                CollectionTask.launchCollectionTask(ADD_FIELD, listener, new TaskData(new Object[] { mMod, fieldName }));
            } catch (ConfirmModSchemaException e) {
                // Create dialogue to for schema change
                ConfirmationDialog c = new ConfirmationDialog();
                c.setArgs(getResources().getString(R.string.full_sync_confirmation));
                Runnable confirm = () -> {
                    mCol.modSchemaNoCheck();
                    String fieldName1 = mFieldNameInput.getText().toString().replaceAll("[\\n\\r]", "");
                    CollectionTask.launchCollectionTask(ADD_FIELD, listener, new TaskData(new Object[] { mMod, fieldName1 }));
                    dismissContextMenu();
                };
                c.setConfirm(confirm);
                c.setCancel(mConfirmDialogCancel);
                ModelFieldEditor.this.showDialogFragment(c);
            }
            mCol.getModels().update(mMod);
            fullRefreshList();
        }
    }).negativeText(R.string.dialog_cancel).show();
}
Also used : EditText(android.widget.EditText) ConfirmModSchemaException(com.ichi2.anki.exception.ConfirmModSchemaException) TaskData(com.ichi2.async.TaskData) ConfirmationDialog(com.ichi2.anki.dialogs.ConfirmationDialog)

Example 4 with ConfirmModSchemaException

use of com.ichi2.anki.exception.ConfirmModSchemaException in project AnkiChinaAndroid by ankichinateam.

the class ModelFieldEditor method repositionFieldDialog.

/*
     * Allows the user to select a number less than the number of fields in the current model to
     * reposition the current field to
     * Processing time is scales with number of items
     */
private void repositionFieldDialog() {
    mFieldNameInput = new EditText(this);
    mFieldNameInput.setRawInputType(InputType.TYPE_CLASS_NUMBER);
    new MaterialDialog.Builder(this).title(String.format(getResources().getString(R.string.model_field_editor_reposition), 1, mFieldLabels.size())).positiveText(R.string.dialog_ok).customView(mFieldNameInput, true).onPositive((dialog, which) -> {
        String newPosition = mFieldNameInput.getText().toString();
        int pos;
        try {
            pos = Integer.parseInt(newPosition);
        } catch (NumberFormatException n) {
            UIUtils.showThemedToast(this, getResources().getString(R.string.toast_out_of_range), true);
            return;
        }
        if (pos < 1 || pos > mFieldLabels.size()) {
            UIUtils.showThemedToast(this, getResources().getString(R.string.toast_out_of_range), true);
        } else {
            changeHandler listener = changeFieldHandler();
            // Input is valid, now attempt to modify
            try {
                mCol.modSchema();
                CollectionTask.launchCollectionTask(REPOSITION_FIELD, listener, new TaskData(new Object[] { mMod, mNoteFields.getJSONObject(mCurrentPos), pos - 1 }));
            } catch (ConfirmModSchemaException e) {
                // Handle mod schema confirmation
                ConfirmationDialog c = new ConfirmationDialog();
                c.setArgs(getResources().getString(R.string.full_sync_confirmation));
                Runnable confirm = () -> {
                    try {
                        mCol.modSchemaNoCheck();
                        String newPosition1 = mFieldNameInput.getText().toString();
                        int pos1 = Integer.parseInt(newPosition1);
                        CollectionTask.launchCollectionTask(REPOSITION_FIELD, listener, new TaskData(new Object[] { mMod, mNoteFields.getJSONObject(mCurrentPos), pos1 - 1 }));
                        dismissContextMenu();
                    } catch (JSONException e1) {
                        throw new RuntimeException(e1);
                    }
                };
                c.setConfirm(confirm);
                c.setCancel(mConfirmDialogCancel);
                ModelFieldEditor.this.showDialogFragment(c);
            }
        }
    }).negativeText(R.string.dialog_cancel).show();
}
Also used : EditText(android.widget.EditText) JSONException(com.ichi2.utils.JSONException) TaskData(com.ichi2.async.TaskData) ConfirmationDialog(com.ichi2.anki.dialogs.ConfirmationDialog) ConfirmModSchemaException(com.ichi2.anki.exception.ConfirmModSchemaException) JSONObject(com.ichi2.utils.JSONObject)

Example 5 with ConfirmModSchemaException

use of com.ichi2.anki.exception.ConfirmModSchemaException in project AnkiChinaAndroid by ankichinateam.

the class Preferences method updatePreference.

/**
 * Code which is run when a SharedPreference change has been detected
 * @param prefs instance of SharedPreferences
 * @param key key in prefs which is being updated
 * @param listener android.preference.PreferenceActivity of PreferenceFragment which is hosting the preference
 */
// Tracked as #5019 on github - convert to fragments
@SuppressWarnings("deprecation")
private void updatePreference(SharedPreferences prefs, String key, PreferenceContext listener) {
    try {
        android.preference.PreferenceScreen screen = listener.getPreferenceScreen();
        android.preference.Preference pref = screen.findPreference(key);
        if (pref == null) {
            Timber.e("Preferences: no preference found for the key: %s", key);
            return;
        }
        // Handle special cases
        switch(key) {
            case CustomSyncServer.PREFERENCE_CUSTOM_MEDIA_SYNC_URL:
            case CustomSyncServer.PREFERENCE_CUSTOM_SYNC_BASE:
            case CustomSyncServer.PREFERENCE_ENABLE_CUSTOM_SYNC_SERVER:
                // This may be a tad hasty - performed before "back" is pressed.
                CustomSyncServer.handleSyncServerPreferenceChange(getBaseContext());
                break;
            case "timeoutAnswer":
                {
                    android.preference.CheckBoxPreference keepScreenOn = (android.preference.CheckBoxPreference) screen.findPreference("keepScreenOn");
                    keepScreenOn.setChecked(((android.preference.CheckBoxPreference) pref).isChecked());
                    break;
                }
            case LANGUAGE:
                closePreferences();
                break;
            case "showProgress":
                getCol().getConf().put("dueCounts", ((android.preference.CheckBoxPreference) pref).isChecked());
                getCol().setMod();
                break;
            case "showEstimates":
                getCol().getConf().put("estTimes", ((android.preference.CheckBoxPreference) pref).isChecked());
                getCol().setMod();
                break;
            case "newSpread":
                getCol().getConf().put("newSpread", Integer.parseInt(((android.preference.ListPreference) pref).getValue()));
                getCol().setMod();
                break;
            case "timeLimit":
                getCol().getConf().put("timeLim", ((NumberRangePreference) pref).getValue() * 60);
                getCol().setMod();
                break;
            case "learnCutoff":
                getCol().getConf().put("collapseTime", ((NumberRangePreference) pref).getValue() * 60);
                getCol().setMod();
                break;
            case "useCurrent":
                getCol().getConf().put("addToCur", "0".equals(((android.preference.ListPreference) pref).getValue()));
                getCol().setMod();
                break;
            case "dayOffset":
                {
                    int hours = ((SeekBarPreference) pref).getValue();
                    Calendar date = getCol().crtGregorianCalendar();
                    date.set(Calendar.HOUR_OF_DAY, hours);
                    getCol().setCrt(date.getTimeInMillis() / 1000);
                    getCol().setMod();
                    BootService.scheduleNotification(getCol().getTime(), this);
                    break;
                }
            case "minimumCardsDueForNotification":
                {
                    android.preference.ListPreference listpref = (android.preference.ListPreference) screen.findPreference("minimumCardsDueForNotification");
                    if (listpref != null) {
                        updateNotificationPreference(listpref);
                        if (Integer.valueOf(listpref.getValue()) < PENDING_NOTIFICATIONS_ONLY) {
                            BootService.scheduleNotification(getCol().getTime(), this);
                        } else {
                            PendingIntent intent = PendingIntent.getBroadcast(this, 0, new Intent(this, NotificationService.class), 0);
                            final AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
                            alarmManager.cancel(intent);
                        }
                    }
                    break;
                }
            case AnkiDroidApp.FEEDBACK_REPORT_KEY:
                {
                    String value = prefs.getString(AnkiDroidApp.FEEDBACK_REPORT_KEY, "");
                    AnkiDroidApp.getInstance().setAcraReportingMode(value);
                    // If the user changed error reporting, make sure future reports have a chance to post
                    AnkiDroidApp.deleteACRALimiterData(this);
                    // We also need to re-chain our UncaughtExceptionHandlers
                    UsageAnalytics.reInitialize();
                    break;
                }
            case "syncAccount":
                {
                    SharedPreferences preferences = AnkiDroidApp.getSharedPrefs(getBaseContext());
                    String username = preferences.getString("username", "");
                    android.preference.Preference syncAccount = screen.findPreference("syncAccount");
                    if (syncAccount != null) {
                        if (TextUtils.isEmpty(username)) {
                            syncAccount.setSummary(R.string.sync_account_summ_logged_out);
                        } else {
                            syncAccount.setSummary(getString(R.string.sync_account_summ_logged_in, username));
                        }
                    }
                    break;
                }
            case "providerEnabled":
                {
                    ComponentName providerName = new ComponentName(this, "com.ichi2.anki.provider.CardContentProvider");
                    PackageManager pm = getPackageManager();
                    int state;
                    if (((android.preference.CheckBoxPreference) pref).isChecked()) {
                        state = PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
                        Timber.i("AnkiDroid ContentProvider enabled by user");
                    } else {
                        state = PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
                        Timber.i("AnkiDroid ContentProvider disabled by user");
                    }
                    pm.setComponentEnabledSetting(providerName, state, PackageManager.DONT_KILL_APP);
                    break;
                }
            case "schedVer":
                {
                    boolean wantNew = ((android.preference.CheckBoxPreference) pref).isChecked();
                    boolean haveNew = getCol().schedVer() == 2;
                    // northing to do?
                    if (haveNew == wantNew) {
                        break;
                    }
                    MaterialDialog.Builder builder = new MaterialDialog.Builder(this);
                    if (haveNew && !wantNew) {
                        // Going back to V1
                        builder.title(R.string.sched_ver_toggle_title);
                        builder.content(R.string.sched_ver_2to1);
                        builder.onPositive((dialog, which) -> {
                            getCol().modSchemaNoCheck();
                            try {
                                getCol().changeSchedulerVer(1);
                                ((android.preference.CheckBoxPreference) pref).setChecked(false);
                            } catch (ConfirmModSchemaException e2) {
                                // This should never be reached as we explicitly called modSchemaNoCheck()
                                throw new RuntimeException(e2);
                            }
                        });
                        builder.onNegative((dialog, which) -> {
                            ((android.preference.CheckBoxPreference) pref).setChecked(true);
                        });
                        builder.positiveText(R.string.dialog_ok);
                        builder.negativeText(R.string.dialog_cancel);
                        builder.show();
                        break;
                    }
                    // Going to V2
                    builder.title(R.string.sched_ver_toggle_title);
                    builder.content(R.string.sched_ver_1to2);
                    builder.onPositive((dialog, which) -> {
                        getCol().modSchemaNoCheck();
                        try {
                            getCol().changeSchedulerVer(2);
                            ((android.preference.CheckBoxPreference) pref).setChecked(true);
                        } catch (ConfirmModSchemaException e2) {
                            // This should never be reached as we explicitly called modSchemaNoCheck()
                            throw new RuntimeException(e2);
                        }
                    });
                    builder.onNegative((dialog, which) -> {
                        ((android.preference.CheckBoxPreference) pref).setChecked(false);
                    });
                    builder.positiveText(R.string.dialog_ok);
                    builder.negativeText(R.string.dialog_cancel);
                    builder.show();
                    break;
                }
            case CardBrowserContextMenu.CARD_BROWSER_CONTEXT_MENU_PREF_KEY:
                CardBrowserContextMenu.ensureConsistentStateWithSharedPreferences(this);
                break;
            case AnkiCardContextMenu.ANKI_CARD_CONTEXT_MENU_PREF_KEY:
                AnkiCardContextMenu.ensureConsistentStateWithSharedPreferences(this);
                break;
        }
        // Update the summary text to reflect new value
        updateSummary(pref);
    } catch (BadTokenException e) {
        Timber.e(e, "Preferences: BadTokenException on showDialog");
    } catch (NumberFormatException e) {
        throw new RuntimeException(e);
    }
}
Also used : Arrays(java.util.Arrays) Bundle(android.os.Bundle) PackageManager(android.content.pm.PackageManager) NonNull(androidx.annotation.NonNull) Uri(android.net.Uri) UsageAnalytics(com.ichi2.anki.analytics.UsageAnalytics) PendingIntent(android.app.PendingIntent) AppCompatPreferenceActivity(com.ichi2.ui.AppCompatPreferenceActivity) Locale(java.util.Locale) NO_SPECIFIC_STATUS_BAR_COLOR(com.ichi2.themes.Themes.NO_SPECIFIC_STATUS_BAR_COLOR) MediaStore(android.provider.MediaStore) Map(java.util.Map) GregorianCalendar(java.util.GregorianCalendar) Timestamp(java.sql.Timestamp) Set(java.util.Set) CustomSyncServer(com.ichi2.anki.web.CustomSyncServer) JSONObject(com.ichi2.utils.JSONObject) Timber(timber.log.Timber) AlertDialog(android.app.AlertDialog) List(java.util.List) StringRes(androidx.annotation.StringRes) ActivityNotFoundException(android.content.ActivityNotFoundException) CompatHelper(com.ichi2.compat.CompatHelper) NotificationService(com.ichi2.anki.services.NotificationService) CardBrowserContextMenu(com.ichi2.anki.contextmenu.CardBrowserContextMenu) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) VersionUtils(com.ichi2.utils.VersionUtils) ActivityManager(android.app.ActivityManager) Context(android.content.Context) OnSharedPreferenceChangeListener(android.content.SharedPreferences.OnSharedPreferenceChangeListener) Intent(android.content.Intent) HashMap(java.util.HashMap) Collection(com.ichi2.libanki.Collection) BootService(com.ichi2.anki.services.BootService) URL_PRIVATE(com.ichi2.libanki.Consts.URL_PRIVATE) MenuItem(android.view.MenuItem) NumberRangePreference(com.ichi2.preferences.NumberRangePreference) Calendar(java.util.Calendar) Toast(android.widget.Toast) Utils(com.ichi2.libanki.Utils) Cursor(android.database.Cursor) ConfirmModSchemaException(com.ichi2.anki.exception.ConfirmModSchemaException) DatabaseLock(com.ichi2.anki.debug.DatabaseLock) ConfirmationPreference(com.ichi2.ui.ConfirmationPreference) Iterator(java.util.Iterator) AlarmManager(android.app.AlarmManager) URLUtil(android.webkit.URLUtil) ComponentName(android.content.ComponentName) StorageAccessException(com.ichi2.anki.exception.StorageAccessException) URL_USER_PROTOCOL(com.ichi2.libanki.Consts.URL_USER_PROTOCOL) FileOutputStream(java.io.FileOutputStream) TextUtils(android.text.TextUtils) FileInputStream(java.io.FileInputStream) Themes(com.ichi2.themes.Themes) File(java.io.File) SeekBarPreference(com.ichi2.ui.SeekBarPreference) AnkiCardContextMenu(com.ichi2.anki.contextmenu.AnkiCardContextMenu) BadTokenException(android.view.WindowManager.BadTokenException) SharedPreferences(android.content.SharedPreferences) TreeMap(java.util.TreeMap) AdaptionUtil(com.ichi2.utils.AdaptionUtil) LanguageUtil(com.ichi2.utils.LanguageUtil) ActivityTransitionAnimation(com.ichi2.anim.ActivityTransitionAnimation) FileChannel(java.nio.channels.FileChannel) VisibleForTesting(androidx.annotation.VisibleForTesting) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) SharedPreferences(android.content.SharedPreferences) GregorianCalendar(java.util.GregorianCalendar) Calendar(java.util.Calendar) PendingIntent(android.app.PendingIntent) Intent(android.content.Intent) PackageManager(android.content.pm.PackageManager) NumberRangePreference(com.ichi2.preferences.NumberRangePreference) ConfirmationPreference(com.ichi2.ui.ConfirmationPreference) SeekBarPreference(com.ichi2.ui.SeekBarPreference) AlarmManager(android.app.AlarmManager) ConfirmModSchemaException(com.ichi2.anki.exception.ConfirmModSchemaException) ComponentName(android.content.ComponentName) PendingIntent(android.app.PendingIntent) BadTokenException(android.view.WindowManager.BadTokenException) NumberRangePreference(com.ichi2.preferences.NumberRangePreference)

Aggregations

JSONObject (com.ichi2.utils.JSONObject)39 ConfirmModSchemaException (com.ichi2.anki.exception.ConfirmModSchemaException)26 JSONArray (com.ichi2.utils.JSONArray)23 Test (org.junit.Test)22 RobolectricTest (com.ichi2.anki.RobolectricTest)14 ConfirmationDialog (com.ichi2.anki.dialogs.ConfirmationDialog)12 Collection (com.ichi2.libanki.Collection)12 Model (com.ichi2.libanki.Model)12 Note (com.ichi2.libanki.Note)8 ArrayList (java.util.ArrayList)8 JSONException (com.ichi2.utils.JSONException)6 HashMap (java.util.HashMap)5 SdkSuppress (androidx.test.filters.SdkSuppress)4 TaskData (com.ichi2.async.TaskData)4 ModelManager (com.ichi2.libanki.ModelManager)4 TextImporter (com.ichi2.libanki.importer.TextImporter)4 Matchers.containsString (org.hamcrest.Matchers.containsString)4 Cursor (android.database.Cursor)3 Uri (android.net.Uri)3 Bundle (android.os.Bundle)3