Example usage for android.database Cursor getLong

List of usage examples for android.database Cursor getLong

Introduction

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

Prototype

long getLong(int columnIndex);

Source Link

Document

Returns the value of the requested column as a long.

Usage

From source file:com.rs.TCOfflineStatementCollection.java

/**
 * return a list of all local statements from db
 * @return List of LocalStatementsItem//from  www .jav a2  s. c  om
 */
public List<LocalStatementsItem> getCachedStatements() {
    List<LocalStatementsItem> statementArray = new ArrayList<LocalStatementsItem>();

    Cursor cursor;
    SQLiteDatabase database;
    TCLocalStorageDatabaseOpenHelper dbHelper;
    dbHelper = new TCLocalStorageDatabaseOpenHelper(appContext);
    database = dbHelper.getWritableDatabase();
    cursor = database.query(TCOfflineDataManager.LOCAL_STATEMENT_TABLE_NAME, null, null, null, null, null,
            LocalStatements.CREATE_DATE + " DESC"); //query for all the statements

    cursor.moveToFirst(); //go to the beginning of the query and then loop through all the packages, adding them to the return List
    while (!cursor.isAfterLast()) {
        LocalStatementsItem thisPackage = new LocalStatementsItem();
        thisPackage.id = cursor.getInt(0);
        thisPackage.statementId = cursor.getString(cursor.getColumnIndex("statementId"));
        thisPackage.statementJson = cursor.getString(cursor.getColumnIndex("statementJson"));
        thisPackage.createDate = cursor.getLong(cursor.getColumnIndex("createDate"));
        thisPackage.postedDate = cursor.getLong(cursor.getColumnIndex("postedDate"));
        thisPackage.querystring = cursor.getString(cursor.getColumnIndex("querystring"));

        statementArray.add(thisPackage);
        cursor.moveToNext();
    }

    cursor.close();
    database.close();

    return statementArray;
}

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

/**
 * Test that query for the next card in the schedule returns a valid result without any deck selector
 */// w  w  w  .j  av a  2  s .c o  m
public void testQueryNextCard() {
    Collection col;
    col = CollectionHelper.getInstance().getCol(getContext());
    Sched sched = col.getSched();

    Cursor reviewInfoCursor = getContext().getContentResolver().query(FlashCardsContract.ReviewInfo.CONTENT_URI,
            null, null, null, null);
    assertNotNull(reviewInfoCursor);
    assertEquals("Check that we actually received one card", 1, reviewInfoCursor.getCount());

    reviewInfoCursor.moveToFirst();
    int cardOrd = reviewInfoCursor
            .getInt(reviewInfoCursor.getColumnIndex(FlashCardsContract.ReviewInfo.CARD_ORD));
    long noteID = reviewInfoCursor
            .getLong(reviewInfoCursor.getColumnIndex(FlashCardsContract.ReviewInfo.NOTE_ID));

    Card nextCard = null;
    for (int i = 0; i < 10; i++) {//minimizing fails, when sched.reset() randomly chooses between multiple cards
        sched.reset();
        nextCard = sched.getCard();
        if (nextCard.note().getId() == noteID && nextCard.getOrd() == cardOrd)
            break;
    }
    assertNotNull("Check that there actually is a next scheduled card", nextCard);
    assertEquals("Check that received card and actual card have same note id", nextCard.note().getId(), noteID);
    assertEquals("Check that received card and actual card have same card ord", nextCard.getOrd(), cardOrd);

}

From source file:com.hichinaschool.flashcards.libanki.importer.Anki2Importer.java

/** Cards */

private int _importCards() {
    // build map of (guid, ord) -> cid and used id cache
    mCards = new HashMap<String, HashMap<Integer, Long>>();
    HashMap<Long, Boolean> existing = new HashMap<Long, Boolean>();
    Cursor cursor = null;
    try {/*from w w  w.j  a v a 2 s  . c  o m*/
        // "SELECT f.guid, c.ord, c.id FROM cards c, notes f WHERE c.nid = f.id"
        cursor = mDst.getDb().getDatabase().query("cards c, notes f",
                new String[] { "f.guid", "c.ord", "c.id" }, "c.nid = f.id", null, null, null, null);
        while (cursor.moveToNext()) {
            long cid = cursor.getLong(2);
            existing.put(cid, true);
            String guid = cursor.getString(0);
            int ord = cursor.getInt(1);
            if (mCards.containsKey(guid)) {
                mCards.get(guid).put(ord, cid);
            } else {
                HashMap<Integer, Long> map = new HashMap<Integer, Long>();
                map.put(ord, cid);
                mCards.put(guid, map);
            }
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
    // loop through src
    ArrayList<Object[]> cards = new ArrayList<Object[]>();
    ArrayList<Object[]> revlog = new ArrayList<Object[]>();
    int cnt = 0;
    int usn = mDst.usn();
    long aheadBy = mSrc.getSched().getToday() - mDst.getSched().getToday();
    try {
        cursor = mSrc.getDb().getDatabase()
                .rawQuery("SELECT f.guid, f.mid, c.* FROM cards c, notes f WHERE c.nid = f.id", null);
        int total = cursor.getCount();
        int ci = 0;
        while (cursor.moveToNext()) {
            Object[] card = new Object[] { cursor.getString(0), cursor.getLong(1), cursor.getLong(2),
                    cursor.getLong(3), cursor.getLong(4), cursor.getInt(5), cursor.getLong(6), cursor.getInt(7),
                    cursor.getInt(8), cursor.getInt(9), cursor.getLong(10), cursor.getLong(11),
                    cursor.getLong(12), cursor.getInt(13), cursor.getInt(14), cursor.getInt(15),
                    cursor.getLong(16), cursor.getLong(17), cursor.getInt(18), cursor.getString(19) };
            String guid = (String) card[0];
            if (mChangedGuids.containsKey(guid)) {
                guid = mChangedGuids.get(guid);
            }
            // does the card's note exist in dst col?
            if (!mNotes.containsKey(guid)) {
                continue;
            }
            Object[] dnid = mNotes.get(guid);
            // does the card already exist in the dst col?
            int ord = (Integer) card[5];
            if (mCards.containsKey(guid) && mCards.get(guid).containsKey(ord)) {
                // fixme: in future, could update if newer mod time
                continue;
            }
            // doesn't exist. strip off note info, and save src id for later
            Object[] oc = card;
            card = new Object[oc.length - 2];
            for (int i = 0; i < card.length; i++) {
                card[i] = oc[i + 2];
            }
            long scid = (Long) card[0];
            // ensure the card id is unique
            while (existing.containsKey(card[0])) {
                card[0] = (Long) card[0] + 999;
            }
            existing.put((Long) card[0], true);
            // update cid, nid, etc
            card[1] = mNotes.get(guid)[0];
            card[2] = _did((Long) card[2]);
            card[4] = Utils.intNow();
            card[5] = usn;
            // review cards have a due date relative to collection
            if ((Integer) card[7] == 2 || (Integer) card[7] == 3 || (Integer) card[6] == 2) {
                card[8] = (Long) card[8] - aheadBy;
            }
            // if odid true, convert card from filtered to normal
            if ((Long) card[15] != 0) {
                // odid
                card[15] = 0;
                // odue
                card[8] = card[14];
                card[14] = 0;
                // queue
                if ((Integer) card[6] == 1) { // type
                    card[7] = 0;
                } else {
                    card[7] = card[6];
                }
                // type
                if ((Integer) card[6] == 1) {
                    card[6] = 0;
                }
            }
            cards.add(card);
            // we need to import revlog, rewriting card ids and bumping usn
            Cursor cur2 = null;
            try {
                //                    "SELECT * FROM revlog WHERE cid = ?"
                cur2 = mDst.getDb().getDatabase().query("revlog",
                        new String[] { "id", "cid", "usn", "ease", "ivl", "lastIvl", "factor", "time", "type" },
                        "cid = ?", new String[] { Long.toString(scid) }, null, null, null);
                while (cur2.moveToNext()) {
                    Object[] rev = new Object[] { cur2.getLong(0), cur2.getLong(1), cur2.getInt(2),
                            cur2.getInt(3), cur2.getLong(4), cur2.getLong(5), cur2.getLong(6), cur2.getLong(7),
                            cur2.getInt(8) };
                    rev[1] = card[0];
                    rev[2] = mDst.usn();
                    revlog.add(rev);
                }
            } finally {
                if (cur2 != null) {
                    cur2.close();
                }
            }
            cnt += 1;
            ++ci;
            publishProgress(true, 100, ci * 100 / total, false);
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
    // apply
    mDst.getDb().executeMany("INSERT OR IGNORE INTO cards VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", cards);
    mDst.getDb().executeMany("INSERT OR IGNORE INTO revlog VALUES (?,?,?,?,?,?,?,?,?)", revlog);
    return cnt;
}

From source file:com.nit.libanki.importer.Anki2Importer.java

/** Cards */

private int _importCards(boolean currDeckImport) {
    // build map of (guid, ord) -> cid and used id cache
    mCards = new HashMap<String, HashMap<Integer, Long>>();
    HashMap<Long, Boolean> existing = new HashMap<Long, Boolean>();
    Cursor cursor = null;
    try {/*from   w w w. ja va 2 s . c o m*/
        // "SELECT f.guid, c.ord, c.id FROM cards c, notes f WHERE c.nid = f.id"
        cursor = mDst.getDb().getDatabase().query("cards c, notes f",
                new String[] { "f.guid", "c.ord", "c.id" }, "c.nid = f.id", null, null, null, null);
        while (cursor.moveToNext()) {
            long cid = cursor.getLong(2);
            existing.put(cid, true);
            String guid = cursor.getString(0);
            int ord = cursor.getInt(1);
            if (mCards.containsKey(guid)) {
                mCards.get(guid).put(ord, cid);
            } else {
                HashMap<Integer, Long> map = new HashMap<Integer, Long>();
                map.put(ord, cid);
                mCards.put(guid, map);
            }
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
    // loop through src
    ArrayList<Object[]> cards = new ArrayList<Object[]>();
    ArrayList<Object[]> revlog = new ArrayList<Object[]>();
    int cnt = 0;
    int usn = mDst.usn();
    long aheadBy = mSrc.getSched().getToday() - mDst.getSched().getToday();
    try {
        cursor = mSrc.getDb().getDatabase()
                .rawQuery("SELECT f.guid, f.mid, c.* FROM cards c, notes f WHERE c.nid = f.id", null);
        int total = cursor.getCount();
        int ci = 0;
        while (cursor.moveToNext()) {
            Object[] card = new Object[] { cursor.getString(0), cursor.getLong(1), cursor.getLong(2),
                    cursor.getLong(3), cursor.getLong(4), cursor.getInt(5), cursor.getLong(6), cursor.getInt(7),
                    cursor.getInt(8), cursor.getInt(9), cursor.getLong(10), cursor.getLong(11),
                    cursor.getLong(12), cursor.getInt(13), cursor.getInt(14), cursor.getInt(15),
                    cursor.getLong(16), cursor.getLong(17), cursor.getInt(18), cursor.getString(19) };
            String guid = (String) card[0];
            if (mChangedGuids.containsKey(guid)) {
                guid = mChangedGuids.get(guid);
            }
            // does the card's note exist in dst col?
            if (!mNotes.containsKey(guid)) {
                continue;
            }
            Object[] dnid = mNotes.get(guid);
            // does the card already exist in the dst col?
            int ord = (Integer) card[5];
            if (mCards.containsKey(guid) && mCards.get(guid).containsKey(ord)) {
                // fixme: in future, could update if newer mod time
                continue;
            }
            // doesn't exist. strip off note info, and save src id for later
            Object[] oc = card;
            card = new Object[oc.length - 2];
            for (int i = 0; i < card.length; i++) {
                card[i] = oc[i + 2];
            }
            long scid = (Long) card[0];
            // ensure the card id is unique
            while (existing.containsKey(card[0])) {
                card[0] = (Long) card[0] + 999;
            }
            existing.put((Long) card[0], true);
            // update cid, nid, etc
            card[1] = mNotes.get(guid)[0];
            card[2] = _did((Long) card[2], currDeckImport);
            card[4] = Utils.intNow();
            card[5] = usn;
            // review cards have a due date relative to collection
            if ((Integer) card[7] == 2 || (Integer) card[7] == 3 || (Integer) card[6] == 2) {
                card[8] = (Long) card[8] - aheadBy;
            }
            // if odid true, convert card from filtered to normal
            //if ((Long)card[15] != 0) {
            // odid
            card[15] = 0;
            // odue
            card[8] = 0; //card[14];
            card[14] = 0;
            // queue
            //if ((Integer)card[6] == 1) { // type
            card[7] = 0;
            //} else {
            //   card[7] = card[6];
            //}
            // type
            //if ((Integer)card[6] == 1) {
            card[6] = 0;
            //}
            //}
            cards.add(card);
            // we need to import revlog, rewriting card ids and bumping usn
            Cursor cur2 = null;
            try {
                //                    "SELECT * FROM revlog WHERE cid = ?"
                cur2 = mDst.getDb().getDatabase().query("revlog",
                        new String[] { "id", "cid", "usn", "ease", "ivl", "lastIvl", "factor", "time", "type" },
                        "cid = ?", new String[] { Long.toString(scid) }, null, null, null);
                while (cur2.moveToNext()) {
                    Object[] rev = new Object[] { cur2.getLong(0), cur2.getLong(1), cur2.getInt(2),
                            cur2.getInt(3), cur2.getLong(4), cur2.getLong(5), cur2.getLong(6), cur2.getLong(7),
                            cur2.getInt(8) };
                    rev[1] = card[0];
                    rev[2] = mDst.usn();
                    revlog.add(rev);
                }
            } finally {
                if (cur2 != null) {
                    cur2.close();
                }
            }
            cnt += 1;
            ++ci;
            publishProgress(true, 100, ci * 100 / total, false);
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
    // apply
    mDst.getDb().executeMany("INSERT OR IGNORE INTO cards VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", cards);
    mDst.getDb().executeMany("INSERT OR IGNORE INTO revlog VALUES (?,?,?,?,?,?,?,?,?)", revlog);
    return cnt;
}

From source file:com.flowzr.budget.holo.export.flowzr.FlowzrSyncEngine.java

public static Object saveOrUpdateCurrencyFromJSON(long id, JSONObject jsonObjectEntity) {
    Currency tEntity = em.get(Currency.class, id);
    if (tEntity == null) {
        tEntity = Currency.EMPTY;
        tEntity.id = KEY_CREATE;//from w  w  w .ja  v a2 s.c  o m
    }
    try {
        tEntity.remoteKey = jsonObjectEntity.getString("key");
        if (jsonObjectEntity.has("title")) {
            tEntity.title = jsonObjectEntity.getString("title");
        }
        if (jsonObjectEntity.has("name")) {
            tEntity.name = jsonObjectEntity.getString("name");
        }
        //deduplicate if server already have the currency
        String sql = "select _id from " + DatabaseHelper.CURRENCY_TABLE + " where name= '" + tEntity.name
                + "';";
        Cursor c = db.rawQuery(sql, null);

        if (c.moveToFirst()) {
            tEntity.id = c.getLong(0);
            c.close();
        } else {
            c.close();
        }
        if (jsonObjectEntity.has("symbol")) {
            try {
                tEntity.symbol = jsonObjectEntity.getString("symbol");
            } catch (Exception e) {
                Log.e(TAG, "Error pulling Currency.symbol");
                e.printStackTrace();
            }
        }
        tEntity.isDefault = false;
        if (jsonObjectEntity.has("isDefault")) {
            if (jsonObjectEntity.getBoolean("isDefault")) {
                tEntity.isDefault = jsonObjectEntity.getBoolean("isDefault");
            }
        }
        if (jsonObjectEntity.has("decimals")) {
            try {
                tEntity.decimals = jsonObjectEntity.getInt("decimals");
            } catch (Exception e) {
                Log.e(TAG, "Error pulling Currency.decimals");
                e.printStackTrace();
            }
        }
        try {
            tEntity.decimalSeparator = jsonObjectEntity.getString("decimalSeparator");
        } catch (Exception e) {
            Log.e(TAG, "Error pulling Currency.symbol");
        }
        try {
            tEntity.groupSeparator = jsonObjectEntity.getString("groupSeparator");
        } catch (Exception e) {
            Log.e(TAG, "Error pulling Currency.symbol");
        }
        em.saveOrUpdate(tEntity);
        return tEntity;
    } catch (Exception e) {
        e.printStackTrace();
        return e;
    }
}

From source file:gov.nasa.arc.geocam.geocam.GeoCamService.java

void postProcessLocation(Uri uri) {
    final String[] projection = new String[] { MediaStore.Images.ImageColumns._ID,
            MediaStore.Images.ImageColumns.DATE_TAKEN, MediaStore.Images.ImageColumns.LATITUDE,
            MediaStore.Images.ImageColumns.LONGITUDE, MediaStore.Images.ImageColumns.DESCRIPTION,
            MediaStore.Images.ImageColumns.SIZE, };

    try {/*from  w  w w  .java2s .  c  om*/
        Cursor cur = getContentResolver().query(uri, projection, null, null, null);
        cur.moveToFirst();

        long dateTakenMillis = cur.getLong(cur.getColumnIndex(MediaStore.Images.ImageColumns.DATE_TAKEN));
        String imageData = cur.getString(cur.getColumnIndex(MediaStore.Images.ImageColumns.DESCRIPTION));
        cur.close();

        List<Location> points = mGpsLog.getBoundingLocations(dateTakenMillis, 1);
        if (points.size() == 2) {
            Location before = points.get(0);
            Location after = points.get(1);
            double lat, lon, alt;

            long beforeDiff = dateTakenMillis - before.getTime();
            long afterDiff = after.getTime() - dateTakenMillis;
            long diff = beforeDiff + afterDiff;

            if (diff < GeoCamMobile.PHOTO_BRACKET_INTERVAL_MSECS) {
                // best case -- not too much time lag between bracketing positions. interpolate.
                double a = ((double) beforeDiff) / diff;
                lat = before.getLatitude() + a * (after.getLatitude() - before.getLatitude());
                lon = before.getLongitude() + a * (after.getLongitude() - before.getLongitude());
                alt = before.getAltitude() + a * (after.getAltitude() - before.getLongitude());
            } else if (beforeDiff < GeoCamMobile.PHOTO_BRACKET_THRESHOLD_MSECS
                    || afterDiff < GeoCamMobile.PHOTO_BRACKET_THRESHOLD_MSECS) {
                // one of the two points is close enough in time to the photo capture time. use its position.
                if (beforeDiff < afterDiff) {
                    lat = before.getLatitude();
                    lon = before.getLongitude();
                    alt = before.getAltitude();
                } else {
                    lat = after.getLatitude();
                    lon = after.getLongitude();
                    alt = after.getAltitude();
                }
            } else {
                // otherwise, we don't have any usable position data
                lat = 0.0;
                lon = 0.0;
                alt = 0.0;
            }

            // Fix the geomagnetic declination if we have all of our info
            if (!(lat == 0.0 && lon == 0.0 && alt == 0.0)) {
                GeomagneticField field = new GeomagneticField((float) lat, (float) lon, (float) alt,
                        dateTakenMillis);
                float declination = field.getDeclination();

                try {
                    JSONObject dataObj = new JSONObject(imageData);

                    double[] angles = GeoCamMobile.rpyUnSerialize(dataObj.getString("rpy"));
                    angles[2] += declination;
                    Log.d(GeoCamMobile.DEBUG_ID,
                            "Fixed heading. Declination: " + declination + " New heading: " + angles[2]);

                    dataObj.put("rpy", GeoCamMobile.rpySerialize(angles[0], angles[1], angles[2]));
                    dataObj.put("yawRef", GeoCamMobile.YAW_TRUE);

                    imageData = dataObj.toString();
                } catch (JSONException e) {
                    Log.e(GeoCamMobile.DEBUG_ID, "Error decoding/encoding for geomagnetic stuff" + e);
                }
            }

            ContentValues values = new ContentValues(2);
            values.put(MediaStore.Images.ImageColumns.LATITUDE, lat);
            values.put(MediaStore.Images.ImageColumns.LONGITUDE, lon);
            values.put(MediaStore.Images.ImageColumns.DESCRIPTION, imageData);
            getContentResolver().update(uri, values, null, null);
        }
    } catch (CursorIndexOutOfBoundsException e) {

    }
}

From source file:com.hichinaschool.flashcards.libanki.sync.Syncer.java

private ArrayList<Object[]> newerRows(JSONArray data, String table, int modIdx) {
    long[] ids = new long[data.length()];
    try {// ww w .  j av  a  2 s .com
        for (int i = 0; i < data.length(); i++) {
            ids[i] = data.getJSONArray(i).getLong(0);
        }
        HashMap<Long, Long> lmods = new HashMap<Long, Long>();
        Cursor cur = null;
        try {
            cur = mCol.getDb().getDatabase().rawQuery(
                    "SELECT id, mod FROM " + table + " WHERE id IN " + Utils.ids2str(ids) + " AND " + usnLim(),
                    null);
            while (cur.moveToNext()) {
                lmods.put(cur.getLong(0), cur.getLong(1));
            }
        } finally {
            if (cur != null && !cur.isClosed()) {
                cur.close();
            }
        }
        ArrayList<Object[]> update = new ArrayList<Object[]>();
        for (int i = 0; i < data.length(); i++) {
            JSONArray r = data.getJSONArray(i);
            if (!lmods.containsKey(r.getLong(0)) || lmods.get(r.getLong(0)) < r.getLong(modIdx)) {
                update.add(ConvUtils.jsonArray2Objects(r));
            }
        }
        return update;
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.ichi2.libanki.Media.java

private List<List<String>> check(File[] local) {
    File mdir = new File(dir());
    // gather all media references in NFC form
    Set<String> allRefs = new HashSet<String>();
    Cursor cur = null;
    try {/*w w  w .  j  a  va 2s.c om*/
        cur = mCol.getDb().getDatabase().rawQuery("select id, mid, flds from notes", null);
        while (cur.moveToNext()) {
            long nid = cur.getLong(0);
            long mid = cur.getLong(1);
            String flds = cur.getString(2);
            List<String> noteRefs = filesInStr(mid, flds);
            // check the refs are in NFC
            for (String f : noteRefs) {
                // if they're not, we'll need to fix them first
                if (!f.equals(HtmlUtil.nfcNormalized(f))) {
                    _normalizeNoteRefs(nid);
                    noteRefs = filesInStr(mid, flds);
                    break;
                }
            }
            allRefs.addAll(noteRefs);
        }
    } finally {
        if (cur != null) {
            cur.close();
        }
    }
    // loop through media folder
    List<String> unused = new ArrayList<String>();
    List<String> invalid = new ArrayList<String>();
    File[] files;
    if (local == null) {
        files = mdir.listFiles();
    } else {
        files = local;
    }
    boolean renamedFiles = false;
    for (File file : files) {
        if (local == null) {
            if (file.isDirectory()) {
                // ignore directories
                continue;
            }
        }
        if (file.getName().startsWith("_")) {
            // leading _ says to ignore file
            continue;
        }
        File nfcFile = new File(dir(), HtmlUtil.nfcNormalized(file.getName()));
        // we enforce NFC fs encoding
        if (local == null) {
            if (!file.getName().equals(nfcFile.getName())) {
                // delete if we already have the NFC form, otherwise rename
                if (nfcFile.exists()) {
                    file.delete();
                    renamedFiles = true;
                } else {
                    file.renameTo(nfcFile);
                    renamedFiles = true;
                }
                file = nfcFile;
            }
        }
        // compare
        if (!allRefs.contains(nfcFile.getName())) {
            unused.add(file.getName());
        } else {
            allRefs.remove(nfcFile.getName());
        }
    }
    // if we renamed any files to nfc format, we must rerun the check
    // to make sure the renamed files are not marked as unused
    if (renamedFiles) {
        return check(local);
    }
    List<String> nohave = new ArrayList<String>();
    for (String x : allRefs) {
        if (!x.startsWith("_")) {
            nohave.add(x);
        }
    }
    List<List<String>> result = new ArrayList<List<String>>();
    result.add(nohave);
    result.add(unused);
    result.add(invalid);
    return result;
}

From source file:edu.stanford.mobisocial.dungbeetle.DungBeetleContentProvider.java

/**
 * Inserts a message locally that has been received from some agent,
 * typically from a remote device./*from   w  w  w .  j a v  a 2  s . c  o  m*/
 */
@Override
public Uri insert(Uri uri, ContentValues values) {
    ContentResolver resolver = getContext().getContentResolver();
    if (DBG)
        Log.i(TAG, "Inserting at uri: " + uri + ", " + values);

    final String appId = getCallingActivityId();
    if (appId == null) {
        Log.d(TAG, "No AppId for calling activity. Ignoring query.");
        return null;
    }

    List<String> segs = uri.getPathSegments();
    if (match(uri, "feeds", "me")) {
        if (!appId.equals(SUPER_APP_ID)) {
            return null;
        }

        long objId = mHelper.addToFeed(appId, "friend", values);
        Uri objUri = DbObject.uriForObj(objId);
        resolver.notifyChange(Feed.uriForName("me"), null);
        resolver.notifyChange(Feed.uriForName("friend"), null);
        resolver.notifyChange(objUri, null);
        return objUri;
    } else if (match(uri, "feeds", ".+")) {
        String feedName = segs.get(1);
        String type = values.getAsString(DbObject.TYPE);
        try {
            JSONObject json = new JSONObject(values.getAsString(DbObject.JSON));
            String objHash = null;
            if (feedName.contains(":")) {
                String[] parts = feedName.split(":");
                feedName = parts[0];
                objHash = parts[1];
            }
            if (objHash != null) {
                json.put(DbObjects.TARGET_HASH, Long.parseLong(objHash));
                json.put(DbObjects.TARGET_RELATION, DbRelation.RELATION_PARENT);
                values.put(DbObject.JSON, json.toString());
            }

            String appAuthority = appId;
            if (SUPER_APP_ID.equals(appId)) {
                if (AppObj.TYPE.equals(type)) {
                    if (json.has(AppObj.ANDROID_PACKAGE_NAME)) {
                        appAuthority = json.getString(AppObj.ANDROID_PACKAGE_NAME);
                    }
                }
            }

            long objId = mHelper.addToFeed(appAuthority, feedName, values);
            Uri objUri = DbObject.uriForObj(objId);
            resolver.notifyChange(objUri, null);
            notifyDependencies(mHelper, resolver, segs.get(1));
            if (DBG)
                Log.d(TAG, "just inserted " + values.getAsString(DbObject.JSON));
            return objUri;
        } catch (JSONException e) {
            return null;
        }
    } else if (match(uri, "out")) {
        try {
            JSONObject obj = new JSONObject(values.getAsString("json"));
            long objId = mHelper.addToOutgoing(appId, values.getAsString(DbObject.DESTINATION),
                    values.getAsString(DbObject.TYPE), obj);
            resolver.notifyChange(Uri.parse(CONTENT_URI + "/out"), null);
            return DbObject.uriForObj(objId);
        } catch (JSONException e) {
            return null;
        }
    } else if (match(uri, "contacts")) {
        if (!appId.equals(SUPER_APP_ID)) {
            return null;
        }
        long id = mHelper.insertContact(values);
        resolver.notifyChange(Uri.parse(CONTENT_URI + "/contacts"), null);
        return uriWithId(uri, id);
    } else if (match(uri, "subscribers")) {
        // Question: Should this be restricted?
        // if(!appId.equals(SUPER_APP_ID)) return null;
        long id = mHelper.insertSubscriber(values);
        resolver.notifyChange(Uri.parse(CONTENT_URI + "/subscribers"), null);
        return uriWithId(uri, id);
    } else if (match(uri, "groups")) {
        if (!appId.equals(SUPER_APP_ID))
            return null;
        long id = mHelper.insertGroup(values);
        getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/groups"), null);
        return uriWithId(uri, id);
    } else if (match(uri, "group_members")) {
        if (!appId.equals(SUPER_APP_ID)) {
            return null;
        }
        long id = mHelper.insertGroupMember(values);
        getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/group_members"), null);
        getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/group_contacts"), null);
        return uriWithId(uri, id);
    }

    else if (match(uri, "group_invitations")) {
        if (!appId.equals(SUPER_APP_ID)) {
            return null;
        }
        String groupName = values.getAsString(InviteToGroupObj.GROUP_NAME);
        Uri dynUpdateUri = Uri.parse(values.getAsString(InviteToGroupObj.DYN_UPDATE_URI));
        long gid = values.getAsLong("groupId");
        SQLiteDatabase db = mHelper.getWritableDatabase();
        mHelper.addToOutgoing(db, appId, values.getAsString(InviteToGroupObj.PARTICIPANTS),
                InviteToGroupObj.TYPE, InviteToGroupObj.json(groupName, dynUpdateUri));
        getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/out"), null);
        return uriWithId(uri, gid);
    }

    else if (match(uri, "dynamic_groups")) {
        if (!appId.equals(SUPER_APP_ID)) {
            return null;
        }
        Uri gUri = Uri.parse(values.getAsString("uri"));
        GroupProviders.GroupProvider gp = GroupProviders.forUri(gUri);
        String feedName = gp.feedName(gUri);
        Maybe<Group> mg = mHelper.groupByFeedName(feedName);
        long id = -1;
        try {
            Group g = mg.get();
            id = g.id;
        } catch (Maybe.NoValError e) {
            ContentValues cv = new ContentValues();
            cv.put(Group.NAME, gp.groupName(gUri));
            cv.put(Group.FEED_NAME, feedName);
            cv.put(Group.DYN_UPDATE_URI, gUri.toString());

            String table = DbObject.TABLE;
            String[] columns = new String[] { DbObject.FEED_NAME };
            String selection = DbObject.CHILD_FEED_NAME + " = ?";
            String[] selectionArgs = new String[] { feedName };
            Cursor parent = mHelper.getReadableDatabase().query(table, columns, selection, selectionArgs, null,
                    null, null);
            try {
                if (parent.moveToFirst()) {
                    String parentName = parent.getString(0);
                    table = Group.TABLE;
                    columns = new String[] { Group._ID };
                    selection = Group.FEED_NAME + " = ?";
                    selectionArgs = new String[] { parentName };

                    Cursor parent2 = mHelper.getReadableDatabase().query(table, columns, selection,
                            selectionArgs, null, null, null);
                    try {
                        if (parent2.moveToFirst()) {
                            cv.put(Group.PARENT_FEED_ID, parent2.getLong(0));
                        } else {
                            Log.e(TAG, "Parent feed found but no id for " + parentName);
                        }
                    } finally {
                        parent2.close();
                    }
                } else {
                    Log.w(TAG, "No parent feed for " + feedName);
                }
            } finally {
                parent.close();
            }
            id = mHelper.insertGroup(cv);
            getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/dynamic_groups"), null);
            getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/groups"), null);
        }
        return uriWithId(uri, id);
    }

    else if (match(uri, "dynamic_group_member")) {
        if (!appId.equals(SUPER_APP_ID)) {
            return null;
        }
        SQLiteDatabase db = mHelper.getWritableDatabase();
        db.beginTransaction();
        try {
            ContentValues cv = new ContentValues();
            String pubKeyStr = values.getAsString(Contact.PUBLIC_KEY);
            RSAPublicKey k = RSACrypto.publicKeyFromString(pubKeyStr);
            String personId = mIdent.personIdForPublicKey(k);
            if (!personId.equals(mIdent.userPersonId())) {
                cv.put(Contact.PUBLIC_KEY, values.getAsString(Contact.PUBLIC_KEY));
                cv.put(Contact.NAME, values.getAsString(Contact.NAME));
                cv.put(Contact.EMAIL, values.getAsString(Contact.EMAIL));
                if (values.getAsString(Contact.PICTURE) != null) {
                    cv.put(Contact.PICTURE, values.getAsByteArray(Contact.PICTURE));
                }

                long cid = -1;
                Contact contact = mHelper.contactForPersonId(personId).otherwise(Contact.NA());
                if (contact.id > -1) {
                    cid = contact.id;
                } else {
                    cid = mHelper.insertContact(db, cv);
                }

                if (cid > -1) {

                    ContentValues gv = new ContentValues();
                    gv.put(GroupMember.GLOBAL_CONTACT_ID, values.getAsString(GroupMember.GLOBAL_CONTACT_ID));
                    gv.put(GroupMember.GROUP_ID, values.getAsLong(GroupMember.GROUP_ID));
                    gv.put(GroupMember.CONTACT_ID, cid);
                    mHelper.insertGroupMember(db, gv);
                    getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/group_members"),
                            null);
                    getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/contacts"), null);
                    getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/group_contacts"),
                            null);

                    // Add subscription to this private group feed
                    ContentValues sv = new ContentValues();
                    sv = new ContentValues();
                    sv.put(Subscriber.CONTACT_ID, cid);
                    sv.put(Subscriber.FEED_NAME, values.getAsString(Group.FEED_NAME));
                    mHelper.insertSubscriber(db, sv);

                    ContentValues xv = new ContentValues();
                    xv.put(Subscriber.CONTACT_ID, cid);
                    xv.put(Subscriber.FEED_NAME, "friend");
                    mHelper.insertSubscriber(db, xv);

                    getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/subscribers"),
                            null);

                    db.setTransactionSuccessful();
                }
                return uriWithId(uri, cid);
            } else {
                Log.i(TAG, "Omitting self.");
                return uriWithId(uri, Contact.MY_ID);
            }
        } finally {
            db.endTransaction();
        }
    } else {
        Log.e(TAG, "Failed to insert into " + uri);
        return null;
    }
}

From source file:net.kourlas.voipms_sms.Database.java

/**
 * Gets the message with the specified VoIP.ms ID from the database.
 *
 * @return The message with the specified VoIP.ms ID.
 *//* w  ww . j a  v a2 s  .c om*/
public synchronized Message getMessageWithVoipId(String did, long voipId) {
    Cursor cursor = database.query(TABLE_MESSAGE, columns,
            COLUMN_DID + "=" + did + " AND " + COLUMN_VOIP_ID + " = " + voipId, null, null, null, null);
    if (cursor.moveToFirst()) {
        Message message = new Message(cursor.getLong(cursor.getColumnIndexOrThrow(COLUMN_DATABASE_ID)),
                cursor.isNull(cursor.getColumnIndexOrThrow(COLUMN_VOIP_ID)) ? null
                        : cursor.getLong(cursor.getColumnIndex(COLUMN_VOIP_ID)),
                cursor.getLong(cursor.getColumnIndexOrThrow(COLUMN_DATE)),
                cursor.getLong(cursor.getColumnIndexOrThrow(COLUMN_TYPE)),
                cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_DID)),
                cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_CONTACT)),
                cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_MESSAGE)),
                cursor.getLong(cursor.getColumnIndexOrThrow(COLUMN_UNREAD)),
                cursor.getLong(cursor.getColumnIndexOrThrow(COLUMN_DELETED)),
                cursor.getLong(cursor.getColumnIndexOrThrow(COLUMN_DELIVERED)),
                cursor.getLong(cursor.getColumnIndexOrThrow(COLUMN_DELIVERY_IN_PROGRESS)));
        cursor.close();
        return message;
    } else {
        cursor.close();
        return null;
    }
}