Example usage for android.database Cursor moveToLast

List of usage examples for android.database Cursor moveToLast

Introduction

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

Prototype

boolean moveToLast();

Source Link

Document

Move the cursor to the last row.

Usage

From source file:org.thoughtcrime.securesms.service.MessageNotifier.java

private static Recipients getMostRecentRecipients(Context context, Cursor c) {
    if (c != null && c.moveToLast()) {
        try {/*from  w  ww  .  j a  v  a  2s .  co m*/
            String type = c.getString(c.getColumnIndexOrThrow(MmsSmsDatabase.TRANSPORT));

            if (type.equals("sms"))
                return getSmsRecipient(context, c);
            else
                return getMmsRecipient(context, c);

        } catch (RecipientFormattingException e) {
            return new Recipients(new LinkedList<Recipient>());
        }
    }

    return null;
}

From source file:Main.java

public static long getLastProgramEndTimeMillis(ContentResolver resolver, Uri channelUri) {
    Uri uri = TvContract.buildProgramsUriForChannel(channelUri);
    String[] projection = { Programs.COLUMN_END_TIME_UTC_MILLIS };
    Cursor cursor = null;
    try {/* www.  ja va 2  s.com*/
        // TvProvider returns programs chronological order by default.
        cursor = resolver.query(uri, projection, null, null, null);
        if (cursor == null || cursor.getCount() == 0) {
            return 0;
        }
        cursor.moveToLast();
        return cursor.getLong(0);
    } catch (Exception e) {
        Log.w(TAG, "Unable to get last program end time for " + channelUri, e);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
    return 0;
}

From source file:org.thoughtcrime.securesms.service.MessageNotifier.java

private static PendingIntent buildPendingIntent(Context context, Cursor c, Recipients recipients) {
    Intent intent = new Intent(context, ConversationListActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

    Log.w("SMSNotifier", "Building pending intent...");
    if (c != null && c.getCount() == 1) {
        Log.w("SMSNotifier", "Adding extras...");
        c.moveToLast();
        long threadId = c.getLong(c.getColumnIndexOrThrow(SmsDatabase.THREAD_ID));
        Log.w("SmsNotifier", "Adding thread_id to pending intent: " + threadId);

        if (recipients.getPrimaryRecipient() != null) {
            intent.putExtra("recipients", recipients);
            intent.putExtra("thread_id", threadId);
        }//from  ww  w. j a  v  a  2  s.c o m

        intent.setData((Uri.parse("custom://" + System.currentTimeMillis())));
    }

    return PendingIntent.getActivity(context, 0, intent, 0);
}

From source file:org.codarama.haxsync.services.ContactsSyncAdapterService.java

private static void updateContactPhoto(long rawContactId, long timestamp, int maxSize, boolean square,
        String imgUrl, boolean faceDetect, boolean force, boolean root, int rootsize, File cacheDir,
        boolean google, boolean primary) {
    if (imgUrl != null) {

        String where = ContactsContract.Data.RAW_CONTACT_ID + " = '" + rawContactId + "' AND "
                + ContactsContract.Data.MIMETYPE + " = '"
                + ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE + "'";

        //getting the old timestamp
        String oldurl = "";
        boolean newpic = force;

        if (!newpic) {
            Cursor c1 = mContentResolver.query(ContactsContract.Data.CONTENT_URI,
                    new String[] { ContactsContract.Data.SYNC3 }, where, null, null);
            if (c1.getCount() > 0) {
                c1.moveToLast();

                if (!c1.isNull(c1.getColumnIndex(ContactsContract.Data.SYNC3))) {
                    oldurl = c1.getString(c1.getColumnIndex(ContactsContract.Data.SYNC3));
                    //Log.i(TAG, "read old timestamp: " + oldTimestamp);
                }//from   ww w . j a va2s . c om
            }
            c1.close();

            //Log.i(TAG, "Old Timestamp " +String.valueOf(oldTimestamp) + "new timestamp: " + String.valueOf(timestamp));

            if (!oldurl.equals(imgUrl)) {
                Log.i(TAG, "OLD URL: " + oldurl);
                Log.i(TAG, "NEW URL: " + imgUrl);
                newpic = true;
            }

        }

        if (newpic) {
            Log.i(TAG, "getting new image, " + imgUrl);
            //   Log.i(TAG, "Old Timestamp " +String.valueOf(oldTimestamp) + "new timestamp: " + String.valueOf(timestamp));

            byte[] photo = WebUtil.download(imgUrl);
            byte[] origPhoto = photo;

            /*if(square)
                   photo = BitmapUtil.resize(photo, maxSize, faceDetect);*/

            ContactUtil.Photo photoi = new Photo();
            photoi.data = photo;
            photoi.timestamp = timestamp;
            photoi.url = imgUrl;

            ContactUtil.updateContactPhoto(mContentResolver, rawContactId, photoi, primary);

            if (root) {
                Cursor c1 = mContentResolver.query(ContactsContract.Data.CONTENT_URI,
                        new String[] { ContactsContract.CommonDataKinds.Photo.PHOTO_FILE_ID }, where, null,
                        null);
                if (c1.getCount() > 0) {
                    c1.moveToLast();
                    String photoID = c1
                            .getString(c1.getColumnIndex(ContactsContract.CommonDataKinds.Photo.PHOTO_FILE_ID));
                    c1.close();
                    if (photoID != null) {
                        photo = BitmapUtil.resize(origPhoto, rootsize, faceDetect);
                        String picpath = DeviceUtil.saveBytes(photo, cacheDir);
                        try {
                            String newpath = RootUtil.movePic(picpath, photoID);
                            RootUtil.changeOwner(newpath);
                        } catch (Exception e) {
                            Log.e("ROOT EXCEPTION", e.getMessage());
                            // TODO: handle exception
                        }
                    }
                }

            }
            Log.i("google photo sync", String.valueOf(google));
            if (google) {
                for (long raw : ContactUtil.getRawContacts(mContentResolver, rawContactId, "com.google")) {
                    Log.i("google rawid", String.valueOf(raw));
                    ContactUtil.updateContactPhoto(mContentResolver, raw, photoi, false);
                }
            }
        }
    }
}

From source file:org.codarama.haxsync.services.ContactsSyncAdapterService.java

@SuppressWarnings("unused")
private static void performSync(Context context, Account account, Bundle extras, String authority,
        ContentProviderClient provider, SyncResult syncResult) throws OperationCanceledException {
    SharedPreferences prefs = context.getSharedPreferences(context.getPackageName() + "_preferences",
            MODE_MULTI_PROCESS);/*from  ww  w .java 2 s. c om*/

    mContentResolver = context.getContentResolver();

    FacebookUtil.refreshPermissions(context);

    //TODO: Clean up stuff that isn't needed anymore since Graph API
    boolean cropPhotos = true;
    boolean sync = prefs.getBoolean("sync_status", true);
    boolean syncNew = prefs.getBoolean("status_new", true);
    boolean syncLocation = prefs.getBoolean("sync_location", true);
    boolean syncSelf = prefs.getBoolean("sync_self", false);
    boolean imageDefault = prefs.getBoolean("image_primary", true);

    boolean oldStatus = sync && (!syncNew || (Build.VERSION.SDK_INT < 15));
    boolean faceDetect = true;

    boolean root = prefs.getBoolean("root_enabled", false);
    int rootSize = 512;

    if (FacebookUtil.authorize(context, account)) {

        HashMap<String, SyncEntry> localContacts = getLocalContacts(account);
        HashMap<String, Long> names = loadPhoneContacts(context);
        HashMap<String, Long> uids = loadHTCData(context);
        //Log.i("CONTACTS", names.toString());
        boolean phoneOnly = prefs.getBoolean("phone_only", true);
        /*if (phoneOnly){
           names = loadPhoneContacts(context);
        }*/
        boolean wifiOnly = prefs.getBoolean("wifi_only", false);
        boolean syncEmail = prefs.getBoolean("sync_facebook_email", false);
        boolean syncBirthday = prefs.getBoolean("sync_contact_birthday", true);
        boolean force = prefs.getBoolean("force_dl", false);
        boolean google = prefs.getBoolean("update_google_photos", false);
        boolean ignoreMiddleaNames = prefs.getBoolean("ignore_middle_names", false);
        boolean addMeToFriends = prefs.getBoolean("add_me_to_friends", false);
        Log.i("google", String.valueOf(google));
        int fuzziness = Integer.parseInt(prefs.getString("fuzziness", "2"));
        Set<String> addFriends = prefs.getStringSet("add_friends", new HashSet<String>());
        Log.i(TAG, "phone_only: " + Boolean.toString(phoneOnly));
        Log.i(TAG, "wifi_only: " + Boolean.toString(wifiOnly));
        Log.i(TAG, "is wifi: " + Boolean.toString(DeviceUtil.isWifi(context)));
        Log.i(TAG, "phone contacts: " + names.toString());
        Log.i(TAG, "using old status api: " + String.valueOf(oldStatus));
        Log.i(TAG, "ignoring middle names : " + String.valueOf(ignoreMiddleaNames));
        Log.i(TAG, "add me to friends : " + String.valueOf(addMeToFriends));
        boolean chargingOnly = prefs.getBoolean("charging_only", false);
        int maxsize = BitmapUtil.getMaxSize(context.getContentResolver());
        File cacheDir = context.getCacheDir();
        Log.i("CACHE DIR", cacheDir.getAbsolutePath());
        Log.i("MAX IMAGE SIZE", String.valueOf(maxsize));
        if (!((wifiOnly && !DeviceUtil.isWifi(context)) || (chargingOnly && !DeviceUtil.isCharging(context)))) {
            try {
                if (syncSelf) {
                    addSelfContact(account, maxsize, cropPhotos, faceDetect, force, root, rootSize, cacheDir,
                            google);
                }
                List<FacebookGraphFriend> friends = FacebookUtil.getFriends(maxsize, addMeToFriends);
                for (FacebookGraphFriend friend : friends) {
                    String uid = friend.getUserName();
                    String friendName = friend.getName(ignoreMiddleaNames);
                    if (friendName != null && uid != null) {
                        String match = matches(names.keySet(), friendName, fuzziness);

                        if (!(phoneOnly && (match == null) && !uids.containsKey(uid))
                                || addFriends.contains(friendName)) {
                            // STEP 1. Add contact - if the contact is not part of the HTCData records and does not match any
                            // of the fuzziness names we add them to the list of contacts with the intention to make them available
                            // for manual merge (I guess)
                            if (localContacts.get(uid) == null) {
                                //String name = friend.getString("name");
                                //Log.i(TAG, name + " already on phone: " + Boolean.toString(names.contains(name)));

                                addContact(account, friendName, uid);

                                SyncEntry entry = new SyncEntry();
                                Uri rawContactUr = RawContacts.CONTENT_URI.buildUpon()
                                        .appendQueryParameter(RawContacts.ACCOUNT_NAME, account.name)
                                        .appendQueryParameter(RawContacts.ACCOUNT_TYPE, account.type)
                                        .appendQueryParameter(RawContacts.Data.DATA1, uid).build();
                                Cursor c = mContentResolver.query(rawContactUr,
                                        new String[] { BaseColumns._ID }, null, null, null);
                                c.moveToLast();
                                long id = c.getLong(c.getColumnIndex(BaseColumns._ID));
                                c.close();
                                //   Log.i("ID", Long.toString(id));
                                entry.raw_id = id;
                                localContacts.put(uid, entry);
                                if (uids.containsKey(uid)) {
                                    ContactUtil.merge(context, uids.get(uid), id);
                                } else if (names.containsKey(match)) {
                                    ContactUtil.merge(context, names.get(match), id);
                                }
                                //localContacts = loadContacts(accounts, context);
                            }

                            // STEP 2. Set contact photo

                            SyncEntry contact = localContacts.get(uid);

                            updateContactPhoto(contact.raw_id, friend.getPicTimestamp(), maxsize, cropPhotos,
                                    friend.getPicURL(), faceDetect, force, root, rootSize, cacheDir, google,
                                    imageDefault);

                            if (syncEmail && !FacebookUtil.RESPECT_FACEBOOK_POLICY)
                                ContactUtil.addEmail(context, contact.raw_id, friend.getEmail());

                            if (syncLocation && !FacebookUtil.RESPECT_FACEBOOK_POLICY) {
                                ContactUtil.updateContactLocation(contact.raw_id, friend.getLocation());
                            }

                            if (oldStatus && !FacebookUtil.RESPECT_FACEBOOK_POLICY) {
                                ArrayList<Status> statuses = friend.getStatuses();
                                if (statuses.size() >= 1) {
                                    updateContactStatus(contact.raw_id, statuses.get(0).getMessage(),
                                            statuses.get(0).getTimestamp());
                                }

                            }
                            if (syncBirthday && !FacebookUtil.RESPECT_FACEBOOK_POLICY) {
                                String birthday = friend.getBirthday();

                                if (birthday != null) {
                                    ContactUtil.addBirthday(contact.raw_id, birthday);
                                }
                            }

                        }
                    }
                }
            } catch (Exception e) {
                // FIXME catching the generic Exception class is not hte best thing to do
                Log.e("ERROR", e.toString());
            }

            if (root) {
                try {
                    RootUtil.refreshContacts();
                } catch (ShellException e) {
                    Log.e("Error", e.getLocalizedMessage());
                }
            }
            if (force) {
                SharedPreferences.Editor editor = prefs.edit();
                editor.putBoolean("force_dl", false);
                editor.commit();

            }

        } else {
            SharedPreferences.Editor editor = prefs.edit();
            editor.putBoolean("missed_contact_sync", true);
            editor.commit();
        }
    }
}

From source file:com.dmitrymalkovich.android.githubanalytics.dashboard.DashboardPresenter.java

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    if (data != null) {
        if (data.moveToLast()) {
            onDataLoaded(data, loader.getId());
        } else {// www  . ja  v a  2s . c  o  m
            onDataEmpty(loader.getId());
        }
    } else {
        onDataNotAvailable(loader.getId());
    }
}

From source file:com.btmura.android.reddit.app.MessageThingListController.java

@Override
public String getNextMoreId() {
    Cursor c = adapter.getCursor();
    if (c != null && c.moveToLast()) {
        if (c.getInt(MessageThingLoader.INDEX_KIND) == Kinds.KIND_MORE) {
            return c.getString(MessageThingLoader.INDEX_THING_ID);
        }//from  w  w  w  .j av a 2 s .  co  m
    }
    return null;
}

From source file:com.roamprocess1.roaming4world.ui.messages.ConversationsAdapter.java

@SuppressLint("SdCardPath")
@Override/* w w w . j a  va  2s .  co m*/
public void bindView(View view, Context context, Cursor cursor) {
    super.bindView(view, context, cursor);

    System.out.println("Conversationlist:bindView");
    final ConversationListItemViews tagView = (ConversationListItemViews) view.getTag();
    String nbr = cursor.getString(cursor.getColumnIndex(SipMessage.FIELD_FROM));
    String fromFull = cursor.getString(cursor.getColumnIndex(SipMessage.FIELD_FROM_FULL));
    String to_number = cursor.getString(cursor.getColumnIndex(SipMessage.FIELD_TO));
    int read = cursor.getInt(cursor.getColumnIndex(SipMessage.FIELD_READ));
    long date = cursor.getLong(cursor.getColumnIndex(SipMessage.FIELD_DATE));

    DBProvider db = new DBProvider();
    Cursor cr = db.allMessage(to_number, fromFull, context);
    cr.moveToLast();
    SipMessage msg1 = new SipMessage(cr);
    String lastMessage = msg1.getBodyContent();

    if (lastMessage.contains("[Offline message -") && !nbr.equals("sip:registrar@kamailio.org")) {
        System.out.println("offline message");
        String[] finalMessage = lastMessage.split("]");
        lastMessage = finalMessage[finalMessage.length - 1];
    }

    TextView txtview = (TextView) view.findViewById(R.id.subject);

    if (lastMessage.startsWith("R4WIMGTOCONTACTCHATSEND@@")) {
        txtview.setText("Image");
    } else {
        txtview.setText(lastMessage);
    }

    tagView.fromFull = fromFull;
    tagView.to = to_number;
    tagView.from = nbr;
    tagView.position = cursor.getPosition();

    /*
    Drawable background = (read == 0)?
        context.getResources().getDrawable(R.drawable.conversation_item_background_unread) :
        context.getResources().getDrawable(R.drawable.conversation_item_background_read);
            
    view.setBackgroundDrawable(background);
     */
    String number = cursor.getString(cursor.getColumnIndex(SipMessage.FIELD_FROM_FULL));
    CallerInfo info = CallerInfo.getCallerInfoFromSipUri(mContext, number);

    // Photo
    tagView.quickContactView.assignContactUri(info.contactContentUri);
    Log.setLogLevel(6);
    Log.d("Conversation adapter number", number);
    String nu = StaticValues.getStripNumber(number);
    String path = "/sdcard/R4W/ProfilePic/" + nu + ".png";
    System.out.println("msg adp out - path=" + path);
    File imageFile = new File(path);
    if (imageFile.exists()) {
        try {
            Bitmap bm = BitmapFactory.decodeFile(path);
            bm = ImageHelperCircular.getRoundedCornerBitmap(bm, bm.getWidth());
            tagView.quickContactView.getImageView().setImageBitmap(bm);
        } catch (Exception e) {
            // TODO: handle exception
            try {
                tagView.quickContactView.getImageView().setImageURI(Uri.parse(path));

            } catch (Exception e2) {
                ContactsAsyncHelper.updateImageViewWithContactPhotoAsync(mContext,
                        tagView.quickContactView.getImageView(), info, R.drawable.ic_contact_picture_holo_dark);
                // TODO: handle exception
            }
        }
    } else {

        ContactsAsyncHelper.updateImageViewWithContactPhotoAsync(mContext,
                tagView.quickContactView.getImageView(), info, R.drawable.ic_contact_picture_holo_dark);
    }

    // From
    System.out.println("formatMessage(cursor):" + formatMessage(cursor));
    tagView.fromView.setText(formatMessage(cursor));

    //Date
    // Set the date/time field by mixing relative and absolute times.
    int flags = DateUtils.FORMAT_ABBREV_RELATIVE;
    tagView.dateView.setText(DateUtils.getRelativeTimeSpanString(date, System.currentTimeMillis(),
            DateUtils.MINUTE_IN_MILLIS, flags));

}

From source file:com.github.longkai.zhihu.ui.HotItemsFragment.java

@Override
public void onClick(View v) {
    loading = true;//from   w  w w  . j  a  va  2 s . com
    page++;
    // ?
    new AsyncQueryHandler(getActivity().getContentResolver()) {
        @Override
        protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
            mAdapter.changeCursor(cursor);
            loading = false;
            if (cursor.moveToLast()) {
                // todo bug
                // ?button?
                // ?id????= =
                long index = cursor.getLong(cursor.getColumnIndex(BaseColumns._ID));
                if (index == MIN_ITEM_INDEX) {
                    loadMore.setText(getString(R.string.no_more));
                    loadMore.setClickable(false);
                }
            }
        }
    }.startQuery(0, null, Utils.parseUri(ITEMS), ITEMS_PROJECTION, null, null,
            "_id desc limit " + (page * COUNT));

}

From source file:com.wso2.mobile.mdm.api.TrackCallSMS.java

/**
 * Returns a JSONArray of SMS objects Ex: [{number:"0772345666", date:"dd/MM/yyyy hh:mm:ss.SSS", content:"Hello"}]
 * //w  w  w . j a v a  2  s . c o  m
 * @param type
 *            - Folder type should be passed in (1 for Inbox, 2 for Sent box)
 */
public JSONArray getSMS(int type) {
    JSONArray jsonArray = null;
    try {
        Uri uriSms = Uri.parse("content://sms");

        Cursor cursor = cr.query(uriSms, new String[] { "_id", "address", "date", "body", "type", "read" },
                "type=" + type, null, "date" + " COLLATE LOCALIZED ASC");

        if (cursor != null) {
            cursor.moveToLast();
            if (cursor.getCount() > 0) {
                jsonArray = new JSONArray();
                do {
                    JSONObject jsonObj = new JSONObject();
                    String date = cursor.getString(cursor.getColumnIndex("date"));
                    Long timestamp = Long.parseLong(date);
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTimeInMillis(timestamp);
                    DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss.SSS");
                    jsonObj.put("number", cursor.getString(cursor.getColumnIndex("address")));
                    jsonObj.put("date", formatter.format(calendar.getTime()));
                    /*jsonObj.put("content",
                          cursor.getString(cursor.getColumnIndex("body")));*/
                    //jsonObj.put("content","Testing SMS");
                    jsonArray.add(jsonObj);
                } while (cursor.moveToPrevious());
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return jsonArray;

}