Search in sources :

Example 46 with JSONException

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

the class DeckTask method doInBackgroundConfSetSubdecks.

private TaskData doInBackgroundConfSetSubdecks(TaskData... params) {
    // Log.i(AnkiDroidApp.TAG, "doInBackgroundConfSetSubdecks");
    Object[] data = params[0].getObjArray();
    Collection col = (Collection) data[0];
    JSONObject deck = (JSONObject) data[1];
    JSONObject conf = (JSONObject) data[2];
    try {
        TreeMap<String, Long> children = col.getDecks().children(deck.getLong("id"));
        for (Map.Entry<String, Long> entry : children.entrySet()) {
            JSONObject child = col.getDecks().get(entry.getValue());
            if (child.getInt("dyn") == 1) {
                continue;
            }
            TaskData newParams = new TaskData(new Object[] { col, child, conf });
            boolean changed = doInBackgroundConfChange(newParams).getBoolean();
            if (!changed) {
                return new TaskData(false);
            }
        }
        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) HashMap(java.util.HashMap) Map(java.util.Map) TreeMap(java.util.TreeMap)

Example 47 with JSONException

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

the class NoteService method createEmptyNote.

/**
 * Creates an empty Note from given Model
 *
 * @param model the model in JSOBObject format
 * @return a new note instance
 */
public static MultimediaEditableNote createEmptyNote(JSONObject model) {
    try {
        JSONArray fieldsArray = model.getJSONArray("flds");
        int numOfFields = fieldsArray.length();
        if (numOfFields > 0) {
            MultimediaEditableNote note = new MultimediaEditableNote();
            note.setNumFields(numOfFields);
            for (int i = 0; i < numOfFields; i++) {
                JSONObject fieldObject = fieldsArray.getJSONObject(i);
                TextField uiTextField = new TextField();
                uiTextField.setName(fieldObject.getString("name"));
                uiTextField.setText(fieldObject.getString("name"));
                note.setField(i, uiTextField);
            }
            note.setModelId(model.getLong("id"));
            return note;
        }
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}
Also used : MultimediaEditableNote(com.ichi2.anki.multimediacard.impl.MultimediaEditableNote) IMultimediaEditableNote(com.ichi2.anki.multimediacard.IMultimediaEditableNote) JSONObject(org.json.JSONObject) JSONArray(org.json.JSONArray) TextField(com.ichi2.anki.multimediacard.fields.TextField) JSONException(org.json.JSONException)

Example 48 with JSONException

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

the class MultimediaCardEditorActivity method showModelSelectDialog.

private Dialog showModelSelectDialog() {
    StyledDialog dialog = null;
    StyledDialog.Builder builder = new StyledDialog.Builder(this);
    ArrayList<CharSequence> dialogItems = new ArrayList<CharSequence>();
    // Use this array to know which ID is associated with each
    // Item(name)
    final ArrayList<Long> dialogIds = new ArrayList<Long>();
    ArrayList<JSONObject> models = mCol.getModels().all();
    Collections.sort(models, new JSONNameComparator());
    builder.setTitle(R.string.note_type);
    for (JSONObject m : models) {
        try {
            dialogItems.add(m.getString("name"));
            dialogIds.add(m.getLong("id"));
        } catch (JSONException e) {
            Log.e("Multimedia Editor", e.getMessage());
        }
    }
    // Convert to Array
    String[] items2 = new String[dialogItems.size()];
    dialogItems.toArray(items2);
    builder.setItems(items2, new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int item) {
            long oldModelId;
            try {
                oldModelId = mCol.getModels().current().getLong("id");
            } catch (JSONException e) {
                Log.e("Multimedia Editor", e.getMessage());
                return;
            }
            long newId = dialogIds.get(item);
            if (oldModelId != newId) {
                changeCurrentModel(newId);
                createEditorUI(mNote);
            }
        }
    });
    dialog = builder.create();
    return dialog;
}
Also used : JSONNameComparator(com.ichi2.utils.JSONNameComparator) DialogInterface(android.content.DialogInterface) StyledDialog(com.ichi2.themes.StyledDialog) ArrayList(java.util.ArrayList) JSONException(org.json.JSONException) SuppressLint(android.annotation.SuppressLint) JSONObject(org.json.JSONObject)

Example 49 with JSONException

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

the class Sched method progressToday.

/**
 * returns today's progress
 *
 * @param counts (if empty, cached version will be used if any)
 * @param card
 * @return [progressCurrentDeck, progressAllDecks, leftCards, eta]
 */
public float[] progressToday(TreeSet<Object[]> counts, Card card, boolean eta) {
    try {
        int doneCurrent = 0;
        int[] leftCurrent = new int[] { 0, 0, 0 };
        String[] cs = new String[] { "new", "lrn", "rev" };
        long currentDid = 0;
        // current selected deck
        if (counts == null) {
            JSONObject deck = mCol.getDecks().current();
            currentDid = deck.getLong("id");
            for (String s : cs) {
                doneCurrent += deck.getJSONArray(s + "Today").getInt(1);
            }
            if (card != null) {
                int idx = countIdx(card);
                leftCurrent[idx] += idx == 1 ? card.getLeft() / 1000 : 1;
            } else {
                reset();
            }
            leftCurrent[0] += mNewCount;
            leftCurrent[1] += mLrnCount;
            leftCurrent[2] += mRevCount;
        }
        // refresh deck progresses with fresh counts if necessary
        if (counts != null || mCachedDeckCounts == null) {
            if (mCachedDeckCounts == null) {
                mCachedDeckCounts = new HashMap<Long, Pair<String[], long[]>>();
            }
            mCachedDeckCounts.clear();
            if (counts == null) {
                // reload counts
                counts = (TreeSet<Object[]>) deckCounts()[0];
            }
            for (Object[] d : counts) {
                int done = 0;
                JSONObject deck = mCol.getDecks().get((Long) d[1]);
                for (String s : cs) {
                    done += deck.getJSONArray(s + "Today").getInt(1);
                }
                mCachedDeckCounts.put((Long) d[1], new Pair<String[], long[]>((String[]) d[0], new long[] { done, (Integer) d[2], (Integer) d[3], (Integer) d[4] }));
            }
        }
        int doneAll = 0;
        int[] leftAll = new int[] { 0, 0, 0 };
        for (Map.Entry<Long, Pair<String[], long[]>> d : mCachedDeckCounts.entrySet()) {
            // || mCol.getDecks().isDyn(d.getKey());
            boolean exclude = d.getKey() == currentDid;
            if (d.getValue().first.length == 1) {
                if (exclude) {
                    // don't count cached version of current deck
                    continue;
                }
                long[] c = d.getValue().second;
                doneAll += c[0];
                leftAll[0] += c[1];
                leftAll[1] += c[2];
                leftAll[2] += c[3];
            } else if (exclude) {
                // exclude cached values for current deck in order to avoid double count
                long[] c = d.getValue().second;
                doneAll -= c[0];
                leftAll[0] -= c[1];
                leftAll[1] -= c[2];
                leftAll[2] -= c[3];
            }
        }
        doneAll += doneCurrent;
        leftAll[0] += leftCurrent[0];
        leftAll[1] += leftCurrent[1];
        leftAll[2] += leftCurrent[2];
        int totalAll = doneAll + leftAll[0] + leftAll[1] + leftAll[2];
        int totalCurrent = doneCurrent + leftCurrent[0] + leftCurrent[1] + leftCurrent[2];
        float progressCurrent = -1;
        if (totalCurrent != 0) {
            progressCurrent = (float) doneCurrent / (float) totalCurrent;
        }
        float progressTotal = -1;
        if (totalAll != 0) {
            progressTotal = (float) doneAll / (float) totalAll;
        }
        return new float[] { progressCurrent, progressTotal, totalAll - doneAll, eta ? eta(leftAll, false) : -1 };
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
}
Also used : JSONException(org.json.JSONException) JSONObject(org.json.JSONObject) JSONObject(org.json.JSONObject) HashMap(java.util.HashMap) Map(java.util.Map) Pair(com.ichi2.anki.Pair)

Example 50 with JSONException

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

the class Connection method doInBackgroundRegister.

private Payload doInBackgroundRegister(Payload data) {
    String username = (String) data.data[0];
    String password = (String) data.data[1];
    BasicHttpSyncer server = new RemoteServer(this, null);
    HttpResponse ret = server.register(username, password);
    String hostkey = null;
    boolean valid = false;
    String status = null;
    if (ret != null) {
        data.returnType = ret.getStatusLine().getStatusCode();
        if (data.returnType == 200) {
            try {
                JSONObject jo = (new JSONObject(server.stream2String(ret.getEntity().getContent())));
                status = jo.getString("status");
                if (status.equals("ok")) {
                    hostkey = jo.getString("hkey");
                    valid = (hostkey != null) && (hostkey.length() > 0);
                }
            } catch (JSONException e) {
            } catch (IllegalStateException e) {
                throw new RuntimeException(e);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
    if (valid) {
        data.success = true;
        data.data = new String[] { username, hostkey };
    } else {
        data.success = false;
        data.data = new String[] { status != null ? status : AnkiDroidApp.getAppResources().getString(R.string.connection_error_message) };
    }
    return data;
}
Also used : BasicHttpSyncer(com.ichi2.libanki.sync.BasicHttpSyncer) JSONObject(org.json.JSONObject) HttpResponse(org.apache.http.HttpResponse) JSONException(org.json.JSONException) IOException(java.io.IOException) RemoteServer(com.ichi2.libanki.sync.RemoteServer)

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