Search in sources :

Example 31 with Counts

use of com.ichi2.libanki.sched.Counts in project Anki-Android by Ramblurr.

the class DeckTask method doInBackgroundImportAdd.

private TaskData doInBackgroundImportAdd(TaskData... params) {
    // Log.i(AnkiDroidApp.TAG, "doInBackgroundImportAdd");
    Resources res = AnkiDroidApp.getInstance().getBaseContext().getResources();
    Collection col = params[0].getCollection();
    String path = params[0].getString();
    boolean sharedDeckImport = params[0].getBoolean();
    ProgressCallback pc = null;
    // don't report progress on shared deck import (or maybe should we?)
    if (!sharedDeckImport) {
        pc = new ProgressCallback(this, res);
    }
    int addedCount = -1;
    try {
        Anki2Importer imp = new Anki2Importer(col, path, pc);
        AnkiDb ankiDB = col.getDb();
        ankiDB.getDatabase().beginTransaction();
        try {
            addedCount = imp.run();
            ankiDB.getDatabase().setTransactionSuccessful();
        } finally {
            ankiDB.getDatabase().endTransaction();
            if (sharedDeckImport) {
                File tmpFile = new File(path);
                tmpFile.delete();
            }
        }
        if (addedCount >= 0) {
            ankiDB.execute("VACUUM");
            ankiDB.execute("ANALYZE");
        }
        publishProgress(new TaskData(res.getString(R.string.import_update_counts)));
        // Update the counts
        DeckTask.TaskData result = doInBackgroundLoadDeckCounts(new TaskData(col));
        if (result == null) {
            return null;
        }
        return new TaskData(addedCount, result.getObjArray(), true);
    } catch (RuntimeException e) {
        Log.e(AnkiDroidApp.TAG, "doInBackgroundImportAdd - RuntimeException on importing cards: ", e);
        AnkiDroidApp.saveExceptionReportFile(e, "doInBackgroundImportAdd");
        return new TaskData(false);
    } catch (IOException e) {
        Log.e(AnkiDroidApp.TAG, "doInBackgroundImportAdd - IOException on importing cards: ", e);
        AnkiDroidApp.saveExceptionReportFile(e, "doInBackgroundImportAdd");
        return new TaskData(false);
    }
}
Also used : Anki2Importer(com.ichi2.libanki.importer.Anki2Importer) AnkiDb(com.ichi2.anki.AnkiDb) IOException(java.io.IOException) Collection(com.ichi2.libanki.Collection) Resources(android.content.res.Resources) ZipFile(java.util.zip.ZipFile) File(java.io.File)

Example 32 with Counts

use of com.ichi2.libanki.sched.Counts in project Anki-Android by Ramblurr.

the class DeckPicker method onActivityResult.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);
    mDontSaveOnStop = false;
    if (resultCode == RESULT_MEDIA_EJECTED) {
        showDialog(DIALOG_SD_CARD_NOT_MOUNTED);
        return;
    } else if (resultCode == RESULT_DB_ERROR) {
        handleDbError();
        return;
    }
    if (requestCode == SHOW_STUDYOPTIONS && resultCode == RESULT_OK) {
        loadCounts();
    } else if (requestCode == ADD_NOTE && resultCode != RESULT_CANCELED) {
        loadCounts();
    } else if (requestCode == BROWSE_CARDS && (resultCode == Activity.RESULT_OK || resultCode == Activity.RESULT_CANCELED)) {
        loadCounts();
    } else if (requestCode == ADD_CRAM_DECK) {
        // TODO: check, if ok has been clicked
        loadCounts();
    } else if (requestCode == REPORT_ERROR) {
        showStartupScreensAndDialogs(AnkiDroidApp.getSharedPrefs(getBaseContext()), 4);
    } else if (requestCode == SHOW_INFO_UPGRADE_DECKS) {
        if (intent != null && intent.hasExtra(Info.TYPE_UPGRADE_STAGE)) {
            int type = intent.getIntExtra(Info.TYPE_UPGRADE_STAGE, Info.UPGRADE_SCREEN_BASIC1);
            if (type == Info.UPGRADE_CONTINUE) {
                showStartupScreensAndDialogs(AnkiDroidApp.getSharedPrefs(getBaseContext()), 3);
            } else {
                showUpgradeScreen(true, type, !intent.hasExtra(Info.TYPE_ANIMATION_RIGHT));
            }
        } else {
            if (resultCode == RESULT_OK) {
                if (mOpenCollectionDialog != null && mOpenCollectionDialog.isShowing()) {
                    mOpenCollectionDialog.dismiss();
                }
                if (AnkiDroidApp.colIsOpen()) {
                    AnkiDroidApp.closeCollection(true);
                }
                AnkiDroidApp.openCollection(AnkiDroidApp.getCollectionPath());
                loadCounts();
            } else {
                finishWithAnimation();
            }
        }
    } else if (requestCode == SHOW_INFO_WELCOME || requestCode == SHOW_INFO_NEW_VERSION) {
        if (resultCode == RESULT_OK) {
            showStartupScreensAndDialogs(AnkiDroidApp.getSharedPrefs(getBaseContext()), requestCode == SHOW_INFO_WELCOME ? 1 : 2);
        } else {
            finishWithAnimation();
        }
    } else if (requestCode == PREFERENCES_UPDATE) {
        String oldPath = mPrefDeckPath;
        SharedPreferences pref = restorePreferences();
        String newLanguage = pref.getString("language", "");
        if (AnkiDroidApp.setLanguage(newLanguage)) {
            mInvalidateMenu = true;
        }
        if (mNotMountedDialog != null && mNotMountedDialog.isShowing() && pref.getBoolean("internalMemory", false)) {
            showStartupScreensAndDialogs(pref, 0);
        } else if (!mPrefDeckPath.equals(oldPath)) {
            loadCollection();
        }
    // if (resultCode == StudyOptions.RESULT_RESTART) {
    // setResult(StudyOptions.RESULT_RESTART);
    // finishWithAnimation();
    // } else {
    // SharedPreferences preferences = PrefSettings.getSharedPrefs(getBaseContext());
    // BackupManager.initBackup();
    // if (!mPrefDeckPath.equals(preferences.getString("deckPath", AnkiDroidApp.getStorageDirectory())) ||
    // mPrefDeckOrder != Integer.parseInt(preferences.getString("deckOrder", "0"))) {
    // // populateDeckList(preferences.getString("deckPath", AnkiDroidApp.getStorageDirectory()));
    // }
    // }
    } else if (requestCode == REPORT_FEEDBACK && resultCode == RESULT_OK) {
    } else if (requestCode == LOG_IN_FOR_SYNC && resultCode == RESULT_OK) {
        sync();
    } else if (requestCode == LOG_IN_FOR_SHARED_DECK && resultCode == RESULT_OK) {
        addSharedDeck();
    } else if (requestCode == ADD_SHARED_DECKS) {
        if (intent != null) {
            mImportPath = intent.getStringExtra("importPath");
        }
        if (AnkiDroidApp.colIsOpen() && mImportPath != null) {
            DeckTask.launchDeckTask(DeckTask.TASK_TYPE_IMPORT, mImportAddListener, new TaskData(AnkiDroidApp.getCol(), mImportPath, true));
            mImportPath = null;
        }
    } else if (requestCode == REQUEST_REVIEW) {
        // Log.i(AnkiDroidApp.TAG, "Result code = " + resultCode);
        switch(resultCode) {
            default:
                // do not reload counts, if activity is created anew because it has been before destroyed by android
                loadCounts();
                break;
            case Reviewer.RESULT_NO_MORE_CARDS:
                mDontSaveOnStop = true;
                Intent i = new Intent();
                i.setClass(this, StudyOptionsActivity.class);
                i.putExtra("onlyFnsMsg", true);
                startActivityForResult(i, SHOW_STUDYOPTIONS);
                if (AnkiDroidApp.SDK_VERSION > 4) {
                    ActivityTransitionAnimation.slide(this, ActivityTransitionAnimation.RIGHT);
                }
                break;
        }
    }
    // workaround for hidden dialog on return
    BroadcastMessages.showDialog();
}
Also used : SharedPreferences(android.content.SharedPreferences) Intent(android.content.Intent) TaskData(com.ichi2.async.DeckTask.TaskData)

Example 33 with Counts

use of com.ichi2.libanki.sched.Counts in project Anki-Android by Ramblurr.

the class DeckTask method doInBackgroundUpdateValuesFromDeck.

private TaskData doInBackgroundUpdateValuesFromDeck(TaskData... params) {
    // Log.i(AnkiDroidApp.TAG, "doInBackgroundUpdateValuesFromDeck");
    try {
        Sched sched = params[0].getCollection().getSched();
        Object[] obj = params[0].getObjArray();
        boolean reset = (Boolean) obj[0];
        if (reset) {
            sched.reset();
        }
        int[] counts = sched.counts();
        int totalNewCount = sched.totalNewForCurrentDeck();
        int totalCount = sched.cardCount();
        double progressMature = ((double) sched.matureCount()) / ((double) totalCount);
        double progressAll = 1 - (((double) (totalNewCount + counts[1])) / ((double) totalCount));
        double[][] serieslist = null;
        // only calculate stats if necessary
        if ((Boolean) obj[1]) {
            serieslist = Stats.getSmallDueStats(sched.getCol());
        }
        return new TaskData(new Object[] { counts[0], counts[1], counts[2], totalNewCount, totalCount, progressMature, progressAll, sched.eta(counts), serieslist });
    } catch (RuntimeException e) {
        Log.e(AnkiDroidApp.TAG, "doInBackgroundUpdateValuesFromDeck - an error occurred: " + e);
        return null;
    }
}
Also used : Sched(com.ichi2.libanki.Sched) JSONObject(org.json.JSONObject)

Example 34 with Counts

use of com.ichi2.libanki.sched.Counts in project Anki-Android by Ramblurr.

the class DeckTask method doInBackgroundLoadTutorial.

private TaskData doInBackgroundLoadTutorial(TaskData... params) {
    // Log.i(AnkiDroidApp.TAG, "doInBackgroundLoadTutorial");
    Resources res = AnkiDroidApp.getInstance().getBaseContext().getResources();
    Collection col = params[0].getCollection();
    col.getDb().getDatabase().beginTransaction();
    String title = res.getString(R.string.help_tutorial);
    try {
        // get deck or create it
        long did = col.getDecks().id(title);
        // reset todays counts
        JSONObject d = col.getDecks().get(did);
        for (String t : new String[] { "new", "rev", "lrn", "time" }) {
            String k = t + "Today";
            JSONArray ja = new JSONArray();
            ja.put(col.getSched().getToday());
            ja.put(0);
            d.put(k, ja);
        }
        // save deck
        col.getDecks().save(d);
        if (col.getSched().cardCount("(" + did + ")") > 0) {
            // deck does already exist. Remove all cards and recreate them
            // to ensure the correct order
            col.remCards(col.getDecks().cids(did));
        }
        JSONObject model = col.getModels().byName(title);
        // }
        if (model == null) {
            model = col.getModels().addBasicModel(col, title);
        }
        model.put("did", did);
        String[] questions = res.getStringArray(R.array.tutorial_questions);
        String[] answers = res.getStringArray(R.array.tutorial_answers);
        String[] sampleQuestions = res.getStringArray(R.array.tutorial_capitals_questions);
        String[] sampleAnswers = res.getStringArray(R.array.tutorial_capitals_answers);
        int len = Math.min(questions.length, answers.length);
        for (int i = 0; i < len + Math.min(sampleQuestions.length, sampleAnswers.length); i++) {
            Note note = col.newNote(model);
            if (note.values().length < 2) {
                return new TaskData(false);
            }
            note.values()[0] = (i < len) ? questions[i] : sampleQuestions[i - len];
            note.values()[1] = (i < len) ? answers[i] : sampleAnswers[i - len];
            col.addNote(note);
        }
        // deck.setSessionTimeLimit(0);
        if (col.getSched().cardCount("(" + did + ")") == 0) {
            // error, delete deck
            col.getDecks().rem(did, true);
            return new TaskData(false);
        } else {
            col.save();
            col.getDecks().select(did);
            col.getDb().getDatabase().setTransactionSuccessful();
            return new TaskData(true);
        }
    } catch (SQLException e) {
        AnkiDroidApp.saveExceptionReportFile(e, "doInBackgroundLoadTutorial");
        return new DeckTask.TaskData(false);
    } catch (JSONException e) {
        AnkiDroidApp.saveExceptionReportFile(e, "doInBackgroundLoadTutorial");
        return new DeckTask.TaskData(false);
    } finally {
        col.getDb().getDatabase().endTransaction();
    }
}
Also used : SQLException(android.database.SQLException) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) JSONObject(org.json.JSONObject) Note(com.ichi2.libanki.Note) Collection(com.ichi2.libanki.Collection) Resources(android.content.res.Resources)

Example 35 with Counts

use of com.ichi2.libanki.sched.Counts in project Anki-Android by Ramblurr.

the class DeckTask method doInBackgroundOpenCollection.

private TaskData doInBackgroundOpenCollection(TaskData... params) {
    // Log.i(AnkiDroidApp.TAG, "doInBackgroundOpenCollection");
    long time = Utils.intNow(1000);
    Resources res = AnkiDroidApp.getInstance().getBaseContext().getResources();
    String collectionFile = params[0].getString();
    SharedPreferences prefs = AnkiDroidApp.getSharedPrefs(AnkiDroidApp.getInstance().getBaseContext());
    // see, if a collection is still opened
    Collection oldCol = AnkiDroidApp.getCol();
    Collection col = null;
    publishProgress(new TaskData(res.getString(R.string.open_collection)));
    if (!(AnkiDroidApp.colIsOpen() && oldCol.getPath().equals(collectionFile))) {
        // android's delete db bug
        if (BackupManager.safetyBackupNeeded(collectionFile)) {
            publishProgress(new TaskData(res.getString(R.string.backup_collection)));
            BackupManager.performBackup(collectionFile);
        }
        publishProgress(new TaskData(res.getString(R.string.open_collection)));
        // load collection
        try {
            col = AnkiDroidApp.openCollection(collectionFile);
        } catch (RuntimeException e) {
            BackupManager.restoreCollectionIfMissing(collectionFile);
            Log.e(AnkiDroidApp.TAG, "doInBackgroundOpenCollection - RuntimeException on opening collection: " + e);
            AnkiDroidApp.saveExceptionReportFile(e, "doInBackgroundOpenCollection");
            return new TaskData(false);
        }
        // create tutorial deck if needed
        if (prefs.contains("createTutorial") && prefs.getBoolean("createTutorial", false)) {
            prefs.edit().remove("createTutorial").commit();
            publishProgress(new TaskData(res.getString(R.string.tutorial_load)));
            doInBackgroundLoadTutorial(new TaskData(col));
        }
    } else {
        // Log.i(AnkiDroidApp.TAG, "doInBackgroundOpenCollection: collection still open - reusing it");
        col = oldCol;
    }
    Object[] counts = null;
    DeckTask.TaskData result = doInBackgroundLoadDeckCounts(new TaskData(col));
    if (result != null) {
        counts = result.getObjArray();
    }
    if (prefs.getBoolean("splashScreen", false)) {
        long millies = Utils.intNow(1000) - time;
        if (millies < 1000) {
            try {
                Thread.sleep(1200 - millies);
            } catch (InterruptedException e) {
            }
        }
    }
    return new TaskData(col, counts);
}
Also used : SharedPreferences(android.content.SharedPreferences) Collection(com.ichi2.libanki.Collection) JSONObject(org.json.JSONObject) Resources(android.content.res.Resources)

Aggregations

Collection (com.ichi2.libanki.Collection)47 Card (com.ichi2.libanki.Card)43 Test (org.junit.Test)39 RobolectricTest (com.ichi2.anki.RobolectricTest)38 Note (com.ichi2.libanki.Note)38 Deck (com.ichi2.libanki.Deck)12 DeckConfig (com.ichi2.libanki.DeckConfig)11 JSONArray (com.ichi2.utils.JSONArray)11 JSONObject (com.ichi2.utils.JSONObject)10 JSONException (com.ichi2.utils.JSONException)6 HashMap (java.util.HashMap)6 Resources (android.content.res.Resources)4 Nullable (androidx.annotation.Nullable)4 Model (com.ichi2.libanki.Model)4 AbstractDeckTreeNode (com.ichi2.libanki.sched.AbstractDeckTreeNode)4 IOException (java.io.IOException)4 Matchers.containsString (org.hamcrest.Matchers.containsString)4 JSONObject (org.json.JSONObject)4 Cursor (android.database.Cursor)3 ConfirmModSchemaException (com.ichi2.anki.exception.ConfirmModSchemaException)3