List of usage examples for android.database Cursor getLong
long getLong(int columnIndex);
From source file:com.ichi2.libanki.sync.Syncer.java
private ArrayList<Object[]> newerRows(JSONArray data, String table, int modIdx) { long[] ids = new long[data.length()]; try {/*from ww w .ja v a 2 s. c o m*/ 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)); } } mCol.log(table, data); return update; } catch (JSONException e) { throw new RuntimeException(e); } }
From source file:com.ichi2.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 . jav a2s . 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]; System.arraycopy(oc, 2, card, 0, card.length); 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:net.kourlas.voipms_sms.Database.java
/** * Gets the message with the specified database ID from the database. * * @return The message with the specified database ID. */// w w w . ja v a 2 s . c om public synchronized Message getMessageWithDatabaseId(String did, long databaseId) { Cursor cursor = database.query(TABLE_MESSAGE, columns, COLUMN_DID + "=" + did + " AND " + COLUMN_DATABASE_ID + " = " + databaseId, 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; } }
From source file:eu.codeplumbers.cosi.services.CosiCallService.java
/** * Read phone call log and update app database *///from w w w . j a va 2 s. c o m private void readCallLog() { //Fetches the complete call log in descending order. i.e recent calls appears first. if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_CALL_LOG) == PackageManager.PERMISSION_GRANTED) { Cursor c = getContentResolver().query(CallLog.Calls.CONTENT_URI, null, null, null, CallLog.Calls.DATE + " DESC"); int totalCalls = c.getCount(); EventBus.getDefault() .post(new CallSyncEvent(SYNC_MESSAGE, "Reading phone log: " + c.getCount() + " calls...")); if (c.moveToFirst()) { for (int i = 0; i < totalCalls; i++) { EventBus.getDefault() .post(new CallSyncEvent(SYNC_MESSAGE, "Local call " + i + "/" + totalCalls + "...")); String callerID = c.getString(c.getColumnIndex(CallLog.Calls._ID)); String callerNumber = c.getString(c.getColumnIndex(CallLog.Calls.NUMBER)); long callDateandTime = c.getLong(c.getColumnIndex(CallLog.Calls.DATE)); long callDuration = c.getLong(c.getColumnIndex(CallLog.Calls.DURATION)); int callType = c.getInt(c.getColumnIndex(CallLog.Calls.TYPE)); Call call = Call.getByIdNumberDate(callerID, callerNumber, callDateandTime); if (call == null) { call = new Call(); } call.setRemoteId( (call.getRemoteId() != "" && call.getRemoteId() != null) ? call.getRemoteId() : ""); call.setCallerId(callerID); call.setCallerNumber(callerNumber); call.setDateAndTime(DateUtils.formatDate(callDateandTime)); call.setType(callType); call.setDuration(callDuration); boolean hasDevice = call.getDeviceId() != "" && call.getDeviceId() != null; call.setDeviceId(hasDevice ? call.getDeviceId() : Device.registeredDevice().getLogin()); call.save(); allCalls.add(call); c.moveToNext(); } } c.close(); } else { EventBus.getDefault() .post(new CallSyncEvent(SERVICE_ERROR, getString(R.string.permission_denied_call_log))); } }
From source file:pt.up.mobile.syncadapter.SigarraSyncAdapter.java
private void syncNotifications(Account account, SyncResult syncResult) throws AuthenticationException, IOException { final User user = AccountUtils.getUser(getContext(), account.name); final String notificationReply = SifeupAPI.getReply(SifeupAPI.getNotificationsUrl(user.getUserCode()), account, getContext());//from w ww. j ava 2s . co m final Gson gson = GsonUtils.getGson(); final Notification[] notifications = gson.fromJson(notificationReply, Notification[].class); if (notifications == null) { syncResult.stats.numParseExceptions++; LogUtils.trackException(getContext(), new RuntimeException(), notificationReply, true); return; } ArrayList<String> fetchedNotCodes = new ArrayList<String>(); ArrayList<ContentValues> bulkValues = new ArrayList<ContentValues>(); for (Notification not : notifications) { final ContentValues values = new ContentValues(); values.put(SigarraContract.Notifcations.CONTENT, gson.toJson(not)); fetchedNotCodes.add(not.getCode()); if (getContext().getContentResolver().update(SigarraContract.Notifcations.CONTENT_URI, values, SigarraContract.Notifcations.UPDATE_NOTIFICATION, SigarraContract.Notifcations.getNotificationsSelectionArgs(account.name, not.getCode())) == 0) { values.put(SigarraContract.Notifcations.CODE, account.name); values.put(SigarraContract.Notifcations.ID_NOTIFICATION, not.getCode()); values.put(SigarraContract.Notifcations.STATE, SigarraContract.Notifcations.NEW); values.put(SigarraContract.Notifcations.CODE, account.name); bulkValues.add(values); } } // inserting the values if (bulkValues.size() > 0) { getContext().getContentResolver().bulkInsert(SigarraContract.Notifcations.CONTENT_URI, bulkValues.toArray(new ContentValues[0])); // if the account being synced is the current active accout // display notification if (AccountUtils.getActiveUserName(getContext()).equals(account.name)) { final NotificationManager mNotificationManager = (NotificationManager) getContext() .getSystemService(Context.NOTIFICATION_SERVICE); NotificationCompat.Builder notBuilder = new NotificationCompat.Builder(getContext()); notBuilder.setAutoCancel(true).setOnlyAlertOnce(true) .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)); if (bulkValues.size() == 1) { final Notification notification = gson.fromJson( bulkValues.get(0).getAsString(SigarraContract.Notifcations.CONTENT), Notification.class); Intent notifyIntent = new Intent(getContext(), NotificationsDescActivity.class) .putExtra(NotificationsDescFragment.NOTIFICATION, notification); // Creates the PendingIntent PendingIntent notifyPendingIntent = PendingIntent.getActivity(getContext(), 0, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT); // Sets the Activity to start in a new, empty task notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); notBuilder.setSmallIcon(R.drawable.icon).setTicker(notification.getMessage()) .setContentTitle(notification.getSubject()).setContentText(notification.getMessage()) .setContentIntent(notifyPendingIntent) .setStyle(new NotificationCompat.BigTextStyle().bigText(notification.getMessage()) .setBigContentTitle(notification.getSubject()) .setSummaryText(notification.getMessage())); mNotificationManager.notify(notification.getCode().hashCode(), notBuilder.build()); } else { final String notTitle = getContext().getString(R.string.new_notifications, bulkValues.size()); Intent notifyIntent = new Intent(getContext(), NotificationsActivity.class); // Sets the Activity to start in a new, empty task notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); // Creates the PendingIntent PendingIntent notifyPendingIntent = PendingIntent.getActivity(getContext(), 0, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT); NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(); // Sets a title for the Inbox style big view inboxStyle.setBigContentTitle(notTitle); // Moves events into the big view for (ContentValues value : bulkValues) { final Notification notification = gson.fromJson( value.getAsString(SigarraContract.Notifcations.CONTENT), Notification.class); inboxStyle.addLine(notification.getSubject()); } // Moves the big view style object into the notification // object. notBuilder.setStyle(inboxStyle); notBuilder.setSmallIcon(R.drawable.icon).setTicker(notTitle).setContentTitle(notTitle) .setContentText("").setContentIntent(notifyPendingIntent); mNotificationManager.notify(NotificationsFragment.class.getName().hashCode(), notBuilder.build()); } } } final Cursor syncState = getContext().getContentResolver().query(SigarraContract.LastSync.CONTENT_URI, SigarraContract.LastSync.COLUMNS, SigarraContract.LastSync.PROFILE, SigarraContract.LastSync.getLastSyncSelectionArgs(AccountUtils.getActiveUserName(getContext())), null); try { if (syncState.moveToFirst()) { if (syncState.getLong(syncState.getColumnIndex(SigarraContract.LastSync.NOTIFICATIONS)) == 0) { // Report that we have checked the notifications final ContentValues values = new ContentValues(); values.put(SigarraContract.LastSync.NOTIFICATIONS, System.currentTimeMillis()); getContext().getContentResolver().update(SigarraContract.LastSync.CONTENT_URI, values, SigarraContract.LastSync.PROFILE, SigarraContract.LastSync.getLastSyncSelectionArgs(account.name)); } } } finally { syncState.close(); } ArrayList<String> notToDelete = new ArrayList<String>(); final Cursor cursor = getContext().getContentResolver().query(SigarraContract.Notifcations.CONTENT_URI, new String[] { SigarraContract.Notifcations.ID_NOTIFICATION }, SigarraContract.Notifcations.PROFILE, SigarraContract.Notifcations.getNotificationsSelectionArgs(account.name), null); try { if (cursor.moveToFirst()) { do { final String code = cursor.getString(0); if (!fetchedNotCodes.contains(code)) notToDelete.add(code); } while (cursor.moveToNext()); } else { // no notifications getContext().getContentResolver().notifyChange(SigarraContract.Notifcations.CONTENT_URI, null); } } finally { cursor.close(); } if (notToDelete.size() > 0) getContext().getContentResolver().delete(SigarraContract.Notifcations.CONTENT_URI, SigarraContract.Notifcations.getNotificationsDelete(notToDelete.toArray(new String[0])), SigarraContract.Notifcations.getNotificationsSelectionArgs(account.name, notToDelete.toArray(new String[0]))); syncResult.stats.numEntries += notifications.length; }
From source file:com.android.contacts.common.model.ContactLoader.java
private void cursorColumnToContentValues(Cursor cursor, ContentValues values, int index) { switch (cursor.getType(index)) { case Cursor.FIELD_TYPE_NULL: // don't put anything in the content values break;/* w w w . ja va 2 s.c o m*/ case Cursor.FIELD_TYPE_INTEGER: values.put(ContactQuery.COLUMNS[index], cursor.getLong(index)); break; case Cursor.FIELD_TYPE_STRING: values.put(ContactQuery.COLUMNS[index], cursor.getString(index)); break; case Cursor.FIELD_TYPE_BLOB: values.put(ContactQuery.COLUMNS[index], cursor.getBlob(index)); break; default: throw new IllegalStateException("Invalid or unhandled data type"); } }
From source file:com.raspi.chatapp.util.storage.MessageHistory.java
public MessageArrayContent getLastMessage(String buddyId) { MessageArrayContent mac = null;//from w ww. j av a2 s . c o m SQLiteDatabase db = mDbHelper.getReadableDatabase(); try { String[] columns = new String[] { MessageHistoryContract.MessageEntry.COLUMN_NAME_BUDDY_ID, MessageHistoryContract.MessageEntry.COLUMN_NAME_MESSAGE_TYPE, MessageHistoryContract.MessageEntry.COLUMN_NAME_MESSAGE_CONTENT, MessageHistoryContract.MessageEntry.COLUMN_NAME_MESSAGE_STATUS, MessageHistoryContract.MessageEntry.COLUMN_NAME_MESSAGE_TIMESTAMP, MessageHistoryContract.MessageEntry.COLUMN_NAME_MESSAGE_URL, MessageHistoryContract.MessageEntry._ID, MessageHistoryContract.MessageEntry.COLUMN_NAME_OTHERS_ID }; Cursor lastMessage = db.query(buddyId, columns, null, null, null, null, MessageHistoryContract.MessageEntry.COLUMN_NAME_MESSAGE_TIMESTAMP + " DESC", "1"); lastMessage.moveToFirst(); if (lastMessage.getCount() != 0 && lastMessage.moveToFirst()) { String type = lastMessage.getString(1); SharedPreferences preferences = context.getSharedPreferences(Constants.PREFERENCES, 0); String me = preferences.getString(Constants.USERNAME, ""); boolean sent = me.equals(lastMessage.getString(0)); if (TYPE_TEXT.equals(type)) { mac = new TextMessage(!sent, lastMessage.getString(2), lastMessage.getLong(4), lastMessage.getString(3), lastMessage.getLong(6), lastMessage.getLong(7)); } else if (TYPE_IMAGE.equals(type)) { JSONArray contentJSON = new JSONArray(lastMessage.getString(2)); mac = new ImageMessage(!sent, contentJSON.getString(0), contentJSON.getString(1), lastMessage.getString(5), lastMessage.getInt(6), lastMessage.getLong(4), lastMessage.getString(3), lastMessage.getLong(6), lastMessage.getString(1), lastMessage.getLong(7)); } } } catch (Exception e) { } finally { db.close(); } return mac; }
From source file:com.ichi2.libanki.Finder.java
private List<Long> _findCards(String query, Object _order) { String[] tokens = _tokenize(query); Pair<String, String[]> res1 = _where(tokens); String preds = res1.first;// w ww .j ava 2 s .c om String[] args = res1.second; List<Long> res = new ArrayList<Long>(); if (preds == null) { return res; } Pair<String, Boolean> res2 = _order instanceof Boolean ? _order((Boolean) _order) : _order((String) _order); String order = res2.first; boolean rev = res2.second; String sql = _query(preds, order); Cursor cur = null; try { cur = mCol.getDb().getDatabase().rawQuery(sql, args); while (cur.moveToNext()) { res.add(cur.getLong(0)); } } catch (SQLException e) { // invalid grouping return new ArrayList<Long>(); } finally { if (cur != null) { cur.close(); } } if (rev) { Collections.reverse(res); } return res; }
From source file:net.kourlas.voipms_sms.Database.java
/** * Gets all of the messages in the database except for deleted messages. * * @return All of the messages in the database except for deleted messages. *//*from ww w .j a va 2 s . co m*/ public synchronized Message[] getUndeletedMessages(String did) { List<Message> messages = new ArrayList<>(); Cursor cursor = database.query(TABLE_MESSAGE, columns, COLUMN_DID + "=" + did + " AND " + COLUMN_DELETED + "=" + "0", null, null, null, null); cursor.moveToFirst(); while (!cursor.isAfterLast()) { 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))); messages.add(message); cursor.moveToNext(); } cursor.close(); Collections.sort(messages); Message[] messageArray = new Message[messages.size()]; return messages.toArray(messageArray); }
From source file:net.kourlas.voipms_sms.Database.java
/** * Gets all of the deleted messages in the database. * * @return All of the deleted messages in the database. *///from w ww . j ava2 s . com public synchronized Message[] getDeletedMessages(String did) { List<Message> messages = new ArrayList<>(); Cursor cursor = database.query(TABLE_MESSAGE, columns, COLUMN_DID + "=" + did + " AND " + COLUMN_DELETED + "=" + "1", null, null, null, null); cursor.moveToFirst(); while (!cursor.isAfterLast()) { 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))); messages.add(message); cursor.moveToNext(); } cursor.close(); Collections.sort(messages); Message[] messageArray = new Message[messages.size()]; return messages.toArray(messageArray); }