Example usage for android.util SparseArray SparseArray

List of usage examples for android.util SparseArray SparseArray

Introduction

In this page you can find the example usage for android.util SparseArray SparseArray.

Prototype

public SparseArray(int initialCapacity) 

Source Link

Document

Creates a new SparseArray containing no mappings that will not require any additional memory allocation to store the specified number of mappings.

Usage

From source file:com.vk.sdk.api.model.VKApiModel.java

/**
 * Sets a tag associated with this model and a key. A tag can be used
 * to store data within a model without resorting to another
 * data structure.//from   ww w  . j  av a2s . c  o  m
 *
 * @see #setTag(Object)
 * @see #getTag(int)
 */
public void setTag(int key, final Object tag) {
    if (mKeyedTags == null) {
        mKeyedTags = new SparseArray<Object>(2);
    }
    mKeyedTags.put(key, tag);
}

From source file:com.tct.email.provider.EmailMessageCursor.java

public EmailMessageCursor(final Context c, final Cursor cursor, final String htmlColumn,
        final String textColumn) {
    super(cursor);
    mHtmlColumnIndex = cursor.getColumnIndex(htmlColumn);
    mTextColumnIndex = cursor.getColumnIndex(textColumn);
    final int cursorSize = cursor.getCount();
    mHtmlParts = new SparseArray<String>(cursorSize);
    mTextParts = new SparseArray<String>(cursorSize);
    //TS: jian.xu 2015-11-03 EMAIL BUGFIX-845079 ADD_S
    mHtmlLinkifyColumnIndex = cursor.getColumnIndex(UIProvider.MessageColumns.BODY_HTML_LINKIFY);
    mHtmlLinkifyParts = new SparseArray<String>(cursorSize);
    mTextLinkifyColumnIndex = cursor.getColumnIndex(UIProvider.MessageColumns.BODY_TEXT_LINKIFY);
    mTextLinkifyParts = new SparseArray<String>(cursorSize);
    //TS: jian.xu 2015-11-03 EMAIL BUGFIX-845079 ADD_E

    final ContentResolver cr = c.getContentResolver();

    while (cursor.moveToNext()) {
        final int position = cursor.getPosition();
        final long messageId = cursor.getLong(cursor.getColumnIndex(BaseColumns._ID));
        // TS: chao.zhang 2015-09-14 EMAIL BUGFIX-1039046  MOD_S
        InputStream htmlIn = null;
        InputStream textIn = null;
        try {//from   w  w  w. j av  a  2 s.  com
            if (mHtmlColumnIndex != -1) {
                final Uri htmlUri = Body.getBodyHtmlUriForMessageWithId(messageId);
                //WARNING: Actually openInput will used 2 PIPE(FD) to connect,but if some exception happen during connect,
                //such as fileNotFoundException,maybe the connection will not be closed. just a try!!!
                htmlIn = cr.openInputStream(htmlUri);
                final String underlyingHtmlString;
                try {
                    underlyingHtmlString = IOUtils.toString(htmlIn);
                } finally {
                    htmlIn.close();
                    htmlIn = null;
                }
                //TS: zhaotianyong 2015-04-05 EMAIL BUGFIX_964325 MOD_S
                final String sanitizedHtml = HtmlSanitizer.sanitizeHtml(underlyingHtmlString);
                mHtmlParts.put(position, sanitizedHtml);
                //TS: zhaotianyong 2015-04-05 EMAIL BUGFIX_964325 MOD_E
                //TS: jian.xu 2015-11-03 EMAIL BUGFIX-845079 ADD_S
                //NOTE: add links for sanitized html
                if (!TextUtils.isEmpty(sanitizedHtml)) {
                    final String linkifyHtml = com.tct.mail.utils.Linkify.addLinks(sanitizedHtml);
                    mHtmlLinkifyParts.put(position, linkifyHtml);
                } else {
                    mHtmlLinkifyParts.put(position, "");
                }
                //TS: jian.xu 2015-11-03 EMAIL BUGFIX-845079 ADD_E
            }
        } catch (final IOException e) {
            LogUtils.v(LogUtils.TAG, e, "Did not find html body for message %d", messageId);
        } catch (final OutOfMemoryError oom) {
            LogUtils.v(LogUtils.TAG, oom,
                    "Terrible,OOM happen durning query EmailMessageCursor in bodyHtml,current message %d",
                    messageId);
            mHtmlLinkifyParts.put(position, "");
        }
        try {
            if (mTextColumnIndex != -1) {
                final Uri textUri = Body.getBodyTextUriForMessageWithId(messageId);
                textIn = cr.openInputStream(textUri);
                final String underlyingTextString;
                try {
                    underlyingTextString = IOUtils.toString(textIn);
                } finally {
                    textIn.close();
                    textIn = null;
                }
                mTextParts.put(position, underlyingTextString);
                //TS: jian.xu 2015-11-03 EMAIL BUGFIX-845079 ADD_S
                //NOTE: add links for underlying text string
                if (!TextUtils.isEmpty(underlyingTextString)) {
                    final SpannableString spannable = new SpannableString(underlyingTextString);
                    Linkify.addLinks(spannable,
                            Linkify.EMAIL_ADDRESSES | Linkify.WEB_URLS | Linkify.PHONE_NUMBERS);
                    final String linkifyText = Html.toHtml(spannable);
                    mTextLinkifyParts.put(position, linkifyText);
                } else {
                    mTextLinkifyParts.put(position, "");
                }
                //TS: jian.xu 2015-11-03 EMAIL BUGFIX-845079 ADD_E
            }
        } catch (final IOException e) {
            LogUtils.v(LogUtils.TAG, e, "Did not find text body for message %d", messageId);
        } catch (final OutOfMemoryError oom) {
            LogUtils.v(LogUtils.TAG, oom,
                    "Terrible,OOM happen durning query EmailMessageCursor in bodyText,current message %d",
                    messageId);
            mTextLinkifyParts.put(position, "");
        }
        //NOTE:Remember that this just a protective code,for better release Not used Resources.
        if (htmlIn != null) {
            try {
                htmlIn.close();
            } catch (IOException e1) {
                LogUtils.v(LogUtils.TAG, e1, "IOException happen while close the htmlInput connection ");
            }
        }
        if (textIn != null) {
            try {
                textIn.close();
            } catch (IOException e2) {
                LogUtils.v(LogUtils.TAG, e2, "IOException happen while close the textInput connection ");
            }
        } // TS: chao.zhang 2015-09-14 EMAIL BUGFIX-1039046  MOD_E
    }
    cursor.moveToPosition(-1);
}

From source file:org.chaos.fx.cnbeta.MainActivity.java

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

    ButterKnife.bind(this);

    setSupportActionBar(mToolbar);/*from   w ww  .  j  a  v  a 2s  . c o m*/

    mPageTitles = new String[] { getString(R.string.nav_home), getString(R.string.nav_hot_articles),
            getString(R.string.nav_hot_comments) };
    mOnReselectListeners = new SparseArray<>(mPageTitles.length);

    mViewPager.setAdapter(new PagerAdapter(getSupportFragmentManager()));
    mViewPager.setOffscreenPageLimit(mPageTitles.length);
    mViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            mBottomBar.setSelectedItemId(INDEX_ID_MAPPING.get(position));
        }
    });
    mBottomBar.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            mViewPager.setCurrentItem(INDEX_ID_MAPPING.keyAt(INDEX_ID_MAPPING.indexOfValue(item.getItemId())),
                    false);
            return true;
        }
    });
    mBottomBar.setOnNavigationItemReselectedListener(
            new BottomNavigationView.OnNavigationItemReselectedListener() {
                @Override
                public void onNavigationItemReselected(@NonNull MenuItem item) {
                    OnReselectListener l = mOnReselectListeners.get(item.getItemId());
                    if (l != null) {
                        l.onReselect();
                    }
                }
            });

    if (Build.VERSION.SDK_INT < 21) {
        mBottomBarShadow.setVisibility(View.GONE);
    }

    mAppBarLayout.post(new Runnable() {
        @Override
        public void run() {
            setHideBarsAutomatically(PreferenceHelper.getInstance().inHideBarsAutomaticallyMode());
        }
    });

    mDefaultPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    mDefaultPreferences.registerOnSharedPreferenceChangeListener(this);

    mTimeBroadcastReceiver.register(this);
}

From source file:com.frostwire.android.gui.activities.TransferDetailActivity.java

private void initTabTitles() {
    tabTitles = new SparseArray<>(6);
    tabTitles.put(R.string.files, getString(R.string.files));
    tabTitles.put(R.string.pieces, getString(R.string.pieces));
    tabTitles.put(R.string.status, getString(R.string.status));
    tabTitles.put(R.string.details, getString(R.string.details));
    tabTitles.put(R.string.trackers, getString(R.string.trackers));
    tabTitles.put(R.string.peers, getString(R.string.peers));
}

From source file:com.appsimobile.appsii.timezonepicker.TimeZoneData.java

void loadTzs(Context context) {
    mTimeZones = new ArrayList<>();
    HashSet<String> processedTimeZones = loadTzsInZoneTab(context);
    String[] tzIds = TimeZone.getAvailableIDs();

    if (DEBUG) {//from   ww w .  jav a2s.  c  o m
        Log.e(TAG, "Available time zones: " + tzIds.length);
    }

    for (String tzId : tzIds) {
        if (processedTimeZones.contains(tzId)) {
            continue;
        }

        /*
         * Dropping non-GMT tzs without a country code. They are not really
         * needed and they are dups but missing proper country codes. e.g.
         * WET CET MST7MDT PST8PDT Asia/Khandyga Asia/Ust-Nera EST
         */
        if (!tzId.startsWith("Etc/GMT")) {
            continue;
        }

        final TimeZone tz = TimeZone.getTimeZone(tzId);
        if (tz == null) {
            Log.e(TAG, "Timezone not found: " + tzId);
            continue;
        }

        TimeZoneInfo tzInfo = new TimeZoneInfo(tz, null);

        if (getIdenticalTimeZoneInTheCountry(tzInfo) == -1) {
            if (DEBUG) {
                Log.e(TAG, "# Adding time zone from getAvailId: " + tzInfo.toString());
            }
            mTimeZones.add(tzInfo);
        } else {
            if (DEBUG) {
                Log.e(TAG, "# Dropping identical time zone from getAvailId: " + tzInfo.toString());
            }
            continue;
        }
        //
        // TODO check for dups
        // checkForNameDups(tz, tzInfo.mCountry, false /* dls */,
        // TimeZone.SHORT, groupIdx, !found);
        // checkForNameDups(tz, tzInfo.mCountry, false /* dls */,
        // TimeZone.LONG, groupIdx, !found);
        // if (tz.useDaylightTime()) {
        // checkForNameDups(tz, tzInfo.mCountry, true /* dls */,
        // TimeZone.SHORT, groupIdx,
        // !found);
        // checkForNameDups(tz, tzInfo.mCountry, true /* dls */,
        // TimeZone.LONG, groupIdx,
        // !found);
        // }
    }

    // Don't change the order of mTimeZones after this sort
    Collections.sort(mTimeZones);

    mTimeZonesByCountry = new LinkedHashMap<>();
    mTimeZonesByOffsets = new SparseArray<>(mHasTimeZonesInHrOffset.length);
    int N = mTimeZones.size();
    mTimeZonesById = new SimpleArrayMap<>(N);
    for (int i = 0; i < N; i++) {
        TimeZoneInfo tz = mTimeZones.get(i);
        // /////////////////////
        // Lookup map for id -> tz
        mTimeZonesById.put(tz.mTzId, tz);
    }
    populateDisplayNameOverrides(mTimeZonesById, mContext.getResources());

    Date date = new Date(mTimeMillis);
    Locale defaultLocal = Locale.getDefault();

    int idx = 0;
    for (int i = 0; i < N; i++) {
        TimeZoneInfo tz = mTimeZones.get(i);
        // /////////////////////
        // Populate display name
        if (tz.mDisplayName == null) {
            tz.mDisplayName = tz.mTz.getDisplayName(tz.mTz.inDaylightTime(date), TimeZone.LONG, defaultLocal);
        }

        // /////////////////////
        // Grouping tz's by country for search by country
        IntList group = mTimeZonesByCountry.get(tz.mCountry);
        if (group == null) {
            group = new IntList();
            mTimeZonesByCountry.put(tz.mCountry, group);
        }

        group.add(idx);

        // /////////////////////
        // Grouping tz's by GMT offsets
        indexByOffsets(idx, tz);

        // Skip all the GMT+xx:xx style display names from search
        if (!tz.mDisplayName.endsWith(":00")) {
            mTimeZoneNames.add(tz.mDisplayName);
        } else if (DEBUG) {
            Log.e(TAG, "# Hiding from pretty name search: " + tz.mDisplayName);
        }

        idx++;
    }

    // printTimeZones();
}

From source file:com.pdftron.pdf.controls.ReflowPagerAdapter.java

public ReflowPagerAdapter(ViewPager viewPager, PDFDoc doc, Context context) {
    mViewPager = viewPager;//from  w w w. j  a v  a2  s  .c o m
    mDoc = doc;
    mContext = context;
    mRequestHandler = new RequestHandler(this);
    mThemeName = null;
    mPageCount = 0;
    try {
        mPageCount = mDoc.getPageCount();
    } catch (Exception e) {
        e.printStackTrace();
    }
    mReflowFiles = new SparseArray<>(mPageCount);
    mViewHolders = new SparseArray<>(mPageCount);
    mViewIndexes = new SparseArray<>(mPageCount);

    // NOTE: make sure that the off-screen page limit is set to one
    viewPager.setOffscreenPageLimit(1);
    mWebViewRepository = new WebViewRepository(mContext);
}

From source file:android.support.transition.TransitionPort.java

/**
 * This method, essentially a wrapper around all calls to createAnimator for all
 * possible target views, is called with the entire set of start/end
 * values. The implementation in Transition iterates through these lists
 * and calls {@link #createAnimator(ViewGroup, TransitionValues, TransitionValues)}
 * with each set of start/end values on this transition. The
 * TransitionSet subclass overrides this method and delegates it to
 * each of its children in succession.// w  w w .j av  a  2 s  . c  o m
 *
 * @hide
 */
@RestrictTo(GROUP_ID)
protected void createAnimators(ViewGroup sceneRoot, TransitionValuesMaps startValues,
        TransitionValuesMaps endValues) {
    if (DBG) {
        Log.d(LOG_TAG, "createAnimators() for " + this);
    }
    ArrayMap<View, TransitionValues> endCopy = new ArrayMap<>(endValues.viewValues);
    SparseArray<TransitionValues> endIdCopy = new SparseArray<>(endValues.idValues.size());
    for (int i = 0; i < endValues.idValues.size(); ++i) {
        int id = endValues.idValues.keyAt(i);
        endIdCopy.put(id, endValues.idValues.valueAt(i));
    }
    LongSparseArray<TransitionValues> endItemIdCopy = new LongSparseArray<>(endValues.itemIdValues.size());
    for (int i = 0; i < endValues.itemIdValues.size(); ++i) {
        long id = endValues.itemIdValues.keyAt(i);
        endItemIdCopy.put(id, endValues.itemIdValues.valueAt(i));
    }
    // Walk through the start values, playing everything we find
    // Remove from the end set as we go
    ArrayList<TransitionValues> startValuesList = new ArrayList<>();
    ArrayList<TransitionValues> endValuesList = new ArrayList<>();
    for (View view : startValues.viewValues.keySet()) {
        TransitionValues start;
        TransitionValues end = null;
        boolean isInListView = false;
        if (view.getParent() instanceof ListView) {
            isInListView = true;
        }
        if (!isInListView) {
            int id = view.getId();
            start = startValues.viewValues.get(view) != null ? startValues.viewValues.get(view)
                    : startValues.idValues.get(id);
            if (endValues.viewValues.get(view) != null) {
                end = endValues.viewValues.get(view);
                endCopy.remove(view);
            } else if (id != View.NO_ID) {
                end = endValues.idValues.get(id);
                View removeView = null;
                for (View viewToRemove : endCopy.keySet()) {
                    if (viewToRemove.getId() == id) {
                        removeView = viewToRemove;
                    }
                }
                if (removeView != null) {
                    endCopy.remove(removeView);
                }
            }
            endIdCopy.remove(id);
            if (isValidTarget(view, id)) {
                startValuesList.add(start);
                endValuesList.add(end);
            }
        } else {
            ListView parent = (ListView) view.getParent();
            if (parent.getAdapter().hasStableIds()) {
                int position = parent.getPositionForView(view);
                long itemId = parent.getItemIdAtPosition(position);
                start = startValues.itemIdValues.get(itemId);
                endItemIdCopy.remove(itemId);
                // TODO: deal with targetIDs for itemIDs for ListView items
                startValuesList.add(start);
                endValuesList.add(end);
            }
        }
    }
    int startItemIdCopySize = startValues.itemIdValues.size();
    for (int i = 0; i < startItemIdCopySize; ++i) {
        long id = startValues.itemIdValues.keyAt(i);
        if (isValidTarget(null, id)) {
            TransitionValues start = startValues.itemIdValues.get(id);
            TransitionValues end = endValues.itemIdValues.get(id);
            endItemIdCopy.remove(id);
            startValuesList.add(start);
            endValuesList.add(end);
        }
    }
    // Now walk through the remains of the end set
    for (View view : endCopy.keySet()) {
        int id = view.getId();
        if (isValidTarget(view, id)) {
            TransitionValues start = startValues.viewValues.get(view) != null ? startValues.viewValues.get(view)
                    : startValues.idValues.get(id);
            TransitionValues end = endCopy.get(view);
            endIdCopy.remove(id);
            startValuesList.add(start);
            endValuesList.add(end);
        }
    }
    int endIdCopySize = endIdCopy.size();
    for (int i = 0; i < endIdCopySize; ++i) {
        int id = endIdCopy.keyAt(i);
        if (isValidTarget(null, id)) {
            TransitionValues start = startValues.idValues.get(id);
            TransitionValues end = endIdCopy.get(id);
            startValuesList.add(start);
            endValuesList.add(end);
        }
    }
    int endItemIdCopySize = endItemIdCopy.size();
    for (int i = 0; i < endItemIdCopySize; ++i) {
        long id = endItemIdCopy.keyAt(i);
        // TODO: Deal with targetIDs and itemIDs
        TransitionValues start = startValues.itemIdValues.get(id);
        TransitionValues end = endItemIdCopy.get(id);
        startValuesList.add(start);
        endValuesList.add(end);
    }
    ArrayMap<Animator, AnimationInfo> runningAnimators = getRunningAnimators();
    for (int i = 0; i < startValuesList.size(); ++i) {
        TransitionValues start = startValuesList.get(i);
        TransitionValues end = endValuesList.get(i);
        // Only bother trying to animate with values that differ between start/end
        if (start != null || end != null) {
            if (start == null || !start.equals(end)) {
                if (DBG) {
                    View view = (end != null) ? end.view : start.view;
                    Log.d(LOG_TAG, "  differing start/end values for view " + view);
                    if (start == null || end == null) {
                        Log.d(LOG_TAG, "    "
                                + ((start == null) ? "start null, end non-null" : "start non-null, end null"));
                    } else {
                        for (String key : start.values.keySet()) {
                            Object startValue = start.values.get(key);
                            Object endValue = end.values.get(key);
                            if (startValue != endValue && !startValue.equals(endValue)) {
                                Log.d(LOG_TAG,
                                        "    " + key + ": start(" + startValue + "), end(" + endValue + ")");
                            }
                        }
                    }
                }
                // TODO: what to do about targetIds and itemIds?
                Animator animator = createAnimator(sceneRoot, start, end);
                if (animator != null) {
                    // Save animation info for future cancellation purposes
                    View view;
                    TransitionValues infoValues = null;
                    if (end != null) {
                        view = end.view;
                        String[] properties = getTransitionProperties();
                        if (view != null && properties != null && properties.length > 0) {
                            infoValues = new TransitionValues();
                            infoValues.view = view;
                            TransitionValues newValues = endValues.viewValues.get(view);
                            if (newValues != null) {
                                for (int j = 0; j < properties.length; ++j) {
                                    infoValues.values.put(properties[j], newValues.values.get(properties[j]));
                                }
                            }
                            int numExistingAnims = runningAnimators.size();
                            for (int j = 0; j < numExistingAnims; ++j) {
                                Animator anim = runningAnimators.keyAt(j);
                                AnimationInfo info = runningAnimators.get(anim);
                                if (info.values != null && info.view == view
                                        && ((info.name == null && getName() == null)
                                                || info.name.equals(getName()))) {
                                    if (info.values.equals(infoValues)) {
                                        // Favor the old animator
                                        animator = null;
                                        break;
                                    }
                                }
                            }
                        }
                    } else {
                        view = start.view;
                    }
                    if (animator != null) {
                        AnimationInfo info = new AnimationInfo(view, getName(),
                                WindowIdPort.getWindowId(sceneRoot), infoValues);
                        runningAnimators.put(animator, info);
                        mAnimators.add(animator);
                    }
                }
            }
        }
    }
}

From source file:com.pdftron.pdf.controls.ReflowPagerAdapter.java

public void onPagesModified() {
    if (DEBUG)/*ww  w . ja va 2  s  .c o m*/
        Log.d(TAG, "pages were modified.");
    mPageCount = 0;
    try {
        mPageCount = mDoc.getPageCount();
    } catch (Exception e) {
        e.printStackTrace();
    }
    mReflowFiles = new SparseArray<>(mPageCount);
    mViewHolders = new SparseArray<>(mPageCount);
    mViewIndexes = new SparseArray<>(mPageCount);
}

From source file:de.mrapp.android.util.view.AbstractViewRecycler.java

/**
 * Adds an unused view to the cache.//w  w  w.  j  a  va  2s.com
 *
 * @param view
 *         The unused view, which should be added to the cache, as an instance of the class
 *         {@link View}. The view may not be null
 * @param viewType
 *         The view type, the unused view corresponds to, as an {@link Integer} value
 */
protected final void addUnusedView(@NonNull final View view, final int viewType) {
    if (useCache) {
        if (unusedViews == null) {
            unusedViews = new SparseArray<>(adapter.getViewTypeCount());
        }

        Queue<View> queue = unusedViews.get(viewType);

        if (queue == null) {
            queue = new LinkedList<>();
            unusedViews.put(viewType, queue);
        }

        queue.add(view);
    }
}

From source file:com.android.mail.ui.AnimatedAdapter.java

public AnimatedAdapter(Context context, ConversationCursor cursor, ConversationCheckedSet batch,
        ControllableActivity activity, SwipeableListView listView,
        final List<ConversationSpecialItemView> specialViews) {
    super(context, -1, cursor, UIProvider.CONVERSATION_PROJECTION, null, 0);
    mContext = context;/*w  w w  . j a  va 2 s .  com*/
    mBatchConversations = batch;
    setAccount(mAccountListener.initialize(activity.getAccountController()));
    mActivity = activity;
    mDefaultFooter = (Space) LayoutInflater.from(context).inflate(R.layout.conversation_list_default_footer,
            listView, false);
    mShowCustomFooter = false;
    mListView = listView;

    mSendersImagesCache = mActivity.getSenderImageCache();

    mContactResolver = mActivity.getContactResolver(mContext.getContentResolver(), mSendersImagesCache);

    mHandler = new Handler();
    if (sDismissAllShortDelay == -1) {
        final Resources r = context.getResources();
        sDismissAllShortDelay = r.getInteger(R.integer.dismiss_all_leavebehinds_short_delay);
        sDismissAllLongDelay = r.getInteger(R.integer.dismiss_all_leavebehinds_long_delay);
    }
    if (specialViews != null) {
        mFleetingViews = new ArrayList<ConversationSpecialItemView>(specialViews);
    } else {
        mFleetingViews = new ArrayList<ConversationSpecialItemView>(0);
    }
    /** Total number of special views */
    final int size = mFleetingViews.size();
    mSpecialViews = new SparseArray<ConversationSpecialItemView>(size);

    // Set the adapter in teaser views.
    for (final ConversationSpecialItemView view : mFleetingViews) {
        view.setAdapter(this);
    }
    updateSpecialViews();
}