Search in sources :

Example 86 with Card

use of org.liberty.android.fantastischmemo.entity.Card in project AnyMemo by helloworld1.

the class QuizletDownloadHelper method downloadCardset.

/**
 * Download cardsets list from Quizlet and save to a db file
 *
 * @param setId
 *            cardset ID
 * @param authToken
 *            oauth token
 * @return The path of saved db file
 * @throws IOException
 *             IOException If http response code is not 2xx
 * @throws JSONException
 *             If the response is invalid JSON
 */
public String downloadCardset(String setId, String authToken) throws IOException, JSONException {
    URL url;
    // needs authtoken
    if (authToken != null) {
        url = new URL(AMEnv.QUIZLET_API_ENDPOINT + "/sets/" + setId);
    } else {
        String urlString = String.format(AMEnv.QUIZLET_API_ENDPOINT + "/sets/" + "%1$s?client_id=%2$s", URLEncoder.encode(setId, "UTF-8"), URLEncoder.encode(AMEnv.QUIZLET_CLIENT_ID, "UTF-8"));
        url = new URL(urlString);
    }
    String response = makeApiCall(url, authToken);
    JSONObject rootObject = new JSONObject(response);
    JSONArray flashcardsArray = rootObject.getJSONArray("terms");
    int termCount = rootObject.getInt("term_count");
    boolean hasImage = rootObject.getBoolean("has_images");
    List<Card> cardList = new ArrayList<Card>(termCount);
    // handle image
    String dbname = downloaderUtils.validateDBName(rootObject.getString("title")) + ".db";
    String imagePath = AMEnv.DEFAULT_IMAGE_PATH + dbname + "/";
    if (hasImage) {
        FileUtils.forceMkdir(new File(imagePath));
    }
    for (int i = 0; i < flashcardsArray.length(); i++) {
        JSONObject jsonItem = flashcardsArray.getJSONObject(i);
        String question = jsonItem.getString("term");
        String answer = jsonItem.getString("definition");
        // Download images, ignore image downloading error.
        try {
            if (jsonItem.has("image") && !jsonItem.isNull("image") && hasImage) {
                JSONObject imageItem = jsonItem.getJSONObject("image");
                String imageUrl = imageItem.getString("url");
                String downloadFilename = Uri.parse(imageUrl).getLastPathSegment();
                downloaderUtils.downloadFile(imageUrl, imagePath + downloadFilename);
                answer += "<br /><img src=\"" + downloadFilename + "\"/>";
            }
        } catch (Exception e) {
            Log.e(TAG, "Error downloading image.", e);
        }
        Card card = new Card();
        card.setQuestion(question);
        card.setAnswer(answer);
        card.setCategory(new Category());
        card.setLearningData(new LearningData());
        cardList.add(card);
    }
    /* Make a valid dbname from the title */
    String dbpath = AMEnv.DEFAULT_ROOT_PATH;
    String fullpath = dbpath + dbname;
    amFileUtil.deleteFileWithBackup(fullpath);
    AnyMemoDBOpenHelper helper = AnyMemoDBOpenHelperManager.getHelper(fullpath);
    try {
        CardDao cardDao = helper.getCardDao();
        cardDao.createCards(cardList);
        long count = helper.getCardDao().getTotalCount(null);
        if (count <= 0L) {
            throw new RuntimeException("Downloaded empty db.");
        }
    } finally {
        AnyMemoDBOpenHelperManager.releaseHelper(helper);
    }
    return fullpath;
}
Also used : Category(org.liberty.android.fantastischmemo.entity.Category) JSONArray(org.json.JSONArray) ArrayList(java.util.ArrayList) URL(java.net.URL) JSONException(org.json.JSONException) IOException(java.io.IOException) Card(org.liberty.android.fantastischmemo.entity.Card) AnyMemoDBOpenHelper(org.liberty.android.fantastischmemo.common.AnyMemoDBOpenHelper) JSONObject(org.json.JSONObject) File(java.io.File) LearningData(org.liberty.android.fantastischmemo.entity.LearningData) CardDao(org.liberty.android.fantastischmemo.dao.CardDao)

Example 87 with Card

use of org.liberty.android.fantastischmemo.entity.Card in project AnyMemo by helloworld1.

the class CardPlayerService method reset.

/*
     * Stop playing and reset the context
     */
public void reset() {
    // When we reset, we want to know the current card
    // to set so the newly created context will have the
    // current card previously set
    // If it is null, we will leave it undertermined.
    Card currentCard = null;
    if (cardPlayerContext != null) {
        stopPlaying();
        currentCard = cardPlayerContext.getCurrentCard();
    }
    cardPlayerContext = new CardPlayerContext(cardPlayerEventHandler, cardTTSUtil, handler, dbOpenHelper, option.getCardPlayerIntervalBetweenQA(), option.getCardPlayerIntervalBetweenCards(), option.getCardPlayerShuffleEnabled(), option.getCardPlayerRepeatEnabled());
    if (currentCard != null) {
        cardPlayerContext.setCurrentCard(currentCard);
    }
}
Also used : CardPlayerContext(org.liberty.android.fantastischmemo.service.cardplayer.CardPlayerContext) Card(org.liberty.android.fantastischmemo.entity.Card)

Example 88 with Card

use of org.liberty.android.fantastischmemo.entity.Card in project AnyMemo by helloworld1.

the class CardProvider method buildCursorFromCards.

/**
 * Build cursor from a list of cards.
 */
private Cursor buildCursorFromCards(List<Card> cards) {
    String[] columnNames = { "id", "ordinal", "question", "answer", "category" };
    MatrixCursor cursor = new MatrixCursor(columnNames, cards.size());
    for (Card c : cards) {
        cursor.addRow(new String[] { c.getId().toString(), c.getOrdinal().toString(), c.getQuestion(), c.getAnswer(), c.getCategory().getName() });
    }
    return cursor;
}
Also used : MatrixCursor(android.database.MatrixCursor) Card(org.liberty.android.fantastischmemo.entity.Card)

Example 89 with Card

use of org.liberty.android.fantastischmemo.entity.Card in project AnyMemo by helloworld1.

the class CardProvider method query.

/**
 * The query returns null if the db is not valid.
 */
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
    List<String> uriSegments = uri.getPathSegments();
    String dbPath = AMEnv.DEFAULT_ROOT_PATH + uriSegments.get(0);
    if (!new File(dbPath).exists()) {
        return null;
    }
    AnyMemoDBOpenHelper helper = AnyMemoDBOpenHelperManager.getHelper(getContext(), dbPath);
    try {
        CardDao cardDao = helper.getCardDao();
        Cursor resultCursor = null;
        switch(sUriMatcher.match(uri)) {
            case COUNT_URI:
                {
                    long count = cardDao.getTotalCount(null);
                    resultCursor = buildCursorFromCount(count);
                    break;
                }
            case RANDOM_URI:
                {
                    int count = Integer.valueOf(uriSegments.get(2));
                    List<Card> cards = cardDao.getRandomCards(null, count);
                    resultCursor = buildCursorFromCards(cards);
                    break;
                }
            case ORD_URI:
                {
                    int ord = Integer.valueOf(uriSegments.get(2));
                    Card card = cardDao.getByOrdinal(ord);
                    resultCursor = buildCursorFromCard(card);
                    break;
                }
            case ID_URI:
                {
                    int id = Integer.valueOf(uriSegments.get(2));
                    Card card = cardDao.getById(id);
                    resultCursor = buildCursorFromCard(card);
                    break;
                }
            case START_URI:
                {
                    int start = Integer.valueOf(uriSegments.get(2));
                    int count = Integer.valueOf(uriSegments.get(4));
                    List<Card> cards = cardDao.getCardsByOrdinalAndSize(start, count);
                    resultCursor = buildCursorFromCards(cards);
                    break;
                }
            case ALL_URI:
                {
                    List<Card> cards = cardDao.getAllCards(null);
                    resultCursor = buildCursorFromCards(cards);
                    break;
                }
            default:
                throw new IllegalArgumentException("No matching handler for uri: " + uri);
        }
        if (resultCursor == null) {
            Log.e(TAG, "No case matched for uri: " + uri);
        }
        return resultCursor;
    } finally {
        AnyMemoDBOpenHelperManager.releaseHelper(helper);
    }
}
Also used : AnyMemoDBOpenHelper(org.liberty.android.fantastischmemo.common.AnyMemoDBOpenHelper) ArrayList(java.util.ArrayList) List(java.util.List) MatrixCursor(android.database.MatrixCursor) Cursor(android.database.Cursor) File(java.io.File) CardDao(org.liberty.android.fantastischmemo.dao.CardDao) Card(org.liberty.android.fantastischmemo.entity.Card)

Example 90 with Card

use of org.liberty.android.fantastischmemo.entity.Card in project AnyMemo by helloworld1.

the class LearnQueueManager method dequeue.

@Override
public synchronized Card dequeue() {
    shuffle();
    if (!learnQueue.isEmpty()) {
        Card c = learnQueue.get(0);
        Log.d(TAG, "Dequeue card: " + c.getId());
        return c;
    } else {
        return null;
    }
}
Also used : Card(org.liberty.android.fantastischmemo.entity.Card)

Aggregations

Card (org.liberty.android.fantastischmemo.entity.Card)95 CardDao (org.liberty.android.fantastischmemo.dao.CardDao)61 SmallTest (android.support.test.filters.SmallTest)43 Test (org.junit.Test)43 AbstractExistingDBTest (org.liberty.android.fantastischmemo.test.AbstractExistingDBTest)41 Category (org.liberty.android.fantastischmemo.entity.Category)30 AnyMemoDBOpenHelper (org.liberty.android.fantastischmemo.common.AnyMemoDBOpenHelper)28 LearningData (org.liberty.android.fantastischmemo.entity.LearningData)25 CategoryDao (org.liberty.android.fantastischmemo.dao.CategoryDao)20 LearningDataDao (org.liberty.android.fantastischmemo.dao.LearningDataDao)13 File (java.io.File)12 ArrayList (java.util.ArrayList)11 SQLException (java.sql.SQLException)9 QueueManager (org.liberty.android.fantastischmemo.queue.QueueManager)9 IOException (java.io.IOException)6 Date (java.util.Date)6 LearnQueueManager (org.liberty.android.fantastischmemo.queue.LearnQueueManager)6 URL (java.net.URL)5 FileWriter (java.io.FileWriter)4 Scheduler (org.liberty.android.fantastischmemo.scheduler.Scheduler)4