Search in sources :

Example 1 with SeekBarPreference

use of com.ichi2.ui.SeekBarPreference 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)

Example 2 with SeekBarPreference

use of com.ichi2.ui.SeekBarPreference in project AnkiChinaAndroid by ankichinateam.

the class Preferences method initPreference.

private void initPreference(android.preference.Preference pref) {
    // Load stored values from Preferences which are stored in the Collection
    if (Arrays.asList(sCollectionPreferences).contains(pref.getKey())) {
        Collection col = getCol();
        if (col != null) {
            try {
                JSONObject conf = col.getConf();
                switch(pref.getKey()) {
                    case "showEstimates":
                        ((android.preference.CheckBoxPreference) pref).setChecked(conf.getBoolean("estTimes"));
                        break;
                    case "showProgress":
                        ((android.preference.CheckBoxPreference) pref).setChecked(conf.getBoolean("dueCounts"));
                        break;
                    case "learnCutoff":
                        ((NumberRangePreference) pref).setValue(conf.getInt("collapseTime") / 60);
                        break;
                    case "timeLimit":
                        ((NumberRangePreference) pref).setValue(conf.getInt("timeLim") / 60);
                        break;
                    case "useCurrent":
                        ((android.preference.ListPreference) pref).setValueIndex(conf.optBoolean("addToCur", true) ? 0 : 1);
                        break;
                    case "newSpread":
                        ((android.preference.ListPreference) pref).setValueIndex(conf.getInt("newSpread"));
                        break;
                    case "dayOffset":
                        Calendar calendar = col.crtGregorianCalendar();
                        ((SeekBarPreference) pref).setValue(calendar.get(Calendar.HOUR_OF_DAY));
                        break;
                    case "schedVer":
                        ((android.preference.CheckBoxPreference) pref).setChecked(conf.optInt("schedVer", 1) == 2);
                }
            } catch (NumberFormatException e) {
                throw new RuntimeException(e);
            }
        } else {
            // Disable Col preferences if Collection closed
            pref.setEnabled(false);
        }
    } else if ("minimumCardsDueForNotification".equals(pref.getKey())) {
        updateNotificationPreference((android.preference.ListPreference) pref);
    }
    // Set the value from the summary cache
    CharSequence s = pref.getSummary();
    mOriginalSumarries.put(pref.getKey(), (s != null) ? s.toString() : "");
    // Update summary
    updateSummary(pref);
}
Also used : JSONObject(com.ichi2.utils.JSONObject) GregorianCalendar(java.util.GregorianCalendar) Calendar(java.util.Calendar) SeekBarPreference(com.ichi2.ui.SeekBarPreference) Collection(com.ichi2.libanki.Collection) NumberRangePreference(com.ichi2.preferences.NumberRangePreference)

Example 3 with SeekBarPreference

use of com.ichi2.ui.SeekBarPreference in project AnkiChinaAndroid by ankichinateam.

the class Preferences method updateSummary.

private void updateSummary(android.preference.Preference pref) {
    if (pref == null || pref.getKey() == null) {
        return;
    }
    // Handle special cases
    switch(pref.getKey()) {
        case "about_dialog_preference":
            pref.setSummary(getResources().getString(R.string.about_version) + " " + VersionUtils.getPkgVersionName());
            break;
        case "custom_sync_server_link":
            SharedPreferences preferences = AnkiDroidApp.getSharedPrefs(this);
            if (!CustomSyncServer.isEnabled(preferences)) {
                pref.setSummary(R.string.disabled);
            } else {
                pref.setSummary(CustomSyncServer.getSyncBaseUrlOrDefault(preferences, ""));
            }
            break;
        case "advanced_statistics_link":
            if (!AnkiDroidApp.getSharedPrefs(this).getBoolean("advanced_statistics_enabled", false)) {
                pref.setSummary(R.string.disabled);
            } else {
                pref.setSummary(R.string.enabled);
            }
            break;
    }
    // Get value text
    String value;
    try {
        if (pref instanceof NumberRangePreference) {
            value = Integer.toString(((NumberRangePreference) pref).getValue());
        } else if (pref instanceof SeekBarPreference) {
            value = Integer.toString(((SeekBarPreference) pref).getValue());
        } else if (pref instanceof android.preference.ListPreference) {
            value = ((android.preference.ListPreference) pref).getEntry().toString();
        } else if (pref instanceof android.preference.EditTextPreference) {
            value = ((android.preference.EditTextPreference) pref).getText();
        } else {
            return;
        }
    } catch (NullPointerException e) {
        value = "";
    }
    // Get summary text
    String oldSummary = mOriginalSumarries.get(pref.getKey());
    // Replace summary text with value according to some rules
    if ("".equals(oldSummary)) {
        pref.setSummary(value);
    } else if ("".equals(value)) {
        pref.setSummary(oldSummary);
    } else if ("minimumCardsDueForNotification".equals(pref.getKey())) {
        pref.setSummary(replaceStringIfNumeric(oldSummary, value));
    } else {
        pref.setSummary(replaceString(oldSummary, value));
    }
}
Also used : SharedPreferences(android.content.SharedPreferences) SeekBarPreference(com.ichi2.ui.SeekBarPreference) NumberRangePreference(com.ichi2.preferences.NumberRangePreference)

Aggregations

NumberRangePreference (com.ichi2.preferences.NumberRangePreference)3 SharedPreferences (android.content.SharedPreferences)2 Collection (com.ichi2.libanki.Collection)2 SeekBarPreference (com.ichi2.ui.SeekBarPreference)2 ActivityManager (android.app.ActivityManager)1 AlarmManager (android.app.AlarmManager)1 AlertDialog (android.app.AlertDialog)1 PendingIntent (android.app.PendingIntent)1 ActivityNotFoundException (android.content.ActivityNotFoundException)1 ComponentName (android.content.ComponentName)1 Context (android.content.Context)1 Intent (android.content.Intent)1 OnSharedPreferenceChangeListener (android.content.SharedPreferences.OnSharedPreferenceChangeListener)1 PackageManager (android.content.pm.PackageManager)1 Cursor (android.database.Cursor)1 Uri (android.net.Uri)1 Bundle (android.os.Bundle)1 MediaStore (android.provider.MediaStore)1 TextUtils (android.text.TextUtils)1 MenuItem (android.view.MenuItem)1