Search in sources :

Example 31 with JSONException

use of com.ichi2.utils.JSONException in project Anki-Android by Ramblurr.

the class Models method _availClozeOrds.

public ArrayList<Integer> _availClozeOrds(JSONObject m, String flds, boolean allowEmpty) {
    String[] sflds = Utils.splitFields(flds);
    Map<String, Pair<Integer, JSONObject>> map = fieldMap(m);
    Set<Integer> ords = new HashSet<Integer>();
    Matcher matcher1 = null;
    try {
        matcher1 = fClozePattern1.matcher(m.getJSONArray("tmpls").getJSONObject(0).getString("qfmt"));
    // Libanki makes two finds for each case of the cloze tags, but we embed both in the pattern.
    // Please note, that this approach is not 100% correct, as we allow cases like {{cloze:...%>
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
    while (matcher1.find()) {
        String fname = matcher1.group(1);
        if (!map.containsKey(fname)) {
            continue;
        }
        int ord = map.get(fname).first;
        Matcher matcher2 = fClozePattern2.matcher(sflds[ord]);
        while (matcher2.find()) {
            ords.add(Integer.parseInt(matcher2.group(1)) - 1);
        }
    }
    if (ords.contains(-1)) {
        ords.remove(-1);
    }
    if (ords.isEmpty() && allowEmpty) {
        // empty clozes use first ord
        return new ArrayList<Integer>(Arrays.asList(new Integer[] { 0 }));
    }
    return new ArrayList<Integer>(ords);
}
Also used : Matcher(java.util.regex.Matcher) ArrayList(java.util.ArrayList) JSONException(org.json.JSONException) Pair(com.ichi2.anki.Pair) HashSet(java.util.HashSet)

Example 32 with JSONException

use of com.ichi2.utils.JSONException in project Anki-Android by Ramblurr.

the class DeckTask method doInBackgroundConfChange.

private TaskData doInBackgroundConfChange(TaskData... params) {
    // Log.i(AnkiDroidApp.TAG, "doInBackgroundConfChange");
    Object[] data = params[0].getObjArray();
    Collection col = (Collection) data[0];
    JSONObject deck = (JSONObject) data[1];
    JSONObject conf = (JSONObject) data[2];
    try {
        long newConfId = conf.getLong("id");
        // If new config has a different sorting order, reorder the cards
        int oldOrder = col.getDecks().getConf(deck.getLong("conf")).getJSONObject("new").getInt("order");
        int newOrder = col.getDecks().getConf(newConfId).getJSONObject("new").getInt("order");
        if (oldOrder != newOrder) {
            switch(newOrder) {
                case 0:
                    col.getSched().randomizeCards(deck.getLong("id"));
                    break;
                case 1:
                    col.getSched().orderCards(deck.getLong("id"));
                    break;
            }
        }
        col.getDecks().setConf(deck, newConfId);
        return new TaskData(true);
    } catch (JSONException e) {
        return new TaskData(false);
    }
}
Also used : JSONObject(org.json.JSONObject) Collection(com.ichi2.libanki.Collection) JSONException(org.json.JSONException) JSONObject(org.json.JSONObject)

Example 33 with JSONException

use of com.ichi2.utils.JSONException in project Anki-Android by Ramblurr.

the class DeckTask method doInBackgroundExportApkg.

private TaskData doInBackgroundExportApkg(TaskData... params) {
    // Log.i(AnkiDroidApp.TAG, "doInBackgroundExportApkg");
    Object[] data = params[0].getObjArray();
    String colPath = (String) data[0];
    String apkgPath = (String) data[1];
    boolean includeMedia = (Boolean) data[2];
    byte[] buf = new byte[1024];
    try {
        try {
            AnkiDb d = AnkiDatabaseManager.getDatabase(colPath);
        } catch (SQLiteDatabaseCorruptException e) {
            // collection is invalid
            return new TaskData(false);
        } finally {
            AnkiDatabaseManager.closeDatabase(colPath);
        }
        // export collection
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(apkgPath));
        FileInputStream colFin = new FileInputStream(colPath);
        ZipEntry ze = new ZipEntry("collection.anki2");
        zos.putNextEntry(ze);
        int len;
        while ((len = colFin.read(buf)) >= 0) {
            zos.write(buf, 0, len);
        }
        zos.closeEntry();
        colFin.close();
        // export media
        JSONObject media = new JSONObject();
        if (includeMedia) {
            File mediaDir = new File(AnkiDroidApp.getCurrentAnkiDroidMediaDir());
            if (mediaDir.exists() && mediaDir.isDirectory()) {
                File[] mediaFiles = mediaDir.listFiles();
                int c = 0;
                for (File f : mediaFiles) {
                    FileInputStream mediaFin = new FileInputStream(f);
                    ze = new ZipEntry(Integer.toString(c));
                    zos.putNextEntry(ze);
                    while ((len = mediaFin.read(buf)) >= 0) {
                        zos.write(buf, 0, len);
                    }
                    zos.closeEntry();
                    media.put(Integer.toString(c), f.getName());
                }
            }
        }
        ze = new ZipEntry("media");
        zos.putNextEntry(ze);
        InputStream mediaIn = new ByteArrayInputStream(Utils.jsonToString(media).getBytes("UTF-8"));
        while ((len = mediaIn.read(buf)) >= 0) {
            zos.write(buf, 0, len);
        }
        zos.closeEntry();
        zos.close();
    } catch (FileNotFoundException e) {
        return new TaskData(false);
    } catch (IOException e) {
        return new TaskData(false);
    } catch (JSONException e) {
        return new TaskData(false);
    }
    return new TaskData(true);
}
Also used : AnkiDb(com.ichi2.anki.AnkiDb) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) ZipEntry(java.util.zip.ZipEntry) FileNotFoundException(java.io.FileNotFoundException) SQLiteDatabaseCorruptException(android.database.sqlite.SQLiteDatabaseCorruptException) JSONException(org.json.JSONException) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) JSONObject(org.json.JSONObject) ByteArrayInputStream(java.io.ByteArrayInputStream) ZipOutputStream(java.util.zip.ZipOutputStream) FileOutputStream(java.io.FileOutputStream) JSONObject(org.json.JSONObject) ZipFile(java.util.zip.ZipFile) File(java.io.File)

Example 34 with JSONException

use of com.ichi2.utils.JSONException in project Anki-Android by Ramblurr.

the class CardBrowser method onCreateDialog.

@Override
protected Dialog onCreateDialog(int id) {
    StyledDialog dialog = null;
    Resources res = getResources();
    StyledDialog.Builder builder = new StyledDialog.Builder(this);
    switch(id) {
        case DIALOG_ORDER:
            builder.setTitle(res.getString(R.string.card_browser_change_display_order_title));
            builder.setMessage(res.getString(R.string.card_browser_change_display_order_reverse));
            builder.setIcon(android.R.drawable.ic_menu_sort_by_size);
            builder.setSingleChoiceItems(res.getStringArray(R.array.card_browser_order_labels), mOrder, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface arg0, int which) {
                    if (which != mOrder) {
                        mOrder = which;
                        mOrderAsc = false;
                        try {
                            if (mOrder == 0) {
                                mCol.getConf().put("sortType", fSortTypes[1]);
                                AnkiDroidApp.getSharedPrefs(getBaseContext()).edit().putBoolean("cardBrowserNoSorting", true).commit();
                            } else {
                                mCol.getConf().put("sortType", fSortTypes[mOrder]);
                                AnkiDroidApp.getSharedPrefs(getBaseContext()).edit().putBoolean("cardBrowserNoSorting", false).commit();
                            }
                            // default to descending for non-text fields
                            if (fSortTypes[mOrder].equals("noteFld")) {
                                mOrderAsc = true;
                            }
                            mCol.getConf().put("sortBackwards", mOrderAsc);
                        } catch (JSONException e) {
                            throw new RuntimeException(e);
                        }
                        searchCards();
                    } else if (which != CARD_ORDER_NONE) {
                        mOrderAsc = !mOrderAsc;
                        try {
                            mCol.getConf().put("sortBackwards", mOrderAsc);
                        } catch (JSONException e) {
                            throw new RuntimeException(e);
                        }
                        Collections.reverse(mCards);
                        updateList();
                    }
                }
            });
            dialog = builder.create();
            break;
        case DIALOG_CONTEXT_MENU:
            // FIXME:
            String[] entries = new String[4];
            @SuppressWarnings("unused") MenuItem item;
            entries[CONTEXT_MENU_MARK] = res.getString(R.string.card_browser_mark_card);
            entries[CONTEXT_MENU_SUSPEND] = res.getString(R.string.card_browser_suspend_card);
            entries[CONTEXT_MENU_DELETE] = res.getString(R.string.card_browser_delete_card);
            entries[CONTEXT_MENU_DETAILS] = res.getString(R.string.card_browser_card_details);
            builder.setTitle("contextmenu");
            builder.setIcon(R.drawable.ic_menu_manage);
            builder.setItems(entries, mContextMenuListener);
            dialog = builder.create();
            break;
        case DIALOG_TAGS:
            allTags = mCol.getTags().all();
            builder.setTitle(R.string.studyoptions_limit_select_tags);
            builder.setMultiChoiceItems(allTags, new boolean[allTags.length], new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    String tag = allTags[which];
                    if (mSelectedTags.contains(tag)) {
                        // Log.i(AnkiDroidApp.TAG, "unchecked tag: " + tag);
                        mSelectedTags.remove(tag);
                    } else {
                        // Log.i(AnkiDroidApp.TAG, "checked tag: " + tag);
                        mSelectedTags.add(tag);
                    }
                }
            });
            builder.setPositiveButton(res.getString(R.string.select), new OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    mSearchEditText.setText("");
                    String tags = mSelectedTags.toString();
                    mSearchEditText.setHint(getResources().getString(R.string.card_browser_tags_shown, tags.substring(1, tags.length() - 1)));
                    StringBuilder sb = new StringBuilder();
                    for (String tag : mSelectedTags) {
                        sb.append("tag:").append(tag).append(" ");
                    }
                    mSearchTerms = sb.toString();
                    searchCards();
                }
            });
            builder.setNegativeButton(res.getString(R.string.cancel), new OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    mSelectedTags.clear();
                }
            });
            builder.setOnCancelListener(new OnCancelListener() {

                @Override
                public void onCancel(DialogInterface dialog) {
                    mSelectedTags.clear();
                }
            });
            dialog = builder.create();
            break;
    }
    return dialog;
}
Also used : DialogInterface(android.content.DialogInterface) StyledDialog(com.ichi2.themes.StyledDialog) JSONException(org.json.JSONException) MenuItem(android.view.MenuItem) OnClickListener(android.content.DialogInterface.OnClickListener) OnClickListener(android.content.DialogInterface.OnClickListener) Resources(android.content.res.Resources) OnCancelListener(android.content.DialogInterface.OnCancelListener)

Example 35 with JSONException

use of com.ichi2.utils.JSONException in project Anki-Android by Ramblurr.

the class DeckPicker method onPrepareDialog.

@Override
protected void onPrepareDialog(int id, Dialog dialog) {
    Resources res = getResources();
    StyledDialog ad = (StyledDialog) dialog;
    switch(id) {
        case DIALOG_DELETE_DECK:
            if (!AnkiDroidApp.colIsOpen() || mDeckList == null || mDeckList.size() == 0) {
                return;
            }
            boolean isDyn = AnkiDroidApp.getCol().getDecks().isDyn(mCurrentDid);
            if (isDyn) {
                ad.setMessage(String.format(res.getString(R.string.delete_cram_deck_message), "\'" + AnkiDroidApp.getCol().getDecks().name(mCurrentDid) + "\'"));
            } else {
                ad.setMessage(String.format(res.getString(R.string.delete_deck_message), "\'" + AnkiDroidApp.getCol().getDecks().name(mCurrentDid) + "\'"));
            }
            break;
        case DIALOG_CONTEXT_MENU:
            if (!AnkiDroidApp.colIsOpen() || mDeckList == null || mDeckList.size() == 0) {
                return;
            }
            mCurrentDid = Long.parseLong(mDeckList.get(mContextMenuPosition).get("did"));
            try {
                ad.changeListItem(CONTEXT_MENU_COLLAPSE_DECK, getResources().getString(AnkiDroidApp.getCol().getDecks().get(mCurrentDid).getBoolean("collapsed") ? R.string.contextmenu_deckpicker_inflate_deck : R.string.contextmenu_deckpicker_collapse_deck));
            } catch (NotFoundException e) {
            // do nothing
            } catch (JSONException e) {
            // do nothing
            }
            ad.setTitle(AnkiDroidApp.getCol().getDecks().name(mCurrentDid));
            break;
        case DIALOG_IMPORT_LOG:
        case DIALOG_SYNC_LOG:
        case DIALOG_SYNC_SANITY_ERROR:
            // If both have text, separate them by a new line.
            if (!TextUtils.isEmpty(mDialogMessage) && !TextUtils.isEmpty(mSyncMessage)) {
                ad.setMessage(mDialogMessage + "\n\n" + mSyncMessage);
            } else if (!TextUtils.isEmpty(mDialogMessage)) {
                ad.setMessage(mDialogMessage);
            } else {
                ad.setMessage(mSyncMessage);
            }
            break;
        case DIALOG_DB_ERROR:
            mLoadFailed = false;
            ad.getButton(Dialog.BUTTON3).setEnabled(hasErrorFiles());
            break;
        case DIALOG_LOAD_FAILED:
            mLoadFailed = true;
            if (mOpenCollectionDialog != null && mOpenCollectionDialog.isShowing()) {
                mOpenCollectionDialog.setMessage(res.getString(R.string.col_load_failed));
            }
            break;
        case DIALOG_ERROR_HANDLING:
            ArrayList<String> options = new ArrayList<String>();
            ArrayList<Integer> values = new ArrayList<Integer>();
            if (AnkiDroidApp.getCol() == null) {
                // retry
                options.add(res.getString(R.string.backup_retry_opening));
                values.add(0);
            } else {
                // fix integrity
                options.add(res.getString(R.string.check_db));
                values.add(1);
            }
            // repair db with sqlite
            options.add(res.getString(R.string.backup_error_menu_repair));
            values.add(2);
            // // restore from backup
            options.add(res.getString(R.string.backup_restore));
            values.add(3);
            // delete old collection and build new one
            options.add(res.getString(R.string.backup_full_sync_from_server));
            values.add(4);
            // delete old collection and build new one
            options.add(res.getString(R.string.backup_del_collection));
            values.add(5);
            String[] titles = new String[options.size()];
            mRepairValues = new int[options.size()];
            for (int i = 0; i < options.size(); i++) {
                titles[i] = options.get(i);
                mRepairValues[i] = values.get(i);
            }
            ad.setItems(titles, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    switch(mRepairValues[which]) {
                        case 0:
                            loadCollection();
                            return;
                        case 1:
                            integrityCheck();
                            return;
                        case 2:
                            showDialog(DIALOG_REPAIR_COLLECTION);
                            return;
                        case 3:
                            showDialog(DIALOG_RESTORE_BACKUP);
                            return;
                        case 4:
                            showDialog(DIALOG_FULL_SYNC_FROM_SERVER);
                            return;
                        case 5:
                            showDialog(DIALOG_NEW_COLLECTION);
                            return;
                    }
                }
            });
            break;
        case DIALOG_IMPORT_SELECT:
            List<File> fileList = Utils.getImportableDecks();
            if (fileList.size() == 0) {
                Themes.showThemedToast(DeckPicker.this, getResources().getString(R.string.upgrade_import_no_file_found), false);
            }
            ad.setEnabled(fileList.size() != 0);
            String[] tts = new String[fileList.size()];
            mImportValues = new String[fileList.size()];
            for (int i = 0; i < tts.length; i++) {
                tts[i] = fileList.get(i).getName().replace(".apkg", "");
                mImportValues[i] = fileList.get(i).getAbsolutePath();
            }
            ad.setItems(tts, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    mImportPath = mImportValues[which];
                    switch(mImportMethod) {
                        case IMPORT_METHOD_ADD:
                            DeckTask.launchDeckTask(DeckTask.TASK_TYPE_IMPORT, mImportAddListener, new TaskData(AnkiDroidApp.getCol(), mImportPath, false));
                            mImportPath = null;
                            break;
                        case IMPORT_METHOD_REPLACE:
                            DeckTask.launchDeckTask(DeckTask.TASK_TYPE_IMPORT_REPLACE, mImportReplaceListener, new TaskData(AnkiDroidApp.getCol(), mImportPath));
                            mImportPath = null;
                            break;
                        case IMPORT_METHOD_ASK:
                        default:
                            showDialog(DIALOG_IMPORT);
                    }
                    mImportMethod = IMPORT_METHOD_ASK;
                }
            });
            break;
    }
}
Also used : DialogInterface(android.content.DialogInterface) StyledDialog(com.ichi2.themes.StyledDialog) ArrayList(java.util.ArrayList) NotFoundException(android.content.res.Resources.NotFoundException) JSONException(org.json.JSONException) TaskData(com.ichi2.async.DeckTask.TaskData) Resources(android.content.res.Resources) File(java.io.File)

Aggregations

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