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);
}
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);
}
}
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);
}
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;
}
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;
}
}
Aggregations