Example usage for android.database Cursor getCount

List of usage examples for android.database Cursor getCount

Introduction

In this page you can find the example usage for android.database Cursor getCount.

Prototype

int getCount();

Source Link

Document

Returns the numbers of rows in the cursor.

Usage

From source file:com.ichi2.anki.tests.ContentProviderTest.java

/**
 * Test that a query for all the notes added in setup() looks correct
 *///ww  w .  ja  va2s . com
public void testQueryNoteIds() {
    final ContentResolver cr = getContext().getContentResolver();
    // Query all available notes
    final Cursor allNotesCursor = cr.query(FlashCardsContract.Note.CONTENT_URI, null, "tag:" + TEST_TAG, null,
            null);
    assertNotNull(allNotesCursor);
    try {
        assertEquals("Check number of results", mCreatedNotes.size(), allNotesCursor.getCount());
        while (allNotesCursor.moveToNext()) {
            // Check that it's possible to leave out columns from the projection
            for (int i = 0; i < FlashCardsContract.Note.DEFAULT_PROJECTION.length; i++) {
                String[] projection = removeFromProjection(FlashCardsContract.Note.DEFAULT_PROJECTION, i);
                String noteId = allNotesCursor
                        .getString(allNotesCursor.getColumnIndex(FlashCardsContract.Note._ID));
                Uri noteUri = Uri.withAppendedPath(FlashCardsContract.Note.CONTENT_URI, noteId);
                final Cursor singleNoteCursor = cr.query(noteUri, projection, null, null, null);
                assertNotNull("Check that there is a valid cursor for detail data", singleNoteCursor);
                try {
                    assertEquals("Check that there is exactly one result", 1, singleNoteCursor.getCount());
                    assertTrue("Move to beginning of cursor after querying for detail data",
                            singleNoteCursor.moveToFirst());
                    // Check columns
                    assertEquals("Check column count", projection.length, singleNoteCursor.getColumnCount());
                    for (int j = 0; j < projection.length; j++) {
                        assertEquals("Check column name " + j, projection[j],
                                singleNoteCursor.getColumnName(j));
                    }
                } finally {
                    singleNoteCursor.close();
                }
            }
        }
    } finally {
        allNotesCursor.close();
    }
}

From source file:com.amarinfingroup.net.tasks.FormLoaderTask.java

/**
 * Initialize {@link FormEntryController} with {@link FormDef} from binary or
 * from XML. If given an instance, it will be used to fill the {@link FormDef}
 * .// www. ja v a  2 s. c om
 */
@Override
protected FECWrapper doInBackground(String... path) {
    FormEntryController fec = null;
    FormDef fd = null;
    FileInputStream fis = null;
    mErrorMsg = null;

    String formPath = path[0];

    File formXml = new File(formPath);
    String formHash = FileUtils.getMd5Hash(formXml);
    File formBin = new File(Collect.CACHE_PATH + File.separator + formHash + ".formdef");

    publishProgress(Collect.getInstance().getString(R.string.survey_loading_reading_form_message));

    FormDef.EvalBehavior mode = AdminPreferencesActivity
            .getConfiguredFormProcessingLogic(Collect.getInstance());
    FormDef.setEvalBehavior(mode);

    //    FormDef.setDefaultEventNotifier(new EventNotifier() {
    //
    //      @Override
    //      public void publishEvent(Event event) {
    //        Log.d("FormDef", event.asLogLine());
    //      }
    //    });

    if (formBin.exists()) {
        // if we have binary, deserialize binary
        Log.i(t, "Attempting to load " + formXml.getName() + " from cached file: " + formBin.getAbsolutePath());
        fd = deserializeFormDef(formBin);
        if (fd == null) {
            // some error occured with deserialization. Remove the file, and make a
            // new .formdef
            // from xml
            Log.w(t, "Deserialization FAILED!  Deleting cache file: " + formBin.getAbsolutePath());
            formBin.delete();
        }
    }
    if (fd == null) {
        // no binary, read from xml
        try {
            Log.i(t, "Attempting to load from: " + formXml.getAbsolutePath());
            fis = new FileInputStream(formXml);
            fd = XFormUtils.getFormFromInputStream(fis);
            if (fd == null) {
                mErrorMsg = "Error reading XForm file";
            } else {
                serializeFormDef(fd, formPath);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            mErrorMsg = e.getMessage();
        } catch (XFormParseException e) {
            mErrorMsg = e.getMessage();
            e.printStackTrace();
        } catch (Exception e) {
            mErrorMsg = e.getMessage();
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(fis);
        }
    }

    if (mErrorMsg != null || fd == null) {
        return null;
    }

    // set paths to /sdcard/odk/forms/formfilename-media/
    String formFileName = formXml.getName().substring(0, formXml.getName().lastIndexOf("."));
    File formMediaDir = new File(formXml.getParent(), formFileName + "-media");

    externalDataManager = new ExternalDataManagerImpl(formMediaDir);

    // add external data function handlers
    ExternalDataHandler externalDataHandlerPull = new ExternalDataHandlerPull(externalDataManager);
    fd.getEvaluationContext().addFunctionHandler(externalDataHandlerPull);

    try {
        loadExternalData(formMediaDir);
    } catch (Exception e) {
        mErrorMsg = e.getMessage();
        e.printStackTrace();
        return null;
    }

    if (isCancelled()) {
        // that means that the user has cancelled, so no need to go further
        return null;
    }

    // create FormEntryController from formdef
    FormEntryModel fem = new FormEntryModel(fd);
    fec = new FormEntryController(fem);

    boolean usedSavepoint = false;

    try {
        // import existing data into formdef
        if (mInstancePath != null) {
            File instance = new File(mInstancePath);
            File shadowInstance = SaveToDiskTask.savepointFile(instance);
            if (shadowInstance.exists() && (shadowInstance.lastModified() > instance.lastModified())) {
                // the savepoint is newer than the saved value of the instance.
                // use it.
                usedSavepoint = true;
                instance = shadowInstance;
                Log.w(t, "Loading instance from shadow file: " + shadowInstance.getAbsolutePath());
            }
            if (instance.exists()) {
                // This order is important. Import data, then initialize.
                try {
                    importData(instance, fec);
                    fd.initialize(false, new InstanceInitializationFactory());
                } catch (RuntimeException e) {
                    Log.e(t, e.getMessage(), e);

                    // SCTO-633
                    if (usedSavepoint && !(e.getCause() instanceof XPathTypeMismatchException)) {
                        // this means that the .save file is corrupted or 0-sized, so
                        // don't use it.
                        usedSavepoint = false;
                        mInstancePath = null;
                        fd.initialize(true, new InstanceInitializationFactory());
                    } else {
                        // this means that the saved instance is corrupted.
                        throw e;
                    }
                }
            } else {
                fd.initialize(true, new InstanceInitializationFactory());
            }
        } else {
            fd.initialize(true, new InstanceInitializationFactory());
        }
    } catch (RuntimeException e) {
        Log.e(t, e.getMessage(), e);
        if (e.getCause() instanceof XPathTypeMismatchException) {
            // this is a case of
            // https://bitbucket.org/m.sundt/javarosa/commits/e5d344783e7968877402bcee11828fa55fac69de
            // the data are imported, the survey will be unusable
            // but we should give the option to the user to edit the form
            // otherwise the survey will be TOTALLY inaccessible.
            Log.w(t, "We have a syntactically correct instance, but the data threw an exception inside JR. We should allow editing.");
        } else {
            mErrorMsg = e.getMessage();
            return null;
        }
    }

    // Remove previous forms
    ReferenceManager._().clearSession();

    // for itemsets.csv, we only check to see if the itemset file has been
    // updated
    File csv = new File(formMediaDir.getAbsolutePath() + "/" + ITEMSETS_CSV);
    String csvmd5 = null;
    if (csv.exists()) {
        csvmd5 = FileUtils.getMd5Hash(csv);
        boolean readFile = false;
        ItemsetDbAdapter ida = new ItemsetDbAdapter();
        ida.open();
        // get the database entry (if exists) for this itemsets.csv, based
        // on the path
        Cursor c = ida.getItemsets(csv.getAbsolutePath());
        if (c != null) {
            if (c.getCount() == 1) {
                c.moveToFirst(); // should be only one, ever, if any
                String oldmd5 = c.getString(c.getColumnIndex("hash"));
                if (oldmd5.equals(csvmd5)) {
                    // they're equal, do nothing
                } else {
                    // the csv has been updated, delete the old entries
                    ida.dropTable(ItemsetDbAdapter.getMd5FromString(csv.getAbsolutePath()),
                            csv.getAbsolutePath());
                    // and read the new
                    readFile = true;
                }
            } else {
                // new csv, add it
                readFile = true;
            }
            c.close();
        }
        ida.close();
        if (readFile) {
            readCSV(csv, csvmd5, ItemsetDbAdapter.getMd5FromString(csv.getAbsolutePath()));
        }
    }

    // This should get moved to the Application Class
    if (ReferenceManager._().getFactories().length == 0) {
        // this is /sdcard/odk
        ReferenceManager._().addReferenceFactory(new FileReferenceFactory(Collect.ODK_ROOT));
    }

    // Set jr://... to point to /sdcard/odk/forms/filename-media/
    ReferenceManager._().addSessionRootTranslator(
            new RootTranslator("jr://images/", "jr://file/forms/" + formFileName + "-media/"));
    ReferenceManager._().addSessionRootTranslator(
            new RootTranslator("jr://image/", "jr://file/forms/" + formFileName + "-media/"));
    ReferenceManager._().addSessionRootTranslator(
            new RootTranslator("jr://audio/", "jr://file/forms/" + formFileName + "-media/"));
    ReferenceManager._().addSessionRootTranslator(
            new RootTranslator("jr://video/", "jr://file/forms/" + formFileName + "-media/"));

    // clean up vars
    fis = null;
    fd = null;
    formBin = null;
    formXml = null;
    formPath = null;

    FormController fc = new FormController(formMediaDir, fec,
            mInstancePath == null ? null : new File(mInstancePath));
    if (mXPath != null) {
        // we are resuming after having terminated -- set index to this
        // position...
        FormIndex idx = fc.getIndexFromXPath(mXPath);
        fc.jumpToIndex(idx);
    }
    if (mWaitingXPath != null) {
        FormIndex idx = fc.getIndexFromXPath(mWaitingXPath);
        fc.setIndexWaitingForData(idx);
    }
    data = new FECWrapper(fc, usedSavepoint);
    return data;

}

From source file:com.android.contacts.list.ContactEntryListAdapter.java

protected void bindQuickContact(final ContactListItemView view, int partitionIndex, Cursor cursor,
        int photoIdColumn, int contactIdColumn, int lookUpKeyColumn) {
    long photoId = 0;
    if (!cursor.isNull(photoIdColumn)) {
        photoId = cursor.getLong(photoIdColumn);
    }//from   w w w  .  j  a va2 s .com

    //Begin by gangzhou.qi at 2012-7-11 ?10:53:05

    accountType = null;
    accountSet = null;
    accountIconDraw = null;
    accountQuerySelectionArgs = new String[] { cursor.getString(0) };
    Cursor accountCur = null;
    accountCur = mContentResolver.query(ContactsContract.RawContacts.CONTENT_URI, null, accountQuerySelection,
            accountQuerySelectionArgs, null);
    if (accountCur != null && accountCur.getCount() > 0) {
        try {
            accountCur.moveToFirst();
            accountType = accountCur
                    .getString(accountCur.getColumnIndex(ContactsContract.RawContacts.ACCOUNT_TYPE));
            accountSet = accountCur.getString(accountCur.getColumnIndex(ContactsContract.RawContacts.DATA_SET));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            accountCur.close();
        }
    }

    if (accountType != null) {
        accountIconDraw = AccountTypeManager.getInstance(mContext)
                .getAccountType(AccountTypeWithDataSet.get(accountType, accountSet)).getDisplayIcon(mContext);
    }
    Log.d(TAG, "accountIconDraw:" + accountIconDraw);
    QuickContactBadgeWithAccount quickContact = view.getQuickContact();

    //if(accountIconDraw != null){
    quickContact.setAccountDrawable(accountIconDraw);
    //}
    //Ended by gangzhou.qi at 2012-7-11 ?10:53:05

    quickContact.assignContactUri(getContactUri(partitionIndex, cursor, contactIdColumn, lookUpKeyColumn));
    getPhotoLoader().loadPhoto(quickContact, photoId, false, mDarkTheme);
}

From source file:net.smart_json_database.JSONDatabase.java

private void updateTagMap() {
    String sql = "SELECT * FROM " + TABLE_TAG;
    SQLiteDatabase db = dbHelper.getReadableDatabase();
    Cursor c = db.rawQuery(sql, new String[] {});
    if (c.getCount() > 0) {
        int col_id = c.getColumnIndex("tag_uid");
        int col_name = c.getColumnIndex("name");

        c.moveToFirst();// www  .  j a  v  a  2 s  .  c o m
        do {
            tags.put(c.getString(col_name), new Integer(c.getInt(col_id)));
            invertedTags.put(new Integer(c.getInt(col_id)), c.getString(col_name));
        } while (c.moveToNext());
    }
    c.close();
    db.close();
}

From source file:com.ichi2.anki.tests.ContentProviderTest.java

/**
 * Move all the cards from their old decks to the first deck that was added in setup()
 */// w  w w.ja v  a2s . co m
public void testMoveCardsToOtherDeck() {
    final ContentResolver cr = getContext().getContentResolver();
    // Query all available notes
    final Cursor allNotesCursor = cr.query(FlashCardsContract.Note.CONTENT_URI, null, "tag:" + TEST_TAG, null,
            null);
    assertNotNull(allNotesCursor);
    try {
        assertEquals("Check number of results", mCreatedNotes.size(), allNotesCursor.getCount());
        while (allNotesCursor.moveToNext()) {
            // Now iterate over all cursors
            Uri cardsUri = Uri.withAppendedPath(
                    Uri.withAppendedPath(FlashCardsContract.Note.CONTENT_URI,
                            allNotesCursor
                                    .getString(allNotesCursor.getColumnIndex(FlashCardsContract.Note._ID))),
                    "cards");
            final Cursor cardsCursor = cr.query(cardsUri, null, null, null, null);
            assertNotNull("Check that there is a valid cursor after query for cards", cardsCursor);
            try {
                assertTrue("Check that there is at least one result for cards", cardsCursor.getCount() > 0);
                while (cardsCursor.moveToNext()) {
                    long targetDid = mTestDeckIds[0];
                    // Move to test deck
                    ContentValues values = new ContentValues();
                    values.put(FlashCardsContract.Card.DECK_ID, targetDid);
                    Uri cardUri = Uri.withAppendedPath(cardsUri, cardsCursor
                            .getString(cardsCursor.getColumnIndex(FlashCardsContract.Card.CARD_ORD)));
                    cr.update(cardUri, values, null, null);
                    Cursor movedCardCur = cr.query(cardUri, null, null, null, null);
                    assertNotNull("Check that there is a valid cursor after moving card", movedCardCur);
                    assertTrue("Move to beginning of cursor after moving card", movedCardCur.moveToFirst());
                    long did = movedCardCur
                            .getLong(movedCardCur.getColumnIndex(FlashCardsContract.Card.DECK_ID));
                    assertEquals("Make sure that card is in new deck", targetDid, did);
                }
            } finally {
                cardsCursor.close();
            }
        }
    } finally {
        allNotesCursor.close();
    }
}

From source file:mobisocial.bento.ebento.io.EventManager.java

private Bitmap getEventImage(Uri objUri, String eventUuid) {
    Bitmap bitmap = null;/*  w w  w.ja  v a 2  s  . c  om*/
    int targetWidth = BitmapHelper.MAX_IMAGE_WIDTH;
    int targetHeight = BitmapHelper.MAX_IMAGE_HEIGHT;
    float degrees = 0;

    DbFeed dbFeed = mMusubi.objForUri(objUri).getSubfeed();

    Cursor c = dbFeed.query();
    int numberOfObjInSubFeed = c.getCount();
    c.moveToFirst();
    for (int i = 0; i < c.getCount(); i++) {
        Obj object = mMusubi.objForCursor(c);
        bitmap = parseEventImage(object, eventUuid);
        if (bitmap != null)
            break;
        c.moveToNext();
    }
    c.close();

    // if no images in subfeed
    if (numberOfObjInSubFeed == 0 && bitmap == null) {
        bitmap = parseEventImage(mMusubi.objForUri(objUri), eventUuid);
    }

    // dummy
    if (bitmap == null) {
        bitmap = BitmapHelper.getDummyBitmap(targetWidth, targetHeight);
    } else {
        bitmap = BitmapHelper.getResizedBitmap(bitmap, targetWidth, targetHeight, degrees);
    }

    return bitmap;
}

From source file:com.gvccracing.android.tttimer.Tabs.RaceInfoTab.java

public void postData() {
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(
            "http://www.gvccracing.com/?page_id=2525&pass=com.gvccracing.android.tttimer");

    try {// ww  w  .j  a v a  2 s  . co  m
        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);

        InputStream is = response.getEntity().getContent();
        BufferedInputStream bis = new BufferedInputStream(is);
        ByteArrayBuffer baf = new ByteArrayBuffer(20);

        int current = 0;

        while ((current = bis.read()) != -1) {
            baf.append((byte) current);
        }

        /* Convert the Bytes read to a String. */
        String text = new String(baf.toByteArray());

        JSONObject mainJson = new JSONObject(text);
        JSONArray jsonArray = mainJson.getJSONArray("members");

        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject json = jsonArray.getJSONObject(i);

            String firstName = json.getString("fname");
            String lastName = json.getString("lname");
            String licenseStr = json.getString("license");
            Integer license = 0;
            try {
                license = Integer.parseInt(licenseStr);
            } catch (Exception ex) {
                Log.e(LOG_TAG(), "Unable to parse license string");
            }
            long age = json.getLong("age");
            String categoryStr = json.getString("category");
            Integer category = 5;
            try {
                category = Integer.parseInt(categoryStr);
            } catch (Exception ex) {
                Log.e(LOG_TAG(), "Unable to parse category string");
            }
            String phone = json.getString("phone");
            long phoneNumber = 0;
            try {
                phoneNumber = Long.parseLong(phone.replace("-", "").replace("(", "").replace(")", "")
                        .replace(" ", "").replace(".", "").replace("*", ""));
            } catch (Exception e) {
                Log.e(LOG_TAG(), "Unable to parse phone number");
            }
            String gender = json.getString("gender");
            String econtact = json.getString("econtact");
            String econtactPhone = json.getString("econtact_phone");
            long eContactPhoneNumber = 0;
            try {
                eContactPhoneNumber = Long.parseLong(econtactPhone.replace("-", "").replace("(", "")
                        .replace(")", "").replace(" ", "").replace(".", "").replace("*", ""));
            } catch (Exception e) {
                Log.e(LOG_TAG(), "Unable to parse econtact phone number");
            }
            Long member_id = json.getLong("member_id");

            String gvccCategory;
            switch (category) {
            case 1:
            case 2:
            case 3:
                gvccCategory = "A";
                break;
            case 4:
                gvccCategory = "B4";
                break;
            case 5:
                gvccCategory = "B5";
                break;
            default:
                gvccCategory = "B5";
                break;
            }

            Log.w(LOG_TAG(), lastName);
            Cursor racerInfo = Racer.Instance().Read(getActivity(),
                    new String[] { Racer._ID, Racer.FirstName, Racer.LastName, Racer.USACNumber,
                            Racer.PhoneNumber, Racer.EmergencyContactName, Racer.EmergencyContactPhoneNumber },
                    Racer.USACNumber + "=?", new String[] { license.toString() }, null);
            if (racerInfo.getCount() > 0) {
                racerInfo.moveToFirst();
                Long racerID = racerInfo.getLong(racerInfo.getColumnIndex(Racer._ID));
                Racer.Instance().Update(getActivity(), racerID, firstName, lastName, license, 0l, phoneNumber,
                        econtact, eContactPhoneNumber, gender);
                Cursor racerClubInfo = RacerClubInfo.Instance().Read(getActivity(),
                        new String[] { RacerClubInfo._ID, RacerClubInfo.GVCCID, RacerClubInfo.RacerAge,
                                RacerClubInfo.Category },
                        RacerClubInfo.Racer_ID + "=? AND " + RacerClubInfo.Year + "=? AND "
                                + RacerClubInfo.Upgraded + "=?",
                        new String[] { racerID.toString(), "2013", "0" }, null);
                if (racerClubInfo.getCount() > 0) {
                    racerClubInfo.moveToFirst();
                    long racerClubInfoID = racerClubInfo
                            .getLong(racerClubInfo.getColumnIndex(RacerClubInfo._ID));
                    String rciCategory = racerClubInfo
                            .getString(racerClubInfo.getColumnIndex(RacerClubInfo.Category));

                    boolean upgraded = gvccCategory != rciCategory;
                    if (upgraded) {
                        RacerClubInfo.Instance().Update(getActivity(), racerClubInfoID, null, null, null, null,
                                null, null, null, null, null, upgraded);
                        RacerClubInfo.Instance().Create(getActivity(), racerID, null, 2013, gvccCategory, 0, 0,
                                0, age, member_id, false);
                    } else {
                        RacerClubInfo.Instance().Update(getActivity(), racerClubInfoID, null, null, null, null,
                                null, null, null, age, member_id, upgraded);
                    }

                } else {
                    RacerClubInfo.Instance().Create(getActivity(), racerID, null, 2013, gvccCategory, 0, 0, 0,
                            age, member_id, false);
                }
                if (racerClubInfo != null) {
                    racerClubInfo.close();
                }
            } else {
                // TODO: Better birth date
                Uri resultUri = Racer.Instance().Create(getActivity(), firstName, lastName, license, 0l,
                        phoneNumber, econtact, eContactPhoneNumber, gender);
                long racerID = Long.parseLong(resultUri.getLastPathSegment());
                RacerClubInfo.Instance().Create(getActivity(), racerID, null, 2013, gvccCategory, 0, 0, 0, age,
                        member_id, false);
            }
            if (racerInfo != null) {
                racerInfo.close();
            }
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        Log.e(LOG_TAG(), e.getMessage());
    }
}

From source file:com.nookdevs.library.FictionwiseBooks.java

protected void getBooksfromDB() {
    try {/*  ww  w . ja  va2s.  com*/
        m_Files.clear();
        m_ArchivedFiles.clear();
        if (m_Db == null) {
            m_Db = getWritableDatabase();
        }
        String query = "select id, ean,titles,authors,desc,keywords,publisher,cover,published,created,path,series, bookid, downloadUrl , status from books";
        Cursor cursor = m_Db.rawQuery(query, null);
        int size = cursor.getCount();
        cursor.moveToFirst();
        for (int i = 0; i < size; i++) {
            String bookId = cursor.getString(12);
            String path = cursor.getString(10);
            ScannedFile sf = new ScannedFile(path, false);
            if (path != null && !path.trim().equals("")) {
                sf.updateLastAccessDate();
            }
            m_BookIdMap.put(bookId, sf);
            sf.setBookID(bookId);
            File f = new File(m_BaseDir + "." + sf.getBookID() + ".archive");
            if (f.exists()) {
                sf.setStatus(BNBooks.ARCHIVED);
            }
            if (BNBooks.ARCHIVED.equals(sf.getStatus())) {
                m_ArchivedFiles.add(sf);
            } else {
                m_Files.add(sf);
            }
            sf.setDownloadUrl(cursor.getString(13));
            sf.setStatus(cursor.getString(14));
            sf.setEan(cursor.getString(1));
            sf.setPublisher(cursor.getString(6));
            sf.setCover(cursor.getString(7));
            sf.setPublishedDate(new Date(cursor.getLong(8)));
            sf.setCreatedDate(new Date(cursor.getLong(9)));
            String title = cursor.getString(2);
            StringTokenizer token = new StringTokenizer(title, ",");
            List<String> titles = new ArrayList<String>(1);
            while (token.hasMoreTokens()) {
                titles.add(token.nextToken());
            }
            sf.setTitles(titles);
            String author = cursor.getString(3);
            token = new StringTokenizer(author, ",");
            while (token.hasMoreTokens()) {
                String auth = token.nextToken();
                sf.addContributor(auth, "");
            }
            //                String desc = cursor.getString(4);
            //                if (desc != null) {
            //                    sf.setDescription(desc);
            //                }
            //                String keywords = cursor.getString(5);
            //                if (keywords != null) {
            //                    token = new StringTokenizer(keywords, ",");
            //                    while (token.hasMoreTokens()) {
            //                        String keyword = token.nextToken();
            //                        sf.addKeywords(keyword);
            //                    }
            //                }
            sf.setLibrary(m_library);
            sf.setSeries(cursor.getString(11));
            sf.setBookInDB(true);
            cursor.moveToNext();
        }
        cursor.close();
        nookLib.updatePageView(m_Files);
        m_Files.clear();
    } catch (Exception ex) {
        Log.e("FictionwiseBooks", "Exception querying datbase", ex);
    }

}

From source file:com.geoodk.collect.android.tasks.FormLoaderTask.java

/**
 * Initialize {@link FormEntryController} with {@link FormDef} from binary or from XML. If given
 * an instance, it will be used to fill the {@link FormDef}.
 *///  ww  w  .  j a va 2  s  .  c o m
@Override
protected FECWrapper doInBackground(String... path) {
    FormEntryController fec = null;
    FormDef fd = null;
    FileInputStream fis = null;
    mErrorMsg = null;

    String formPath = path[0];

    File formXml = new File(formPath);
    String formHash = FileUtils.getMd5Hash(formXml);
    File formBin = new File(Collect.CACHE_PATH + File.separator + formHash + ".formdef");

    initializeJavaRosa();

    publishProgress(Collect.getInstance().getString(R.string.survey_loading_reading_form_message));

    if (formBin.exists()) {
        // if we have binary, deserialize binary
        Log.i(t, "Attempting to load " + formXml.getName() + " from cached file: " + formBin.getAbsolutePath());
        fd = deserializeFormDef(formBin);
        if (fd == null) {
            // some error occured with deserialization. Remove the file, and make a new .formdef
            // from xml
            Log.w(t, "Deserialization FAILED!  Deleting cache file: " + formBin.getAbsolutePath());
            formBin.delete();
        }
    }
    if (fd == null) {
        // no binary, read from xml
        try {
            Log.i(t, "Attempting to load from: " + formXml.getAbsolutePath());
            fis = new FileInputStream(formXml);
            fd = XFormUtils.getFormFromInputStream(fis);
            if (fd == null) {
                mErrorMsg = "Error reading XForm file";
            } else {
                serializeFormDef(fd, formPath);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            mErrorMsg = e.getMessage();
        } catch (XFormParseException e) {
            mErrorMsg = e.getMessage();
            e.printStackTrace();
        } catch (Exception e) {
            mErrorMsg = e.getMessage();
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(fis);
        }
    }

    if (mErrorMsg != null || fd == null) {
        return null;
    }

    // set paths to /sdcard/odk/forms/formfilename-media/
    String formFileName = formXml.getName().substring(0, formXml.getName().lastIndexOf("."));
    File formMediaDir = new File(formXml.getParent(), formFileName + "-media");

    externalDataManager = new ExternalDataManagerImpl(formMediaDir);

    // new evaluation context for function handlers
    EvaluationContext ec = new EvaluationContext(null);
    ExternalDataHandler externalDataHandlerPull = new ExternalDataHandlerPull(externalDataManager);
    ec.addFunctionHandler(externalDataHandlerPull);

    fd.setEvaluationContext(ec);

    try {
        loadExternalData(formMediaDir);
    } catch (Exception e) {
        mErrorMsg = e.getMessage();
        e.printStackTrace();
        return null;
    }

    if (isCancelled()) {
        // that means that the user has cancelled, so no need to go further
        return null;
    }

    // create FormEntryController from formdef
    FormEntryModel fem = new FormEntryModel(fd);
    fec = new FormEntryController(fem);

    boolean usedSavepoint = false;

    try {
        // import existing data into formdef
        if (mInstancePath != null) {
            File instance = new File(mInstancePath);
            File shadowInstance = SaveToDiskTask.savepointFile(instance);
            if (shadowInstance.exists() && (shadowInstance.lastModified() > instance.lastModified())) {
                // the savepoint is newer than the saved value of the instance.
                // use it.
                usedSavepoint = true;
                instance = shadowInstance;
                Log.w(t, "Loading instance from shadow file: " + shadowInstance.getAbsolutePath());
            }
            if (instance.exists()) {
                // This order is important. Import data, then initialize.
                try {
                    importData(instance, fec);
                    fd.initialize(false, new InstanceInitializationFactory());
                } catch (RuntimeException e) {
                    Log.e(t, e.getMessage(), e);

                    // SCTO-633
                    if (usedSavepoint && !(e.getCause() instanceof XPathTypeMismatchException)) {
                        // this means that the .save file is corrupted or 0-sized, so don't use it.
                        usedSavepoint = false;
                        mInstancePath = null;
                        fd.initialize(true, new InstanceInitializationFactory());
                    } else {
                        // this means that the saved instance is corrupted.
                        throw e;
                    }
                }
            } else {
                fd.initialize(true, new InstanceInitializationFactory());
            }
        } else {
            fd.initialize(true, new InstanceInitializationFactory());
        }
    } catch (RuntimeException e) {
        Log.e(t, e.getMessage(), e);
        if (e.getCause() instanceof XPathTypeMismatchException) {
            // this is a case of https://bitbucket.org/m.sundt/javarosa/commits/e5d344783e7968877402bcee11828fa55fac69de
            // the data are imported, the survey will be unusable
            // but we should give the option to the user to edit the form
            // otherwise the survey will be TOTALLY inaccessible.
            Log.w(t, "We have a syntactically correct instance, but the data threw an exception inside JR. We should allow editing.");
        } else {
            mErrorMsg = e.getMessage();
            return null;
        }
    }

    // Remove previous forms
    ReferenceManager._().clearSession();

    // for itemsets.csv, we only check to see if the itemset file has been
    // updated
    File csv = new File(formMediaDir.getAbsolutePath() + "/" + ITEMSETS_CSV);
    String csvmd5 = null;
    if (csv.exists()) {
        csvmd5 = FileUtils.getMd5Hash(csv);
        boolean readFile = false;
        ItemsetDbAdapter ida = new ItemsetDbAdapter();
        ida.open();
        // get the database entry (if exists) for this itemsets.csv, based
        // on the path
        Cursor c = ida.getItemsets(csv.getAbsolutePath());
        if (c != null) {
            if (c.getCount() == 1) {
                c.moveToFirst(); // should be only one, ever, if any
                String oldmd5 = c.getString(c.getColumnIndex("hash"));
                if (oldmd5.equals(csvmd5)) {
                    // they're equal, do nothing
                } else {
                    // the csv has been updated, delete the old entries
                    ida.dropTable(oldmd5);
                    // and read the new
                    readFile = true;
                }
            } else {
                // new csv, add it
                readFile = true;
            }
            c.close();
        }
        ida.close();
        if (readFile) {
            readCSV(csv, csvmd5);
        }
    }

    // This should get moved to the Application Class
    if (ReferenceManager._().getFactories().length == 0) {
        // this is /sdcard/odk
        ReferenceManager._().addReferenceFactory(new FileReferenceFactory(Collect.ODK_ROOT));
    }

    // Set jr://... to point to /sdcard/odk/forms/filename-media/
    ReferenceManager._().addSessionRootTranslator(
            new RootTranslator("jr://images/", "jr://file/forms/" + formFileName + "-media/"));
    ReferenceManager._().addSessionRootTranslator(
            new RootTranslator("jr://image/", "jr://file/forms/" + formFileName + "-media/"));
    ReferenceManager._().addSessionRootTranslator(
            new RootTranslator("jr://audio/", "jr://file/forms/" + formFileName + "-media/"));
    ReferenceManager._().addSessionRootTranslator(
            new RootTranslator("jr://video/", "jr://file/forms/" + formFileName + "-media/"));

    // clean up vars
    fis = null;
    fd = null;
    formBin = null;
    formXml = null;
    formPath = null;

    FormController fc = new FormController(formMediaDir, fec,
            mInstancePath == null ? null : new File(mInstancePath));
    if (csvmd5 != null) {
        fc.setItemsetHash(csvmd5);
    }
    if (mXPath != null) {
        // we are resuming after having terminated -- set index to this position...
        FormIndex idx = fc.getIndexFromXPath(mXPath);
        fc.jumpToIndex(idx);
    }
    if (mWaitingXPath != null) {
        FormIndex idx = fc.getIndexFromXPath(mWaitingXPath);
        fc.setIndexWaitingForData(idx);
    }
    data = new FECWrapper(fc, usedSavepoint);
    return data;

}

From source file:net.smart_json_database.JSONDatabase.java

private ArrayList<JSONEntity> fetchByRawSQL(SQLiteDatabase db, String sql, String[] params, Order order) {

    ArrayList<JSONEntity> list = null;
    TreeMap<String, JSONEntity> map = null;
    if (order != null && order.sortDataField()) {
        map = new TreeMap<String, JSONEntity>();
    } else {/* w w  w. j av a 2  s.c  o m*/
        list = new ArrayList<JSONEntity>();
    }

    if (order != null && order.sortDatabaseField()) {
        sql += order.sql();
    }

    Cursor c = db.rawQuery(sql, params);
    if (c.getCount() > 0) {

        c.moveToFirst();
        do {
            try {
                JSONEntity entity = JSONEntity.loadFromCursor(c);
                getTagsForJSONEntity(entity, db);
                getHasManyRelationsForJSONEntity(entity, db);
                getBelongsToRelationsForJSONEntity(entity, db);
                if (list != null) {
                    list.add(entity);
                } else {
                    map.put(entity.getString(order.collation()), entity);
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                //e.printStackTrace();
            }
        } while (c.moveToNext());
    }
    c.close();
    if (map != null) {
        list = new ArrayList<JSONEntity>(map.values());
    }
    return list;
}