Example usage for android.database Cursor moveToPosition

List of usage examples for android.database Cursor moveToPosition

Introduction

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

Prototype

boolean moveToPosition(int position);

Source Link

Document

Move the cursor to an absolute position.

Usage

From source file:com.android.calendar.event.CreateEventDialogFragment.java

private void setDefaultCalendarView(Cursor cursor) {
    if (cursor == null || cursor.getCount() == 0) {
        // Create an error message for the user that, when clicked,
        // will exit this activity without saving the event.
        dismiss();/*from   w w w.j a  v  a2 s .  c om*/
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle(R.string.no_syncable_calendars).setIconAttribute(android.R.attr.alertDialogIcon)
                .setMessage(R.string.no_calendars_found)
                .setPositiveButton(R.string.add_account, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        final Activity activity = getActivity();
                        if (activity != null) {
                            Intent nextIntent = new Intent(Settings.ACTION_ADD_ACCOUNT);
                            final String[] array = { "com.android.calendar" };
                            nextIntent.putExtra(Settings.EXTRA_AUTHORITIES, array);
                            nextIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                            activity.startActivity(nextIntent);
                        }
                    }
                }).setNegativeButton(android.R.string.no, null);
        builder.show();
        return;
    }

    String defaultCalendar = null;
    final Activity activity = getActivity();
    if (activity != null) {
        defaultCalendar = Utils.getSharedPreference(activity, GeneralPreferences.KEY_DEFAULT_CALENDAR,
                (String) null);
    } else {
        Log.e(TAG, "Activity is null, cannot load default calendar");
    }

    int calendarOwnerIndex = cursor.getColumnIndexOrThrow(Calendars.OWNER_ACCOUNT);
    int accountNameIndex = cursor.getColumnIndexOrThrow(Calendars.ACCOUNT_NAME);
    int accountTypeIndex = cursor.getColumnIndexOrThrow(Calendars.ACCOUNT_TYPE);

    cursor.moveToPosition(-1);
    while (cursor.moveToNext()) {
        String calendarOwner = cursor.getString(calendarOwnerIndex);
        if (defaultCalendar == null) {
            // There is no stored default upon the first time running.  Use a primary
            // calendar in this case.
            if (calendarOwner != null && calendarOwner.equals(cursor.getString(accountNameIndex))
                    && !CalendarContract.ACCOUNT_TYPE_LOCAL.equals(cursor.getString(accountTypeIndex))) {
                setCalendarFields(cursor);
                return;
            }
        } else if (defaultCalendar.equals(calendarOwner)) {
            // Found the default calendar.
            setCalendarFields(cursor);
            return;
        }
    }
    cursor.moveToFirst();
    setCalendarFields(cursor);
}

From source file:info.guardianproject.otr.app.im.app.NewChatActivity.java

public boolean showChat(long requestedChatId) {
    Cursor cursorChats = mChatPagerAdapter.getCursor();

    if (cursorChats == null)
        return false;

    cursorChats.moveToPosition(-1);
    int posIdx = 1;

    while (cursorChats.moveToNext()) {
        long chatId = cursorChats.getLong(ChatView.CONTACT_ID_COLUMN);

        if (chatId == requestedChatId) {
            mChatPager.setCurrentItem(posIdx);
            return true;
        }//from   ww  w  . java2 s .c  o m

        posIdx++;
    }

    // Was not found
    return false;
}

From source file:com.tandong.sa.sherlock.widget.SearchView.java

/**
 * Query rewriting./*from   w  w  w  . j  av a 2  s  .  c om*/
 */
private void rewriteQueryFromSuggestion(int position) {
    CharSequence oldQuery = mQueryTextView.getText();
    Cursor c = mSuggestionsAdapter.getCursor();
    if (c == null) {
        return;
    }
    if (c.moveToPosition(position)) {
        // Get the new query from the suggestion.
        CharSequence newQuery = mSuggestionsAdapter.convertToString(c);
        if (newQuery != null) {
            // The suggestion rewrites the query.
            // Update the text field, without getting new suggestions.
            setQuery(newQuery);
        } else {
            // The suggestion does not rewrite the query, restore the user's
            // query.
            setQuery(oldQuery);
        }
    } else {
        // We got a bad position, restore the user's query.
        setQuery(oldQuery);
    }
}

From source file:org.totschnig.myexpenses.activity.ExpenseEdit.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.one_expense);

    mDateFormat = android.text.format.DateFormat.getDateFormat(this);
    mTimeFormat = android.text.format.DateFormat.getTimeFormat(this);

    setupToolbar();/*from www  . j a  v  a2  s.  c om*/
    mManager = getSupportLoaderManager();
    //we enable it only after accountcursor has been loaded, preventing NPE when user clicks on it early
    configTypeButton();
    mTypeButton.setEnabled(false);
    mCommentText = (EditText) findViewById(R.id.Comment);
    mTitleText = (EditText) findViewById(R.id.Title);
    mReferenceNumberText = (EditText) findViewById(R.id.Number);
    mDateButton = (Button) findViewById(R.id.DateButton);
    mAttachPictureButton = (ImageView) findViewById(R.id.AttachImage);
    mPictureViewContainer = (FrameLayout) findViewById(R.id.picture_container);
    mTimeButton = (Button) findViewById(R.id.TimeButton);
    mPayeeLabel = (TextView) findViewById(R.id.PayeeLabel);
    mPayeeText = (AutoCompleteTextView) findViewById(R.id.Payee);
    mTransferAmountText = (AmountEditText) findViewById(R.id.TranferAmount);
    mExchangeRate1Text = (AmountEditText) findViewById(R.id.ExchangeRate_1);
    mExchangeRate1Text.setFractionDigits(EXCHANGE_RATE_FRACTION_DIGITS);
    mExchangeRate1Text.addTextChangedListener(new LinkedExchangeRateTextWatchter(true));
    mExchangeRate2Text = (AmountEditText) findViewById(R.id.ExchangeRate_2);
    mExchangeRate2Text.setFractionDigits(EXCHANGE_RATE_FRACTION_DIGITS);
    mExchangeRate2Text.addTextChangedListener(new LinkedExchangeRateTextWatchter(false));

    mPayeeAdapter = new SimpleCursorAdapter(this, R.layout.support_simple_spinner_dropdown_item, null,
            new String[] { KEY_PAYEE_NAME }, new int[] { android.R.id.text1 }, 0);
    mPayeeText.setAdapter(mPayeeAdapter);
    mPayeeAdapter.setFilterQueryProvider(new FilterQueryProvider() {
        @SuppressLint("NewApi")
        public Cursor runQuery(CharSequence str) {
            if (str == null) {
                return null;
            }
            String search = Utils.esacapeSqlLikeExpression(Utils.normalize(str.toString()));
            //we accept the string at the beginning of a word
            String selection = KEY_PAYEE_NAME_NORMALIZED + " LIKE ? OR " + KEY_PAYEE_NAME_NORMALIZED
                    + " LIKE ? OR " + KEY_PAYEE_NAME_NORMALIZED + " LIKE ?";
            String[] selectArgs = { search + "%", "% " + search + "%", "%." + search + "%" };
            return getContentResolver().query(TransactionProvider.PAYEES_URI, new String[] { KEY_ROWID,
                    KEY_PAYEE_NAME,
                    "(SELECT max(" + KEY_ROWID + ") FROM " + TABLE_TRANSACTIONS + " WHERE " + WHERE_NOT_SPLIT
                            + " AND " + KEY_PAYEEID + " = " + TABLE_PAYEES + "." + KEY_ROWID + ")" },
                    selection, selectArgs, null);
        }
    });

    mPayeeAdapter.setCursorToStringConverter(new CursorToStringConverter() {
        public CharSequence convertToString(Cursor cur) {
            return cur.getString(1);
        }
    });
    mPayeeText.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Cursor c = (Cursor) mPayeeAdapter.getItem(position);
            if (c.moveToPosition(position)) {
                mTransaction.updatePayeeWithId(c.getString(1), c.getLong(0));
                if (mNewInstance && mTransaction != null
                        && !(mTransaction instanceof Template || mTransaction instanceof SplitTransaction)) {
                    //moveToPosition should not be necessary,
                    //but has been reported to not be positioned correctly on samsung GT-I8190N
                    if (!c.isNull(2)) {
                        if (PrefKey.AUTO_FILL_HINT_SHOWN.getBoolean(false)) {
                            if (PrefKey.AUTO_FILL.getBoolean(true)) {
                                startAutoFill(c.getLong(2));
                            }
                        } else {
                            Bundle b = new Bundle();
                            b.putLong(KEY_ROWID, c.getLong(2));
                            b.putInt(ConfirmationDialogFragment.KEY_TITLE, R.string.dialog_title_information);
                            b.putString(ConfirmationDialogFragment.KEY_MESSAGE,
                                    getString(R.string.hint_auto_fill));
                            b.putInt(ConfirmationDialogFragment.KEY_COMMAND_POSITIVE, R.id.AUTO_FILL_COMMAND);
                            b.putString(ConfirmationDialogFragment.KEY_PREFKEY,
                                    PrefKey.AUTO_FILL_HINT_SHOWN.getKey());
                            b.putInt(ConfirmationDialogFragment.KEY_POSITIVE_BUTTON_LABEL, R.string.yes);
                            b.putInt(ConfirmationDialogFragment.KEY_NEGATIVE_BUTTON_LABEL, R.string.no);
                            ConfirmationDialogFragment.newInstance(b).show(getSupportFragmentManager(),
                                    "AUTO_FILL_HINT");
                        }
                    }
                }
            }
        }
    });

    mCategoryButton = (Button) findViewById(R.id.Category);
    mPlanButton = (Button) findViewById(R.id.Plan);
    mMethodSpinner = (Spinner) findViewById(R.id.Method);
    mAccountSpinner = new SpinnerHelper(findViewById(R.id.Account));
    mTransferAccountSpinner = new SpinnerHelper(findViewById(R.id.TransferAccount));
    mTransferAccountSpinner.setOnItemSelectedListener(this);
    mStatusSpinner = new SpinnerHelper(findViewById(R.id.Status));
    mReccurenceSpinner = new SpinnerHelper(findViewById(R.id.Recurrence));
    mPlanToggleButton = (ToggleButton) findViewById(R.id.PlanExecutionAutomatic);
    TextPaint paint = mPlanToggleButton.getPaint();
    int automatic = (int) paint.measureText(getString(R.string.plan_automatic));
    int manual = (int) paint.measureText(getString(R.string.plan_manual));
    mPlanToggleButton.setWidth((automatic > manual ? automatic : manual) + +mPlanToggleButton.getPaddingLeft()
            + mPlanToggleButton.getPaddingRight());

    mRowId = Utils.getFromExtra(getIntent().getExtras(), KEY_ROWID, 0);

    //upon orientation change stored in instance state, since new splitTransactions are immediately persisted to DB
    if (savedInstanceState != null) {
        mSavedInstance = true;
        mRowId = savedInstanceState.getLong(KEY_ROWID);
        mPictureUri = savedInstanceState.getParcelable(KEY_PICTURE_URI);
        mPictureUriTemp = savedInstanceState.getParcelable(KEY_PICTURE_URI_TMP);
        setPicture();

        mCalendar = (Calendar) savedInstanceState.getSerializable(KEY_CALENDAR);
        mLabel = savedInstanceState.getString(KEY_LABEL);
        if ((mCatId = savedInstanceState.getLong(KEY_CATID)) == 0L) {
            mCatId = null;
        }
        if ((mMethodId = savedInstanceState.getLong(KEY_METHODID)) == 0L)
            mMethodId = null;
        if ((mAccountId = savedInstanceState.getLong(KEY_ACCOUNTID)) == 0L) {
            mAccountId = null;
        } else {
            //once user has selected account, we no longer want
            //the passed in KEY_CURRENCY to override it in onLoadFinished
            getIntent().removeExtra(KEY_CURRENCY);
        }
        if ((mTransferAccountId = savedInstanceState.getLong(KEY_TRANSFER_ACCOUNT)) == 0L)
            mTransferAccountId = null;
    }
    mTemplateId = getIntent().getLongExtra(KEY_TEMPLATEID, 0);
    //were we called from a notification
    int notificationId = getIntent().getIntExtra(MyApplication.KEY_NOTIFICATION_ID, 0);
    if (notificationId > 0) {
        ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).cancel(notificationId);
    }

    CrStatusAdapter sAdapter = new CrStatusAdapter(this) {

        @Override
        public boolean isEnabled(int position) {
            //if the transaction is reconciled, the status can not be changed
            //otherwise only unreconciled and cleared can be set
            return mTransaction != null && mTransaction.crStatus != CrStatus.RECONCILED
                    && position != CrStatus.RECONCILED.ordinal();
        }
    };
    mStatusSpinner.setAdapter(sAdapter);

    //1. fetch the transaction or create a new instance
    if (mRowId != 0 || mTemplateId != 0) {
        mNewInstance = false;
        int taskId;
        Serializable extra = null;
        Long objectId;
        if (mRowId != 0) {
            taskId = TaskExecutionFragment.TASK_INSTANTIATE_TRANSACTION;
            //if called with extra KEY_CLONE, we ask the task to clone, but no longer after orientation change
            extra = getIntent().getBooleanExtra(KEY_CLONE, false) && savedInstanceState == null;
            objectId = mRowId;
        } else {
            objectId = mTemplateId;
            //are we editing the template or instantiating a new one
            if ((mPlanInstanceId = getIntent().getLongExtra(KEY_INSTANCEID, 0)) != 0L) {
                taskId = TaskExecutionFragment.TASK_INSTANTIATE_TRANSACTION_FROM_TEMPLATE;
                mPlanInstanceDate = getIntent().getLongExtra(KEY_DATE, 0);
                mRecordTemplateWidget = getIntent().getBooleanExtra(AbstractWidget.EXTRA_START_FROM_WIDGET,
                        false) && !ContribFeature.TEMPLATE_WIDGET.hasAccess();
            } else {
                taskId = TaskExecutionFragment.TASK_INSTANTIATE_TEMPLATE;
            }
        }
        FragmentManager fm = getSupportFragmentManager();
        if (fm.findFragmentByTag(ProtectionDelegate.ASYNC_TAG) == null) {
            startTaskExecution(taskId, new Long[] { objectId }, extra, R.string.progress_dialog_loading);
        }
    } else {
        mOperationType = getIntent().getIntExtra(MyApplication.KEY_OPERATION_TYPE, MyExpenses.TYPE_TRANSACTION);
        if (!isValidType(mOperationType)) {
            mOperationType = MyExpenses.TYPE_TRANSACTION;
        }
        if (mOperationType == MyExpenses.TYPE_SPLIT && !ContribFeature.SPLIT_TRANSACTION.hasAccess()
                && ContribFeature.SPLIT_TRANSACTION.usagesLeft() < 1) {
            Toast.makeText(this, ContribFeature.SPLIT_TRANSACTION.buildRequiresString(this), Toast.LENGTH_LONG)
                    .show();
            finish();
            return;
        }
        final Long parentId = getIntent().getLongExtra(KEY_PARENTID, 0);
        final boolean isNewTemplate = getIntent().getBooleanExtra(KEY_NEW_TEMPLATE, false);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        View spinner = findViewById(R.id.OperationType);
        mOperationTypeSpinner = new SpinnerHelper(spinner);
        spinner.setVisibility(View.VISIBLE);
        List<Integer> allowedOperationTypes = new ArrayList<>();
        allowedOperationTypes.add(MyExpenses.TYPE_TRANSACTION);
        allowedOperationTypes.add(MyExpenses.TYPE_TRANSFER);
        if (!isNewTemplate && parentId == 0) {
            allowedOperationTypes.add(MyExpenses.TYPE_SPLIT);
        }
        mOperationTypeAdapter = new OperationTypeAdapter(this, allowedOperationTypes, isNewTemplate,
                parentId != 0);
        mOperationTypeSpinner.setAdapter(mOperationTypeAdapter);
        resetOperationType();
        mOperationTypeSpinner.setOnItemSelectedListener(this);
        Long accountId = getIntent().getLongExtra(KEY_ACCOUNTID, 0);
        if (isNewTemplate) {
            mTransaction = Template.getTypedNewInstance(mOperationType, accountId);
        } else {
            switch (mOperationType) {
            case MyExpenses.TYPE_TRANSACTION:
                if (accountId == 0L) {
                    accountId = MyApplication.getInstance().getSettings()
                            .getLong(PREFKEY_TRANSACTION_LAST_ACCOUNT_FROM_WIDGET, 0L);
                }
                mTransaction = parentId == 0L ? Transaction.getNewInstance(accountId)
                        : SplitPartCategory.getNewInstance(accountId, parentId);
                break;
            case MyExpenses.TYPE_TRANSFER:
                Long transfer_account = 0L;
                if (accountId == 0L) {
                    accountId = MyApplication.getInstance().getSettings()
                            .getLong(PREFKEY_TRANSFER_LAST_ACCOUNT_FROM_WIDGET, 0L);
                    transfer_account = MyApplication.getInstance().getSettings()
                            .getLong(PREFKEY_TRANSFER_LAST_TRANSFER_ACCOUNT_FROM_WIDGET, 0L);
                }
                mTransaction = parentId == 0L ? Transfer.getNewInstance(accountId, transfer_account)
                        : SplitPartTransfer.getNewInstance(accountId, parentId, transfer_account);
                break;
            case MyExpenses.TYPE_SPLIT:
                if (accountId == 0L) {
                    accountId = MyApplication.getInstance().getSettings()
                            .getLong(PREFKEY_SPLIT_LAST_ACCOUNT_FROM_WIDGET, 0L);
                }
                mTransaction = SplitTransaction.getNewInstance(accountId);
                //Split transactions are returned persisted to db and already have an id
                if (mTransaction != null) {
                    mRowId = mTransaction.getId();
                }
                break;
            }
        }
        if (mTransaction == null) {
            String errMsg = "Error instantiating transaction for account " + accountId;
            AcraHelper.report(new IllegalStateException(errMsg), "Extras", getIntent().getExtras().toString());
            Toast.makeText(this, errMsg, Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        if (!mSavedInstance) {
            //processing data from user switching operation type
            Transaction cached = (Transaction) getIntent().getSerializableExtra(KEY_CACHED_DATA);
            if (cached != null) {
                mTransaction.accountId = cached.accountId;
                mCalendar.setTime(cached.getDate());
                mPictureUri = getIntent().getParcelableExtra(KEY_CACHED_PICTURE_URI);
                setPicture();
                mTransaction.methodId = cached.methodId;
            }
        }
        setup();
    }
}

From source file:info.guardianproject.otr.app.im.app.NewChatActivity.java

private void doResolveIntent(Intent intent) {

    if (requireOpenDashboardOnStart(intent)) {
        long providerId = intent.getLongExtra(ImServiceConstants.EXTRA_INTENT_PROVIDER_ID, -1L);
        mLastAccountId = intent.getLongExtra(ImServiceConstants.EXTRA_INTENT_ACCOUNT_ID, -1L);
        if (providerId == -1L || mLastAccountId == -1L) {
            finish();/*from  w w  w  .j a v a  2 s .c o m*/
        } else {
            //   mChatSwitcher.open();
        }
        return;
    }

    if (ImServiceConstants.ACTION_MANAGE_SUBSCRIPTION.equals(intent.getAction())) {

        long providerId = intent.getLongExtra(ImServiceConstants.EXTRA_INTENT_PROVIDER_ID, -1);
        mLastAccountId = intent.getLongExtra(ImServiceConstants.EXTRA_INTENT_ACCOUNT_ID, -1L);
        String from = intent.getStringExtra(ImServiceConstants.EXTRA_INTENT_FROM_ADDRESS);

        if ((providerId == -1) || (from == null)) {
            finish();
        } else {

            showSubscriptionDialog(providerId, from);

        }
    } else if (intent != null) {
        Uri data = intent.getData();

        if (intent.getBooleanExtra("showaccounts", false))
            mDrawer.openDrawer(GravityCompat.START);

        if (data != null) {
            if (data.getScheme() != null && data.getScheme().equals("immu")) {
                String user = data.getUserInfo();
                String host = data.getHost();
                String path = null;

                if (data.getPathSegments().size() > 0)
                    path = data.getPathSegments().get(0);

                if (host != null && path != null) {

                    IImConnection connMUC = findConnectionForGroupChat(user, host);

                    if (connMUC != null) {

                        startGroupChat(path, host, user, connMUC);
                        setResult(RESULT_OK);
                    } else {
                        mHandler.showAlert("Connection Error",
                                "Unable to find a connection to join a group chat from. Please sign in and try again.");
                        setResult(Activity.RESULT_CANCELED);
                        finish();
                    }

                }

            } else {

                String type = getContentResolver().getType(data);
                if (Imps.Chats.CONTENT_ITEM_TYPE.equals(type)) {

                    long requestedContactId = ContentUris.parseId(data);

                    Cursor cursorChats = mChatPagerAdapter.getCursor();

                    if (cursorChats != null) {
                        cursorChats.moveToPosition(-1);
                        int posIdx = 1;
                        boolean foundChatView = false;

                        while (cursorChats.moveToNext()) {
                            long chatId = cursorChats.getLong(ChatView.CONTACT_ID_COLUMN);

                            if (chatId == requestedContactId) {
                                mChatPager.setCurrentItem(posIdx);
                                foundChatView = true;
                                break;
                            }

                            posIdx++;
                        }

                        if (!foundChatView) {

                            Uri.Builder builder = Imps.Contacts.CONTENT_URI.buildUpon();
                            ContentUris.appendId(builder, requestedContactId);
                            Cursor cursor = getContentResolver().query(builder.build(),
                                    ChatView.CHAT_PROJECTION, null, null, null);

                            try {
                                if (cursor.getCount() > 0) {
                                    cursor.moveToFirst();
                                    openExistingChat(cursor);
                                }
                            } finally {
                                cursor.close();
                            }
                        }
                    }

                } else if (Imps.Invitation.CONTENT_ITEM_TYPE.equals(type)) {
                    //chatView.bindInvitation(ContentUris.parseId(data));

                }
            }
        } else if (intent.hasExtra(ImServiceConstants.EXTRA_INTENT_ACCOUNT_ID)) {
            //set the current account id
            mLastAccountId = intent.getLongExtra(ImServiceConstants.EXTRA_INTENT_ACCOUNT_ID, -1L);

            //move the pager back to the first page
            if (mChatPager != null)
                mChatPager.setCurrentItem(0);

        } else {
            //  refreshConnections();
        }
    }

}

From source file:com.android.contacts.ContactSaveService.java

private long[] getRawContactIdsForAggregation(long[] contactIds) {
    if (contactIds == null) {
        return null;
    }/*  www. ja  v a  2 s.co  m*/

    final ContentResolver resolver = getContentResolver();

    final StringBuilder queryBuilder = new StringBuilder();
    final String stringContactIds[] = new String[contactIds.length];
    for (int i = 0; i < contactIds.length; i++) {
        queryBuilder.append(RawContacts.CONTACT_ID + "=?");
        stringContactIds[i] = String.valueOf(contactIds[i]);
        if (contactIds[i] == -1) {
            return null;
        }
        if (i == contactIds.length - 1) {
            break;
        }
        queryBuilder.append(" OR ");
    }

    final Cursor c = resolver.query(RawContacts.CONTENT_URI, JoinContactQuery.PROJECTION,
            queryBuilder.toString(), stringContactIds, null);
    if (c == null) {
        Log.e(TAG, "Unable to open Contacts DB cursor");
        showToast(R.string.contactSavedErrorToast);
        return null;
    }
    long rawContactIds[];
    try {
        if (c.getCount() < 2) {
            Log.e(TAG, "Not enough raw contacts to aggregate together.");
            return null;
        }
        rawContactIds = new long[c.getCount()];
        for (int i = 0; i < rawContactIds.length; i++) {
            c.moveToPosition(i);
            long rawContactId = c.getLong(JoinContactQuery._ID);
            rawContactIds[i] = rawContactId;
        }
    } finally {
        c.close();
    }
    return rawContactIds;
}

From source file:com.google.android.apps.muzei.provider.MuzeiProvider.java

/**
 * Limit the number of cached files per art source to {@link #MAX_CACHE_SIZE}.
 * @see #MAX_CACHE_SIZE/*from www.j av a  2  s  . c o m*/
 */
private void cleanupCachedFiles() {
    Context context = getContext();
    if (context == null) {
        return;
    }
    Cursor sources = querySource(MuzeiContract.Sources.CONTENT_URI,
            new String[] { MuzeiContract.Sources.COLUMN_NAME_COMPONENT_NAME }, null, null, null);
    if (sources == null) {
        return;
    }
    // Access to certain artwork can be persisted through MuzeiDocumentsProvider
    // We never want to delete these artwork as that would break other apps
    Set<Uri> persistedUris = MuzeiDocumentsProvider.getPersistedArtworkUris(context);
    // Loop through each source, cleaning up old artwork
    while (sources.moveToNext()) {
        String componentName = sources.getString(0);
        // Now use that ComponentName to look through the past artwork from that source
        Cursor artworkBySource = queryArtwork(MuzeiContract.Artwork.CONTENT_URI,
                new String[] { BaseColumns._ID, MuzeiContract.Artwork.COLUMN_NAME_IMAGE_URI,
                        MuzeiContract.Artwork.COLUMN_NAME_TOKEN },
                MuzeiContract.Artwork.COLUMN_NAME_SOURCE_COMPONENT_NAME + "=?", new String[] { componentName },
                MuzeiContract.Artwork.COLUMN_NAME_DATE_ADDED + " DESC");
        if (artworkBySource == null) {
            continue;
        }
        List<String> artworkIdsToKeep = new ArrayList<>();
        List<String> artworkToKeep = new ArrayList<>();
        // First find all of the persisted artwork from this source and mark them as artwork to keep
        while (artworkBySource.moveToNext()) {
            long id = artworkBySource.getLong(0);
            Uri uri = ContentUris.withAppendedId(MuzeiContract.Artwork.CONTENT_URI, id);
            String artworkUri = artworkBySource.getString(1);
            String artworkToken = artworkBySource.getString(2);
            String unique = !TextUtils.isEmpty(artworkUri) ? artworkUri : artworkToken;
            if (persistedUris.contains(uri)) {
                // Always keep artwork that is persisted
                artworkIdsToKeep.add(Long.toString(id));
                artworkToKeep.add(unique);
            }
        }
        // Now go through the artwork from this source and find the most recent artwork
        // and mark them as artwork to keep
        int count = 0;
        artworkBySource.moveToPosition(-1);
        while (artworkBySource.moveToNext()) {
            // BaseColumns._ID is a long, but we need it as a String later anyways
            String id = artworkBySource.getString(0);
            String artworkUri = artworkBySource.getString(1);
            String artworkToken = artworkBySource.getString(2);
            String unique = !TextUtils.isEmpty(artworkUri) ? artworkUri : artworkToken;
            if (artworkToKeep.contains(unique)) {
                // This ensures we are double counting the same artwork in our count
                artworkIdsToKeep.add(id);
                continue;
            }
            if (count++ < MAX_CACHE_SIZE) {
                // Keep artwork below the MAX_CACHE_SIZE
                artworkIdsToKeep.add(id);
                artworkToKeep.add(unique);
            }
        }
        // Now delete all artwork not in the keep list
        int numDeleted = deleteArtwork(MuzeiContract.Artwork.CONTENT_URI,
                MuzeiContract.Artwork.COLUMN_NAME_SOURCE_COMPONENT_NAME + "=?" + " AND "
                        + MuzeiContract.Artwork.TABLE_NAME + "." + BaseColumns._ID + " NOT IN ("
                        + TextUtils.join(",", artworkIdsToKeep) + ")",
                new String[] { componentName });
        if (numDeleted > 0) {
            Log.d(TAG, "For " + componentName + " kept " + artworkToKeep.size() + " artwork, deleted "
                    + numDeleted);
        }
        artworkBySource.close();
    }
    sources.close();
}

From source file:org.getlantern.firetweet.provider.FiretweetDataProvider.java

private void showTimelineNotification(AccountPreferences pref, long position) {
    final long accountId = pref.getAccountId();
    final Context context = getContext();
    final Resources resources = context.getResources();
    final NotificationManager nm = getNotificationManager();
    final Expression selection = Expression.and(Expression.equals(Statuses.ACCOUNT_ID, accountId),
            Expression.greaterThan(Statuses.STATUS_ID, position));
    final String filteredSelection = Utils.buildStatusFilterWhereClause(Statuses.TABLE_NAME, selection)
            .getSQL();/* w ww.  j  a  v  a2  s .  co m*/
    final String[] userProjection = { Statuses.USER_ID, Statuses.USER_NAME, Statuses.USER_SCREEN_NAME };
    final String[] statusProjection = { Statuses.STATUS_ID };
    final Cursor statusCursor = mDatabaseWrapper.query(Statuses.TABLE_NAME, statusProjection, filteredSelection,
            null, null, null, Statuses.SORT_ORDER_TIMESTAMP_DESC);
    final Cursor userCursor = mDatabaseWrapper.query(Statuses.TABLE_NAME, userProjection, filteredSelection,
            null, Statuses.USER_ID, null, Statuses.SORT_ORDER_TIMESTAMP_DESC);
    try {
        final int usersCount = userCursor.getCount();
        final int statusesCount = statusCursor.getCount();
        if (statusesCount == 0 || usersCount == 0)
            return;
        final int idxStatusId = statusCursor.getColumnIndex(Statuses.STATUS_ID),
                idxUserName = userCursor.getColumnIndex(Statuses.USER_NAME),
                idxUserScreenName = userCursor.getColumnIndex(Statuses.USER_NAME),
                idxUserId = userCursor.getColumnIndex(Statuses.USER_NAME);
        final long statusId = statusCursor.moveToFirst() ? statusCursor.getLong(idxStatusId) : -1;
        final String notificationTitle = resources.getQuantityString(R.plurals.N_new_statuses, statusesCount,
                statusesCount);
        final String notificationContent;
        userCursor.moveToFirst();
        final String displayName = UserColorNameUtils.getUserNickname(context, userCursor.getLong(idxUserId),
                mNameFirst ? userCursor.getString(idxUserName) : userCursor.getString(idxUserScreenName));
        if (usersCount == 1) {
            notificationContent = context.getString(R.string.from_name, displayName);
        } else if (usersCount == 2) {
            userCursor.moveToPosition(1);
            final String othersName = UserColorNameUtils.getUserNickname(context, userCursor.getLong(idxUserId),
                    mNameFirst ? userCursor.getString(idxUserName) : userCursor.getString(idxUserScreenName));
            notificationContent = resources.getQuantityString(R.plurals.from_name_and_N_others, usersCount - 1,
                    othersName, usersCount - 1);
        } else {
            userCursor.moveToPosition(1);
            final String othersName = UserColorNameUtils.getUserNickname(context, userCursor.getLong(idxUserId),
                    mNameFirst ? userCursor.getString(idxUserName) : userCursor.getString(idxUserScreenName));
            notificationContent = resources.getString(R.string.from_name_and_N_others, othersName,
                    usersCount - 1);
        }

        // Setup notification
        final NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
        builder.setAutoCancel(true);
        builder.setSmallIcon(R.drawable.ic_stat_twitter);
        builder.setTicker(notificationTitle);
        builder.setContentTitle(notificationTitle);
        builder.setContentText(notificationContent);
        builder.setCategory(NotificationCompat.CATEGORY_SOCIAL);
        builder.setContentIntent(getContentIntent(context, AUTHORITY_HOME, accountId));
        builder.setDeleteIntent(getDeleteIntent(context, AUTHORITY_HOME, accountId, statusId));
        builder.setNumber(statusesCount);
        builder.setColor(pref.getNotificationLightColor());
        setNotificationPreferences(builder, pref, pref.getHomeTimelineNotificationType());
        nm.notify("home_" + accountId, NOTIFICATION_ID_HOME_TIMELINE, builder.build());
        Utils.sendPebbleNotification(context, notificationContent);
    } finally {
        statusCursor.close();
        userCursor.close();
    }
}

From source file:com.android.bluetooth.map.BluetoothMapContent.java

public void dumpSmsTable() {
    addSmsEntry();// ww  w . j  ava  2s.  c o m
    if (D)
        Log.d(TAG, "**** Dump of sms table ****");
    Cursor c = mResolver.query(Sms.CONTENT_URI, SMS_PROJECTION, null, null, "_id DESC");
    if (c != null) {
        if (D)
            Log.d(TAG, "c.getCount() = " + c.getCount());
        c.moveToPosition(-1);
        while (c.moveToNext()) {
            printSms(c);
        }
        c.close();
    } else {
        Log.d(TAG, "query failed");
    }

}