Search in sources :

Example 96 with JSONArray

use of com.ichi2.utils.JSONArray in project Anki-Android by ankidroid.

the class AbstractSchedTest method undoAndRedo.

protected void undoAndRedo(boolean preload) {
    Collection col = getCol();
    DeckConfig conf = col.getDecks().confForDid(1);
    conf.getJSONObject("new").put("delays", new JSONArray(new double[] { 1, 3, 5, 10 }));
    col.getDecks().save(conf);
    col.set_config("collapseTime", 20 * 60);
    AbstractSched sched = col.getSched();
    addNoteUsingBasicModel("foo", "bar");
    col.reset();
    advanceRobolectricLooper();
    Card card = sched.getCard();
    assertNotNull(card);
    assertEquals(new Counts(1, 0, 0), sched.counts(card));
    if (preload) {
        sched.preloadNextCard();
    }
    sched.answerCard(card, sched.getGoodNewButton());
    advanceRobolectricLooper();
    card = sched.getCard();
    assertNotNull(card);
    assertEquals(new Counts(0, (schedVersion == 1) ? 3 : 1, 0), sched.counts(card));
    if (preload) {
        sched.preloadNextCard();
    }
    sched.answerCard(card, sched.getGoodNewButton());
    advanceRobolectricLooper();
    card = sched.getCard();
    assertNotNull(card);
    assertEquals(new Counts(0, (schedVersion == 1) ? 2 : 1, 0), sched.counts(card));
    if (preload) {
        sched.preloadNextCard();
        advanceRobolectricLooper();
    }
    assertNotNull(card);
    card = nonTaskUndo(col);
    advanceRobolectricLooper();
    assertNotNull(card);
    assertEquals(new Counts(0, (schedVersion == 1) ? 3 : 1, 0), sched.counts(card));
    sched.count();
    if (preload) {
        sched.preloadNextCard();
        advanceRobolectricLooper();
    }
    sched.answerCard(card, sched.getGoodNewButton());
    advanceRobolectricLooper();
    card = sched.getCard();
    assertNotNull(card);
    if (preload) {
        sched.preloadNextCard();
    }
    assertEquals(new Counts(0, (schedVersion == 1) ? 2 : 1, 0), sched.counts(card));
    assertNotNull(card);
}
Also used : JSONArray(com.ichi2.utils.JSONArray) Collection(com.ichi2.libanki.Collection) DeckConfig(com.ichi2.libanki.DeckConfig) Card(com.ichi2.libanki.Card)

Example 97 with JSONArray

use of com.ichi2.utils.JSONArray in project Anki-Android by ankidroid.

the class ContentProviderTest method testInsertField.

/**
 * Check that inserting and removing a note into default deck works as expected
 */
@Test
public void testInsertField() throws Exception {
    // Get required objects for test
    final ContentResolver cr = getContentResolver();
    Collection col = getCol();
    Model model = StdModels.BASIC_MODEL.add(col, BASIC_MODEL_NAME);
    long modelId = model.getLong("id");
    JSONArray initialFieldsArr = model.getJSONArray("flds");
    int initialFieldCount = initialFieldsArr.length();
    Uri noteTypeUri = ContentUris.withAppendedId(FlashCardsContract.Model.CONTENT_URI, modelId);
    ContentValues insertFieldValues = new ContentValues();
    insertFieldValues.put(FlashCardsContract.Model.FIELD_NAME, TEST_FIELD_NAME);
    Uri fieldUri = cr.insert(Uri.withAppendedPath(noteTypeUri, "fields"), insertFieldValues);
    assertNotNull("Check field uri", fieldUri);
    // Ensure that the changes are physically saved to the DB
    col = reopenCol();
    model = col.getModels().get(modelId);
    // Test the field is as expected
    long fieldId = ContentUris.parseId(fieldUri);
    assertEquals("Check field id", initialFieldCount, fieldId);
    assertNotNull("Check model", model);
    JSONArray fldsArr = model.getJSONArray("flds");
    assertEquals("Check fields length", initialFieldCount + 1, fldsArr.length());
    assertEquals("Check last field name", TEST_FIELD_NAME, fldsArr.getJSONObject(fldsArr.length() - 1).optString("name", ""));
    col.getModels().rem(model);
}
Also used : ContentValues(android.content.ContentValues) Model(com.ichi2.libanki.Model) JSONArray(com.ichi2.utils.JSONArray) Collection(com.ichi2.libanki.Collection) Uri(android.net.Uri) ContentResolver(android.content.ContentResolver) Test(org.junit.Test)

Example 98 with JSONArray

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

the class Models method fieldMap.

/**
 * "Mapping of field name -> (ord, field).
 */
public Map<String, Pair<Integer, JSONObject>> fieldMap(JSONObject m) {
    JSONArray ja;
    try {
        ja = m.getJSONArray("flds");
        // TreeMap<Integer, String> map = new TreeMap<Integer, String>();
        Map<String, Pair<Integer, JSONObject>> result = new HashMap<String, Pair<Integer, JSONObject>>();
        for (int i = 0; i < ja.length(); i++) {
            JSONObject f = ja.getJSONObject(i);
            result.put(f.getString("name"), new Pair<Integer, JSONObject>(f.getInt("ord"), f));
        }
        return result;
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
}
Also used : JSONObject(org.json.JSONObject) HashMap(java.util.HashMap) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) Pair(com.ichi2.anki.Pair)

Example 99 with JSONArray

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

the class StudyOptionsFragment method onPrepareDialog.

private void onPrepareDialog(int id, StyledDialog styledDialog) {
    Resources res = getResources();
    switch(id) {
        case DIALOG_CUSTOM_STUDY_DETAILS:
            styledDialog.setTitle(res.getStringArray(R.array.custom_study_options_labels)[mCustomDialogChoice]);
            switch(mCustomDialogChoice + 1) {
                case CUSTOM_STUDY_NEW:
                    if (AnkiDroidApp.colIsOpen()) {
                        Collection col = AnkiDroidApp.getCol();
                        mCustomStudyTextView1.setText(res.getString(R.string.custom_study_new_total_new, col.getSched().totalNewForCurrentDeck()));
                    }
                    mCustomStudyTextView2.setText(res.getString(R.string.custom_study_new_extend));
                    mCustomStudyEditText.setText(Integer.toString(AnkiDroidApp.getSharedPrefs(getActivity()).getInt("extendNew", 10)));
                    styledDialog.setButtonOnClickListener(Dialog.BUTTON_POSITIVE, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (AnkiDroidApp.colIsOpen()) {
                                try {
                                    int n = Integer.parseInt(mCustomStudyEditText.getText().toString());
                                    AnkiDroidApp.getSharedPrefs(getActivity()).edit().putInt("extendNew", n).commit();
                                    Collection col = AnkiDroidApp.getCol();
                                    JSONObject deck = col.getDecks().current();
                                    deck.put("extendNew", n);
                                    col.getDecks().save(deck);
                                    col.getSched().extendLimits(n, 0);
                                    resetAndUpdateValuesFromDeck();
                                    finishCongrats();
                                } catch (NumberFormatException e) {
                                    // ignore non numerical values
                                    Themes.showThemedToast(getActivity().getBaseContext(), getResources().getString(R.string.custom_study_invalid_number), false);
                                } catch (JSONException e) {
                                    throw new RuntimeException(e);
                                }
                            }
                        }
                    });
                    break;
                case CUSTOM_STUDY_REV:
                    if (AnkiDroidApp.colIsOpen()) {
                        Collection col = AnkiDroidApp.getCol();
                        mCustomStudyTextView1.setText(res.getString(R.string.custom_study_rev_total_rev, col.getSched().totalRevForCurrentDeck()));
                    }
                    mCustomStudyTextView2.setText(res.getString(R.string.custom_study_rev_extend));
                    mCustomStudyEditText.setText(Integer.toString(AnkiDroidApp.getSharedPrefs(getActivity()).getInt("extendRev", 10)));
                    styledDialog.setButtonOnClickListener(Dialog.BUTTON_POSITIVE, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (AnkiDroidApp.colIsOpen()) {
                                try {
                                    int n = Integer.parseInt(mCustomStudyEditText.getText().toString());
                                    AnkiDroidApp.getSharedPrefs(getActivity()).edit().putInt("extendRev", n).commit();
                                    Collection col = AnkiDroidApp.getCol();
                                    JSONObject deck = col.getDecks().current();
                                    deck.put("extendRev", n);
                                    col.getDecks().save(deck);
                                    col.getSched().extendLimits(0, n);
                                    resetAndUpdateValuesFromDeck();
                                    finishCongrats();
                                } catch (NumberFormatException e) {
                                    // ignore non numerical values
                                    Themes.showThemedToast(getActivity().getBaseContext(), getResources().getString(R.string.custom_study_invalid_number), false);
                                } catch (JSONException e) {
                                    throw new RuntimeException(e);
                                }
                            }
                        }
                    });
                    break;
                case CUSTOM_STUDY_FORGOT:
                    mCustomStudyTextView1.setText("");
                    mCustomStudyTextView2.setText(res.getString(R.string.custom_study_forgotten));
                    mCustomStudyEditText.setText(Integer.toString(AnkiDroidApp.getSharedPrefs(getActivity()).getInt("forgottenDays", 2)));
                    styledDialog.setButtonOnClickListener(Dialog.BUTTON_POSITIVE, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            JSONArray ar = new JSONArray();
                            try {
                                int forgottenDays = Integer.parseInt(((EditText) mCustomStudyEditText).getText().toString());
                                ar.put(0, 1);
                                createFilteredDeck(ar, new Object[] { String.format(Locale.US, "rated:%d:1", forgottenDays), 9999, Sched.DYN_RANDOM }, false);
                            } catch (NumberFormatException e) {
                                // ignore non numerical values
                                Themes.showThemedToast(getActivity().getBaseContext(), getResources().getString(R.string.custom_study_invalid_number), false);
                            } catch (JSONException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    });
                    break;
                case CUSTOM_STUDY_AHEAD:
                    mCustomStudyTextView1.setText("");
                    mCustomStudyTextView2.setText(res.getString(R.string.custom_study_ahead));
                    mCustomStudyEditText.setText(Integer.toString(AnkiDroidApp.getSharedPrefs(getActivity()).getInt("aheadDays", 1)));
                    styledDialog.setButtonOnClickListener(Dialog.BUTTON_POSITIVE, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            try {
                                int days = Integer.parseInt(((EditText) mCustomStudyEditText).getText().toString());
                                createFilteredDeck(new JSONArray(), new Object[] { String.format(Locale.US, "prop:due<=%d", days), 9999, Sched.DYN_DUE }, true);
                            } catch (NumberFormatException e) {
                                // ignore non numerical values
                                Themes.showThemedToast(getActivity().getBaseContext(), getResources().getString(R.string.custom_study_invalid_number), false);
                            }
                        }
                    });
                    break;
                case CUSTOM_STUDY_RANDOM:
                    mCustomStudyTextView1.setText("");
                    mCustomStudyTextView2.setText(res.getString(R.string.custom_study_random));
                    mCustomStudyEditText.setText(Integer.toString(AnkiDroidApp.getSharedPrefs(getActivity()).getInt("randomCards", 100)));
                    styledDialog.setButtonOnClickListener(Dialog.BUTTON_POSITIVE, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            try {
                                int randomCards = Integer.parseInt(((EditText) mCustomStudyEditText).getText().toString());
                                createFilteredDeck(new JSONArray(), new Object[] { "", randomCards, Sched.DYN_RANDOM }, true);
                            } catch (NumberFormatException e) {
                                // ignore non numerical values
                                Themes.showThemedToast(getActivity().getBaseContext(), getResources().getString(R.string.custom_study_invalid_number), false);
                            }
                        }
                    });
                    break;
                case CUSTOM_STUDY_PREVIEW:
                    mCustomStudyTextView1.setText("");
                    mCustomStudyTextView2.setText(res.getString(R.string.custom_study_preview));
                    mCustomStudyEditText.setText(Integer.toString(AnkiDroidApp.getSharedPrefs(getActivity()).getInt("previewDays", 1)));
                    styledDialog.setButtonOnClickListener(Dialog.BUTTON_POSITIVE, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            String previewDays = ((EditText) mCustomStudyEditText).getText().toString();
                            createFilteredDeck(new JSONArray(), new Object[] { "is:new added:" + previewDays, 9999, Sched.DYN_OLDEST }, false);
                        }
                    });
                    break;
                case CUSTOM_STUDY_TAGS:
                    mCustomStudyTextView1.setText("");
                    mCustomStudyTextView2.setText(res.getString(R.string.custom_study_tags));
                    mCustomStudyEditText.setText(AnkiDroidApp.getSharedPrefs(getActivity()).getString("customTags", ""));
                    styledDialog.setButtonOnClickListener(Dialog.BUTTON_POSITIVE, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            String tags = ((EditText) mCustomStudyEditText).getText().toString();
                            createFilteredDeck(new JSONArray(), new Object[] { "(is:new or is:due) " + tags, 9999, Sched.DYN_RANDOM }, true);
                        }
                    });
                    break;
            }
    }
}
Also used : EditText(android.widget.EditText) DialogInterface(android.content.DialogInterface) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) OnClickListener(android.content.DialogInterface.OnClickListener) JSONObject(org.json.JSONObject) Collection(com.ichi2.libanki.Collection) JSONObject(org.json.JSONObject) Resources(android.content.res.Resources)

Example 100 with JSONArray

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

the class StudyOptionsFragment method createFilteredDeck.

private void createFilteredDeck(JSONArray delays, Object[] terms, Boolean resched) {
    JSONObject dyn;
    if (AnkiDroidApp.colIsOpen()) {
        Collection col = AnkiDroidApp.getCol();
        try {
            String deckName = col.getDecks().current().getString("name");
            String customStudyDeck = getResources().getString(R.string.custom_study_deck_name);
            JSONObject cur = col.getDecks().byName(customStudyDeck);
            if (cur != null) {
                if (cur.getInt("dyn") != 1) {
                    StyledDialog.Builder builder = new StyledDialog.Builder(getActivity());
                    builder.setMessage(R.string.custom_study_deck_exists);
                    builder.setNegativeButton(getResources().getString(R.string.cancel), new OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                        // 
                        }
                    });
                    builder.create().show();
                    return;
                } else {
                    // safe to empty
                    col.getSched().emptyDyn(cur.getLong("id"));
                    // reuse; don't delete as it may have children
                    dyn = cur;
                    col.getDecks().select(cur.getLong("id"));
                }
            } else {
                long did = col.getDecks().newDyn(customStudyDeck);
                dyn = col.getDecks().get(did);
            }
            // and then set various options
            dyn.put("delays", delays);
            JSONArray ar = dyn.getJSONArray("terms");
            ar.getJSONArray(0).put(0, new StringBuilder("deck:\"").append(deckName).append("\" ").append(terms[0]).toString());
            ar.getJSONArray(0).put(1, terms[1]);
            ar.getJSONArray(0).put(2, terms[2]);
            dyn.put("resched", resched);
            if (mFragmented) {
                Bundle config = new Bundle();
                config.putString("searchSuffix", "'deck:" + dyn.getString("name") + "'");
                initAllContentViews(getLayoutInflater(config));
                finishCongrats();
            } else {
                // Load a new fragment with the filtered deck view. The config passed is null, so it uses the
                // current deck. The deck we just created is internally set as the current deck.
                ((StudyOptionsActivity) getActivity()).loadContent(false, null);
            }
            // Initial rebuild
            mProgressDialog = StyledProgressDialog.show(getActivity(), "", getResources().getString(R.string.rebuild_custom_study_deck), true);
            DeckTask.launchDeckTask(DeckTask.TASK_TYPE_REBUILD_CRAM, mRebuildCustomStudyListener, new DeckTask.TaskData(AnkiDroidApp.getCol(), AnkiDroidApp.getCol().getDecks().selected(), mFragmented));
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
    }
}
Also used : DialogInterface(android.content.DialogInterface) Bundle(android.os.Bundle) ChartBuilder(com.ichi2.charts.ChartBuilder) StyledDialog(com.ichi2.themes.StyledDialog) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) TaskData(com.ichi2.async.DeckTask.TaskData) DeckTask(com.ichi2.async.DeckTask) JSONObject(org.json.JSONObject) Collection(com.ichi2.libanki.Collection) OnClickListener(android.content.DialogInterface.OnClickListener)

Aggregations

JSONArray (com.ichi2.utils.JSONArray)188 JSONObject (com.ichi2.utils.JSONObject)97 Collection (com.ichi2.libanki.Collection)54 Test (org.junit.Test)44 ArrayList (java.util.ArrayList)42 Note (com.ichi2.libanki.Note)40 Card (com.ichi2.libanki.Card)39 DeckConfig (com.ichi2.libanki.DeckConfig)37 RobolectricTest (com.ichi2.anki.RobolectricTest)36 Deck (com.ichi2.libanki.Deck)19 Model (com.ichi2.libanki.Model)19 JSONException (com.ichi2.utils.JSONException)19 Cursor (android.database.Cursor)17 HashMap (java.util.HashMap)16 SuppressLint (android.annotation.SuppressLint)15 IOException (java.io.IOException)14 NonNull (androidx.annotation.NonNull)13 File (java.io.File)10 Response (okhttp3.Response)10 JSONArray (org.json.JSONArray)8