Search in sources :

Example 11 with DeckPicker

use of com.ichi2.anki.DeckPicker in project AnkiChinaAndroid by ankichinateam.

the class SettingFragment method onCreateView.

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    Timber.i("on create view in setting fragment");
    if (mRoot == null) {
        final SharedPreferences preferences = getPreferences();
        mRoot = inflater.inflate(R.layout.fragment_setting, container, false);
        rl_login = mRoot.findViewById(R.id.rl_login);
        mLl_defaultLink = mRoot.findViewById(R.id.ll_default_link);
        mRl_user_name = mRoot.findViewById(R.id.tv_user_name);
        mTv_logout = mRoot.findViewById(R.id.tv_quit);
        mIv_entrance = mRoot.findViewById(R.id.iv_entrance);
        mRl_cloud_space = mRoot.findViewById(R.id.tv_cloud_space);
        mLl_switch_server = mRoot.findViewById(R.id.ll_switch_server);
        mTv_server_name = mRoot.findViewById(R.id.server_name);
        mTv_switch_server = mRoot.findViewById(R.id.tv_switch_server);
        rl_login.setOnClickListener(v -> ((DeckPicker) getAnkiActivity()).loginToSyncServer());
        mRoot.findViewById(R.id.rl_personal_setting).setOnClickListener(v -> {
            Timber.i("Navigating to settings");
            mOldColPath = CollectionHelper.getCurrentAnkiDroidDirectory(getAnkiActivity());
            // Remember the theme we started with so we can restart the Activity if it changes
            mOldTheme = Themes.getCurrentTheme(getContext());
            getAnkiActivity().startActivityForResultWithAnimation(new Intent(getAnkiActivity(), Preferences.class), REQUEST_PREFERENCES_UPDATE, ActivityTransitionAnimation.FADE);
        });
        // mRoot.findViewById(R.id.rl_sync_set).setOnClickListener(v -> {
        // Timber.i("AnkiDroid directory inaccessible");
        // Intent i = Preferences.getPreferenceSubscreenIntent(getAnkiActivity(), "com.ichi2.anki.prefs.general");
        // getAnkiActivity().startActivityWithAnimation(i, ActivityTransitionAnimation.FADE);
        // });
        mNightModeSwitch = mRoot.findViewById(R.id.switch_dark_mode);
        mNightModeSwitch.setChecked(preferences.getBoolean(NIGHT_MODE_PREFERENCE, false));
        mNightModeSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> {
            applyNightMode(isChecked);
        });
        mAutoSyncSwitch = mRoot.findViewById(R.id.switch_auto_sync);
        mAutoSyncSwitch.setChecked(preferences.getBoolean("automaticSyncMode", true));
        mAutoSyncSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> {
            preferences.edit().putBoolean("automaticSyncMode", isChecked).apply();
        });
        mRoot.findViewById(R.id.rl_dark_mode).setOnClickListener(v -> {
            Timber.i("Toggling Night Mode");
            mNightModeSwitch.performClick();
        });
        mRoot.findViewById(R.id.vip_power).setOnClickListener(this);
        mRoot.findViewById(R.id.rl_anki_course).setOnClickListener(this);
        mRoot.findViewById(R.id.rl_team).setOnClickListener(this);
        mRoot.findViewById(R.id.rl_version).setOnClickListener(this);
        mRoot.findViewById(R.id.rl_feedback).setOnClickListener(this);
        mRoot.findViewById(R.id.user_protocol).setOnClickListener(this);
        mRoot.findViewById(R.id.user_private).setOnClickListener(this);
        mRoot.findViewById(R.id.rl_market_like).setOnClickListener(this);
        mLl_switch_server.setOnClickListener(this);
        mVipText = mRoot.findViewById(R.id.vip_text);
        mVipPower = mRoot.findViewById(R.id.vip_power);
        mVipText.setText(mVip ? getVipString(mVipDay) : getNotVipString());
        mVipPower.setText(mVip ? "查看权益" : "立即开通");
        OKHttpUtil.get(Consts.ANKI_CHINA_BASE + Consts.API_VERSION + "configs/1", "", "", new OKHttpUtil.MyCallBack() {

            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, String token, Object arg1, Response response) throws IOException {
                if (response.isSuccessful()) {
                    Timber.i("initMoreDrawerMenuItem successfully!:%s", response.body());
                    try {
                        final JSONObject object = new JSONObject(response.body().string());
                        final JSONArray items = object.getJSONArray("data");
                        Timber.i("initMoreDrawerMenuItem %d ", items.length());
                        List<DynamicItem> dynamicItems = new ArrayList<>();
                        for (int i = 0; i < items.length(); i++) {
                            JSONObject jsonObject = items.getJSONObject(i);
                            String title = jsonObject.optString("title");
                            String image = jsonObject.optString("image_url");
                            String link = jsonObject.optString("target_url");
                            Drawable drawable = null;
                            try {
                                drawable = Drawable.createFromStream(new URL(image).openStream(), title + ".jpg");
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            dynamicItems.add(new DynamicItem(title, link, drawable));
                            Timber.i("load drawable result %s,%s ,%s  ", title, image, link);
                        }
                        getAnkiActivity().runOnUiThread(() -> {
                            mLl_defaultLink.removeAllViews();
                            for (int i = 0; i < dynamicItems.size(); i++) {
                                int finalI = i;
                                int[] attrs = new int[] { R.attr.settingItemBackgroundTop, R.attr.settingItemBackground, R.attr.settingItemBackgroundBottom, R.attr.settingItemBackgroundRound };
                                TypedArray ta = getAnkiActivity().obtainStyledAttributes(attrs);
                                Drawable background;
                                background = ta.getDrawable(dynamicItems.size() == 1 ? 3 : finalI == 0 ? 0 : finalI == dynamicItems.size() - 1 ? 2 : 1);
                                DynamicItem dynamicItem = dynamicItems.get(finalI);
                                SettingItem item = new SettingItem(getContext(), dynamicItem.title, dynamicItem.drawable);
                                item.findViewById(R.id.rl_root).setBackground(background);
                                item.setOnClickListener(v -> {
                                    WebViewActivity.openUrlInApp(getAnkiActivity(), dynamicItem.link, "", -1);
                                });
                                mLl_defaultLink.addView(item);
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    Timber.e("initMoreDrawerMenuItem failed, error code %d", response.code());
                }
            }
        });
    }
    return mRoot;
}
Also used : StringFormat(org.acra.data.StringFormat) Text(org.w3c.dom.Text) LinearLayout(android.widget.LinearLayout) Bundle(android.os.Bundle) URL(java.net.URL) NonNull(androidx.annotation.NonNull) WindowManager(android.view.WindowManager) ImageView(android.widget.ImageView) ForeGroundColorSpan(com.ichi2.anki.DeckPicker.ForeGroundColorSpan) Drawable(android.graphics.drawable.Drawable) JSONException(org.json.JSONException) JSONObject(org.json.JSONObject) Handler(android.os.Handler) View(android.view.View) ForegroundColorSpan(android.text.style.ForegroundColorSpan) CHANGE_ACCOUNT(com.ichi2.anki.DeckPicker.CHANGE_ACCOUNT) URL_ANKI_COURSE(com.ichi2.libanki.Consts.URL_ANKI_COURSE) ViewGroup(android.view.ViewGroup) Timber(timber.log.Timber) List(java.util.List) TextView(android.widget.TextView) Nullable(androidx.annotation.Nullable) HostNumFactory(com.ichi2.anki.web.HostNumFactory) Consts(com.ichi2.libanki.Consts) OKHttpUtil(com.ichi2.utils.OKHttpUtil) MobclickAgent(com.umeng.analytics.MobclickAgent) RelativeLayout(android.widget.RelativeLayout) Window(android.view.Window) DeckPicker.goAppShop(com.ichi2.anki.DeckPicker.goAppShop) URL_FEEDBACK(com.ichi2.libanki.Consts.URL_FEEDBACK) Spanned(android.text.Spanned) Dialog(android.app.Dialog) Intent(android.content.Intent) Collection(com.ichi2.libanki.Collection) URL_PRIVATE(com.ichi2.libanki.Consts.URL_PRIVATE) TypedArray(android.content.res.TypedArray) ArrayList(java.util.ArrayList) SpannableStringBuilder(android.text.SpannableStringBuilder) SyncErrorDialog(com.ichi2.anki.dialogs.SyncErrorDialog) Toast(android.widget.Toast) Connection(com.ichi2.async.Connection) Response(okhttp3.Response) Call(okhttp3.Call) Callback(okhttp3.Callback) ActionBar(android.app.ActionBar) URL_VERSION(com.ichi2.libanki.Consts.URL_VERSION) SettingItem(com.ichi2.ui.SettingItem) SwitchCompat(androidx.appcompat.widget.SwitchCompat) SpannableString(android.text.SpannableString) LayoutInflater(android.view.LayoutInflater) URL_VOLUNTEER(com.ichi2.libanki.Consts.URL_VOLUNTEER) URL_USER_PROTOCOL(com.ichi2.libanki.Consts.URL_USER_PROTOCOL) TextUtils(android.text.TextUtils) BackgroundColorSpan(android.text.style.BackgroundColorSpan) IOException(java.io.IOException) Themes(com.ichi2.themes.Themes) Color(android.graphics.Color) Gravity(android.view.Gravity) TaskStackBuilder(androidx.core.app.TaskStackBuilder) SharedPreferences(android.content.SharedPreferences) ActivityTransitionAnimation(com.ichi2.anim.ActivityTransitionAnimation) JSONArray(org.json.JSONArray) Resources(android.content.res.Resources) Call(okhttp3.Call) OKHttpUtil(com.ichi2.utils.OKHttpUtil) SharedPreferences(android.content.SharedPreferences) JSONArray(org.json.JSONArray) Drawable(android.graphics.drawable.Drawable) Intent(android.content.Intent) IOException(java.io.IOException) SpannableString(android.text.SpannableString) URL(java.net.URL) JSONException(org.json.JSONException) IOException(java.io.IOException) Response(okhttp3.Response) JSONObject(org.json.JSONObject) TypedArray(android.content.res.TypedArray) SettingItem(com.ichi2.ui.SettingItem) JSONObject(org.json.JSONObject) List(java.util.List) ArrayList(java.util.ArrayList) SharedPreferences(android.content.SharedPreferences) Nullable(androidx.annotation.Nullable)

Example 12 with DeckPicker

use of com.ichi2.anki.DeckPicker in project AnkiChinaAndroid by ankichinateam.

the class StudyOptionsFragment method onMenuItemClick.

@SuppressWarnings("deprecation")
@Override
public boolean onMenuItemClick(MenuItem item) {
    switch(item.getItemId()) {
        case R.id.action_browser:
            {
                Timber.i("DeckPicker:: Old browser button pressed");
                getAnkiActivity().openOldCardBrowser();
                return true;
            }
        case R.id.action_undo:
            Timber.i("StudyOptionsFragment:: Undo button pressed");
            CollectionTask.launchCollectionTask(UNDO, undoListener);
            return true;
        case R.id.action_deck_options:
            Timber.i("StudyOptionsFragment:: Deck options button pressed");
            if (getCol().getDecks().isDyn(getCol().getDecks().selected())) {
                openFilteredDeckOptions();
            } else {
                Intent i = new Intent(getActivity(), DeckOptions.class);
                getActivity().startActivityForResult(i, DECK_OPTIONS);
                ActivityTransitionAnimation.slide(getActivity(), ActivityTransitionAnimation.FADE);
            }
            return true;
        case R.id.action_setting:
            Timber.i("StudyOptionsFragment:: Deck setting button pressed");
            Intent i = new Intent(getActivity(), StudySettingActivity.class);
            getActivity().startActivityForResult(i, DECK_OPTIONS);
            ActivityTransitionAnimation.slide(getActivity(), ActivityTransitionAnimation.FADE);
            return true;
        case R.id.action_custom_study:
            Timber.i("StudyOptionsFragment:: custom study button pressed");
            showCustomStudyContextMenu();
            return true;
        case R.id.action_unbury:
            Timber.i("StudyOptionsFragment:: unbury button pressed");
            getCol().getSched().unburyCardsForDeck();
            refreshInterfaceAndDecklist(true);
            item.setVisible(false);
            return true;
        case R.id.action_rebuild:
            Timber.i("StudyOptionsFragment:: rebuild cram deck button pressed");
            mProgressDialog = StyledProgressDialog.show(getActivity(), "", getResources().getString(R.string.rebuild_filtered_deck), true);
            CollectionTask.launchCollectionTask(REBUILD_CRAM, getCollectionTaskListener(true));
            return true;
        case R.id.action_empty:
            Timber.i("StudyOptionsFragment:: empty cram deck button pressed");
            mProgressDialog = StyledProgressDialog.show(getActivity(), "", getResources().getString(R.string.empty_filtered_deck), false);
            CollectionTask.launchCollectionTask(EMPTY_CRAM, getCollectionTaskListener(true));
            return true;
        case R.id.action_rename:
            ((AnkiActivity) getActivity()).renameDeckDialog(getCol().getDecks().selected());
            return true;
        case R.id.action_delete:
            getAnkiActivity().mContextMenuDid = getCol().getDecks().selected();
            ((AnkiActivity) getActivity()).confirmDeckDeletion(getCol().getDecks().selected());
            return true;
        case R.id.action_export:
            ((AnkiActivity) getActivity()).exportDeck(getCol().getDecks().selected());
            return true;
        case R.id.action_add_card:
            addNote();
            return true;
        case R.id.create_deck:
            getAnkiActivity().mContextMenuDid = getCol().getDecks().selected();
            ((AnkiActivity) getActivity()).createSubdeckDialog();
            return true;
        case // 停止/恢复
        R.id.action_suspend:
            mDeckIsStopped = deckIsStopped();
            if (mDeckIsStopped) {
                customDialog = new CustomStyleDialog.Builder(getAnkiActivity()).setTitle("恢复学习").setMessage("恢复学习后将每天新卡数和复习数值调整成默认值,请确认是否开始学习").setPositiveButton("确定", (dialog, which) -> {
                    resumeDeckStudy();
                    dialog.dismiss();
                }).setNegativeButton("取消", (dialog, which) -> dialog.dismiss()).create();
            } else {
                customDialog = new CustomStyleDialog.Builder(getAnkiActivity()).setTitle("停止学习").setMessage("暂停学习将会自动把每天新卡数和复习数调整为零,适用于有事暂停一两周不学习,若该记忆库学习的时长不超过2个月,又暂停了30天未学习,建议重设进度,重新开始学习").setPositiveButton("确定", (dialog, which) -> {
                    stopDeckStudy();
                    dialog.dismiss();
                }).setNegativeButton("取消", (dialog, which) -> dialog.dismiss()).create();
            }
            customDialog.show();
            return true;
        case // 重设学习进度
        R.id.action_reset_card_progress:
            customDialog = new CustomStyleDialog.Builder(getAnkiActivity()).setTitle("重设学习进度").setMessage("重设学习进度后,该记忆库的所有卡片学习记录都会被清除,请谨慎操作").setPositiveButton("确定", (dialog, which) -> {
                CollectionTask.launchCollectionTask(RESET_DECK, new ResetCardHandler(StudyOptionsFragment.this), new TaskData(new Object[] { "deck:\"" + getCol().getDecks().current().getString("name") + "\" " }));
                dialog.dismiss();
            }).setNegativeButton("取消", (dialog, which) -> dialog.dismiss()).create();
            customDialog.show();
            return true;
        default:
            return false;
    }
}
Also used : DividerItemDecoration(androidx.recyclerview.widget.DividerItemDecoration) Bundle(android.os.Bundle) TypeToken(com.google.gson.reflect.TypeToken) Deck(com.ichi2.libanki.Deck) NonNull(androidx.annotation.NonNull) Uri(android.net.Uri) WindowManager(android.view.WindowManager) ImageView(android.widget.ImageView) ColorDrawable(android.graphics.drawable.ColorDrawable) Drawable(android.graphics.drawable.Drawable) Maps(java8.util.Maps) KEY_STOPPED(com.ichi2.anki.StudySettingActivity.KEY_STOPPED) DeckInfoListAdapter(com.ichi2.anki.widgets.DeckInfoListAdapter) Decks(com.ichi2.libanki.Decks) Gson(com.google.gson.Gson) Locale(java.util.Locale) Handler(android.os.Handler) DeckConfig(com.ichi2.libanki.DeckConfig) Map(java.util.Map) Fragment(androidx.fragment.app.Fragment) View(android.view.View) Button(android.widget.Button) TaskData(com.ichi2.async.TaskData) RecyclerView(androidx.recyclerview.widget.RecyclerView) REQUEST_BROWSE_CARDS(com.ichi2.anki.DeckPicker.REQUEST_BROWSE_CARDS) TabLayout(com.google.android.material.tabs.TabLayout) TYPE_LIFE(com.ichi2.libanki.stats.Stats.AxisType.TYPE_LIFE) SHOW_STUDYOPTIONS(com.ichi2.anki.DeckPicker.SHOW_STUDYOPTIONS) Set(java.util.Set) FragmentTransaction(androidx.fragment.app.FragmentTransaction) DisplayMetrics(android.util.DisplayMetrics) ViewGroup(android.view.ViewGroup) Timber(timber.log.Timber) DeckPickerContextMenu(com.ichi2.anki.dialogs.DeckPickerContextMenu) List(java.util.List) Nullable(androidx.annotation.Nullable) TextView(android.widget.TextView) NextCardHandler(com.ichi2.anki.AbstractFlashcardViewer.NextCardHandler) ALL_DECKS_ID(com.ichi2.libanki.stats.Stats.ALL_DECKS_ID) CompatHelper(com.ichi2.compat.CompatHelper) Toolbar(androidx.appcompat.widget.Toolbar) RelativeLayout(android.widget.RelativeLayout) TaskListenerWithContext(com.ichi2.async.TaskListenerWithContext) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) Window(android.view.Window) Snackbar(com.google.android.material.snackbar.Snackbar) DialogFragment(androidx.fragment.app.DialogFragment) KEY_SHOW_TTS_ICON(com.ichi2.libanki.Consts.KEY_SHOW_TTS_ICON) Context(android.content.Context) TaskListener(com.ichi2.async.TaskListener) Dialog(android.app.Dialog) Intent(android.content.Intent) StepsPreference.convertToJSON(com.ichi2.preferences.StepsPreference.convertToJSON) HashMap(java.util.HashMap) Collection(com.ichi2.libanki.Collection) StyledProgressDialog(com.ichi2.themes.StyledProgressDialog) PixelFormat(android.graphics.PixelFormat) Editable(android.text.Editable) TypedArray(android.content.res.TypedArray) MenuItem(android.view.MenuItem) TASK_TYPE(com.ichi2.async.CollectionTask.TASK_TYPE) ArrayList(java.util.ArrayList) JSONArray(com.ichi2.utils.JSONArray) Menu(android.view.Menu) Utils(com.ichi2.libanki.Utils) AbstractDeckTreeNode(com.ichi2.libanki.sched.AbstractDeckTreeNode) Stats(com.ichi2.libanki.stats.Stats) LayoutInflater(android.view.LayoutInflater) CollectionTask(com.ichi2.async.CollectionTask) Color(android.graphics.Color) Gravity(android.view.Gravity) SharedPreferences(android.content.SharedPreferences) TypedValue(android.util.TypedValue) TreeMap(java.util.TreeMap) KEY_MIND_MODE(com.ichi2.anki.StudySettingActivity.KEY_MIND_MODE) CustomStudyDialog(com.ichi2.anki.dialogs.CustomStudyDialog) DeckPicker.fadeOut(com.ichi2.anki.DeckPicker.fadeOut) Activity(android.app.Activity) ActivityTransitionAnimation(com.ichi2.anim.ActivityTransitionAnimation) DeckPicker.fadeIn(com.ichi2.anki.DeckPicker.fadeIn) STUDY_SETTING(com.ichi2.anki.StudySettingActivity.STUDY_SETTING) EditText(android.widget.EditText) CustomStyleDialog(com.ichi2.ui.CustomStyleDialog) Resources(android.content.res.Resources) Intent(android.content.Intent) TaskData(com.ichi2.async.TaskData)

Example 13 with DeckPicker

use of com.ichi2.anki.DeckPicker 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 14 with DeckPicker

use of com.ichi2.anki.DeckPicker 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)

Example 15 with DeckPicker

use of com.ichi2.anki.DeckPicker in project AnkiChinaAndroid by ankichinateam.

the class DeckPickerNoSpaceLeftDialog method onCreateDialog.

@Override
public MaterialDialog onCreateDialog(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Resources res = getResources();
    return new MaterialDialog.Builder(getActivity()).title(res.getString(R.string.sd_card_full_title)).content(res.getString(R.string.backup_deck_no_space_left)).cancelable(true).positiveText(res.getString(R.string.dialog_ok)).onPositive((dialog, which) -> ((DeckPicker) getActivity()).startLoadingCollection()).cancelListener(dialog -> ((DeckPicker) getActivity()).startLoadingCollection()).show();
}
Also used : DeckPicker(com.ichi2.anki.DeckPicker) Bundle(android.os.Bundle) AnalyticsDialogFragment(com.ichi2.anki.analytics.AnalyticsDialogFragment) R(com.ichi2.anki.R) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) Resources(android.content.res.Resources) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) Resources(android.content.res.Resources) DeckPicker(com.ichi2.anki.DeckPicker)

Aggregations

Intent (android.content.Intent)11 Resources (android.content.res.Resources)10 Bundle (android.os.Bundle)10 MaterialDialog (com.afollestad.materialdialogs.MaterialDialog)8 Collection (com.ichi2.libanki.Collection)8 SharedPreferences (android.content.SharedPreferences)7 View (android.view.View)6 TextView (android.widget.TextView)6 Context (android.content.Context)5 TypedArray (android.content.res.TypedArray)5 Drawable (android.graphics.drawable.Drawable)5 Menu (android.view.Menu)5 HostNumFactory (com.ichi2.anki.web.HostNumFactory)5 List (java.util.List)5 Window (android.view.Window)4 WindowManager (android.view.WindowManager)4 RelativeLayout (android.widget.RelativeLayout)4 NonNull (androidx.annotation.NonNull)4 Nullable (androidx.annotation.Nullable)4 ArrayList (java.util.ArrayList)4