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() 

Source Link

Document

Creates a new SparseArray containing no mappings.

Usage

From source file:com.facebook.litho.ComponentsPools.java

static Object acquireMountContent(Context context, int componentId, boolean allocatePool) {
    if (context instanceof ComponentContext) {
        context = ((ComponentContext) context).getBaseContext();

        if (context instanceof ComponentContext) {
            throw new IllegalStateException("Double wrapped ComponentContext.");
        }/*w w  w  .jav a  2  s.c o m*/
    }

    final RecyclePool<Object> pool;

    synchronized (mountContentLock) {

        if (allocatePool) {
            if (sActivityCallbacks == null && !sIsManualCallbacks) {
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                    throw new RuntimeException(
                            "Activity callbacks must be invoked manually below ICS (API level 14)");
                }
                sActivityCallbacks = new PoolsActivityCallback();
                ((Application) context.getApplicationContext())
                        .registerActivityLifecycleCallbacks(sActivityCallbacks);
            }
        }

        SparseArray<RecyclePool> poolsArray = sMountContentPoolsByContext.get(context);

        if (poolsArray == null) {
            if (allocatePool) {
                // The context is created here because we are sure the Activity is alive at this point in
                // contrast of the release call where the Activity might by gone.
                sMountContentPoolsByContext.put(context, new SparseArray<RecyclePool>());
            }
            return null;
        }

        pool = poolsArray.get(componentId);
        if (pool == null) {
            return null;
        }
    }

    return pool.acquire();
}

From source file:com.sonymobile.androidapp.gridcomputing.fragments.ReportChartFragment.java

/**
 * Groups the original values into a sparse array.
 * The outer sparse array is indexed by the group field.
 * The inner sparse array is indexed by the index field.
 * If groupField and indexField are the same, then the outer sparse array contains only 1 entry
 * index by 0 and the inner sparse array is indexed by indexField.
 * @param original the original value returned from the SQL query.
 * @param groupField the field used to group the outer sparse array.
 * @param indexField the field used to group the inner sparse array.
 * @return a bidimensional sparse array indexed by  groupField and indexField.
 *///from   ww w .  j  a  v  a 2  s  .c  om
private SparseArray<SparseArray<Double>> groupValues(final SparseArray<Pair<Date, Double>> original,
        final int groupField, final int indexField) {
    final Calendar calendar = Calendar.getInstance();
    final SparseArray<SparseArray<Double>> weeks = new SparseArray<>();

    for (int i = 0; i < original.size(); i++) {
        try {
            final int key = original.keyAt(i);

            calendar.setTime(original.get(key).first);
            final double value = original.get(key).second;

            final int indexValue = calendar.get(indexField);
            final int groupValue = groupField == indexField ? 0 : calendar.get(groupField);

            SparseArray<Double> currentWeek = weeks.get(groupValue);
            if (currentWeek == null) {
                currentWeek = new SparseArray<>();
                weeks.put(groupValue, currentWeek);
            }
            currentWeek.put(indexValue, value);
        } catch (Exception e) {
            Log.e(e.getMessage());
        }
    }

    // normalize the data
    // if the index field is DAY_OF_WEEK, then we'll add the remaining days to fill
    // the week from sunday until saturday
    if (indexField == Calendar.DAY_OF_WEEK) {
        for (int i = 0; i < weeks.size(); i++) {
            final int key = weeks.keyAt(i);
            SparseArray<Double> currentWeek = weeks.get(key);
            for (int j = Calendar.SUNDAY; j <= Calendar.SATURDAY; j++) {
                if (currentWeek.get(j) == null) {
                    currentWeek.put(j, 0.0);
                }
            }
        }
    }

    return weeks;
}

From source file:com.android.mail.browse.ConversationContainer.java

public ConversationContainer(Context c, AttributeSet attrs) {
    super(c, attrs);

    mOverlayViews = new SparseArray<OverlayView>();

    mVelocityTracker = new InputSmoother(c);

    mTouchSlop = ViewConfiguration.get(c).getScaledTouchSlop();

    // Disabling event splitting fixes pinch-zoom when the first pointer goes down on the
    // WebView and the second pointer goes down on an overlay view.
    // Intercepting ACTION_POINTER_DOWN events allows pinch-zoom to work when the first pointer
    // goes down on an overlay view.
    setMotionEventSplittingEnabled(false);
}

From source file:com.nttec.everychan.ui.gallery.GalleryActivity.java

@Override
protected void onCreate(final Bundle savedInstanceState) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)
        requestWindowFeature(Window.FEATURE_PROGRESS);
    settings = getIntent().getParcelableExtra(EXTRA_SETTINGS);
    if (settings == null)
        settings = GallerySettings.fromSettings(new ApplicationSettings(
                PreferenceManager.getDefaultSharedPreferences(getApplication()), getResources()));
    settings.getTheme().setTo(this, R.style.Transparent);
    super.onCreate(savedInstanceState);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
        CompatibilityImpl.setActionBarNoIcon(this);

    inflater = getLayoutInflater();/*  w w  w . j a v  a  2 s .com*/
    instantiatedViews = new SparseArray<View>();
    tnDownloadingExecutor = Executors.newFixedThreadPool(4, Async.LOW_PRIORITY_FACTORY);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH && settings.fullscreenGallery()) {
        setContentView(R.layout.gallery_layout_fullscreen);
        GalleryFullscreen.initFullscreen(this);
    } else {
        setContentView(R.layout.gallery_layout);
    }

    progressBar = (ProgressBar) findViewById(android.R.id.progress);
    progressBar.setMax(Window.PROGRESS_END);
    viewPager = (ViewPager) findViewById(R.id.gallery_viewpager);
    navigationInfo = (TextView) findViewById(R.id.gallery_navigation_info);
    for (int id : new int[] { R.id.gallery_navigation_previous, R.id.gallery_navigation_next })
        findViewById(id).setOnClickListener(this);

    bindService(new Intent(this, GalleryBackend.class), new ServiceConnection() {
        {
            serviceConnection = this;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            GalleryBinder galleryBinder = GalleryBinder.Stub.asInterface(service);
            try {
                GalleryInitData initData = new GalleryInitData(getIntent(), savedInstanceState);
                boardModel = initData.boardModel;
                chan = boardModel.chan;
                remote = new GalleryRemote(galleryBinder, galleryBinder.initContext(initData));
                GalleryInitResult initResult = remote.getInitResult();
                if (initResult != null) {
                    attachments = initResult.attachments;
                    currentPosition = initResult.initPosition;
                    if (initResult.shouldWaitForPageLoaded)
                        waitForPageLoaded(savedInstanceState);
                } else {
                    attachments = Collections.singletonList(
                            Triple.of(initData.attachment, initData.attachmentHash, (String) null));
                    currentPosition = 0;
                }

                viewPager.setAdapter(new GalleryAdapter());
                viewPager.setCurrentItem(currentPosition);
                viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
                    @Override
                    public void onPageSelected(int position) {
                        currentPosition = position;
                        updateItem();
                    }
                });
            } catch (Exception e) {
                Logger.e(TAG, e);
                finish();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Logger.e(TAG, "backend service disconnected");
            remote = null;
            System.exit(0);
        }
    }, BINDING_FLAGS);

    GalleryExceptionHandler.init();
}

From source file:com.github.paradam.support.v4.infinitepager.InfiniteFragmentStatePagerAdapter.java

@Override
public void notifyDataSetChanged() {
    onPreNotifyDataSetChange();//from   w ww.  jav a 2s.c o  m
    final int count = getRelativeCount();
    final int margin = getMargin();

    ArrayList<Fragment.SavedState> newSavedState = new ArrayList<Fragment.SavedState>(count);
    ArrayList<Fragment> newFragments = new ArrayList<Fragment>(count);
    SparseArray<Fragment> newDestroyedFragments = new SparseArray<Fragment>();

    int length = mFragments.size();

    for (int x = 0; x < length; x++) {
        Fragment fragment = mFragments.get(x);
        boolean fromDestroyed = false;
        if (fragment == null) {
            // Check if there is a destroyed fragment that was in the list, use that if there is.
            fragment = mDestroyedFragments.get(x);
            fromDestroyed = true;
        }
        int position = getItemPosition(fragment);
        switch (position) {
        case POSITION_UNCHANGED:
            while (newFragments.size() < x + 1) {
                newFragments.add(null);
                newSavedState.add(null);
            }
            if (!fromDestroyed) {
                newFragments.set(x, mFragments.get(x));
            } else {
                newDestroyedFragments.put(x, fragment);
            }
            if (mSavedState.size() > x) {
                newSavedState.set(x, mSavedState.get(x));
            }
            break;
        case POSITION_NONE:
            // Do not add fragment.
            if (!fromDestroyed) {
                if (mCurTransaction == null) {
                    mCurTransaction = mFragmentManager.beginTransaction();
                }
                mCurTransaction.remove(mFragments.get(x));
            }
            break;
        default:
            position = (position - margin + count) % count;
            while (newFragments.size() < position + 1) {
                newFragments.add(null);
                newSavedState.add(null);
            }
            if (!fromDestroyed) {
                newFragments.set(position, fragment);
            } else {
                newDestroyedFragments.put(position, fragment);
            }
            if (mSavedState.size() > x) {
                newSavedState.set(position, mSavedState.get(x));
            }
        }
    }

    mSavedState = newSavedState;
    mFragments = newFragments;
    mDestroyedFragments = newDestroyedFragments;

    super.notifyDataSetChanged();
}

From source file:dev.drsoran.moloko.activities.AbstractTasksListActivity.java

private void initializeListNavigation() {
    getSupportFragmentManager().addOnBackStackChangedListener(this);

    final boolean isFirstInitialization = selectedNavigationItem == null;
    if (isFirstInitialization) {
        selectedNavigationItem = new SelectedNavigationItem();
        setSelectedNavigationItemIdFromIntent();
        setSelectedNavigationItemPositionFromSubTitle();

        backStackNavigationItems = new SparseArray<SelectedNavigationItem>();

        // The initial fragment gets the back stack ID -1 because it was added
        // without back stack.
        backStackNavigationItems.append(INITIAL_FRAGMENT_BACK_STACK_ID, selectedNavigationItem);
    }/*from ww w  .  ja va 2  s  . co  m*/

    setNavigationAdapter();
}

From source file:com.oxplot.contactphotosync.AssignContactPhotoActivity.java

@Override
public void onCreate(Bundle savedState) {
    super.onCreate(savedState);

    thumbSize = getResources().getInteger(R.integer.config_list_thumb_size);

    if (savedState != null) {
        String cropTempPath = savedState.getString("crop_temp");
        if (cropTempPath != null)
            cropTemp = new File(cropTempPath);
        pickedRawContact = savedState.getInt("picked_raw_contact", 0);
    }//  w w w . ja  v  a2  s  .  c  o  m

    // Initialize cache directory

    new File(getCacheDir(), DISK_CACHE_DIR).mkdir();

    unchangedThumb = new BitmapDrawable(getResources(), Bitmap.createBitmap(1, 1, Config.ALPHA_8));

    setContentView(R.layout.activity_assign_contact_photo);
    contactList = (ListView) findViewById(R.id.contactList);
    emptyList = (TextView) findViewById(R.id.empty);
    loadingProgress = (ProgressBar) findViewById(R.id.loading);

    contactList.setEmptyView(loadingProgress);
    contactList.setAdapter(new ContactAdapter());
    contactList.setDividerHeight(1);
    contactList.setMultiChoiceModeListener(new ContactListMultiChoiceModeListener());
    contactList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);

    getActionBar().setDisplayHomeAsUpEnabled(true);
    account = getIntent().getStringExtra("account");
    setTitle(account);

    thumbMemCache = new SparseArray<Drawable>();
    asyncTasks = new HashSet<AsyncTask<?, ?, ?>>();
    defaultThumb = getResources().getDrawable(R.drawable.new_picture);

    contactList.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {

            pickedRawContact = ((Contact) contactList.getItemAtPosition(position)).rawContactId;
            Intent intent = new Intent();

            // We only really accept PNG and JPEG but the activities registered for
            // the intended action only accept the generic form of the mime type. We
            // will check for our constraints after the image is picked.

            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(
                    Intent.createChooser(intent, getResources().getString(R.string.select_picture)),
                    REQ_CODE_PICK_IMAGE);

        }
    });

}

From source file:com.abid_mujtaba.fetchheaders.models.Account.java

public SparseArray<Email> fetchEmails() throws MessagingException // Fetches messages from account and uses them to create an array of Email objects. Catches connection exception and re-throws them up the chain.
{
    Properties props = new Properties();

    props.setProperty("mail.store.protocol", "imaps");
    props.setProperty("mail.imaps.host", mHost);
    props.setProperty("mail.imaps.port", "993");
    props.setProperty("mail.imaps.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); // Uses SSL to secure communication
    props.setProperty("mail.imaps.socketFactory.fallback", "false");

    Session imapSession = Session.getInstance(props);

    try {/*from w  w w.j a va  2s .  com*/
        Store store = imapSession.getStore("imaps");

        // Connect to server by sending username and password:
        store.connect(mHost, mUsername, mPassword);

        mInbox = store.getFolder("Inbox");
        mInbox.open(Folder.READ_WRITE); // Open Inbox as read-write since we will be deleting emails later

        mTrash = store.getFolder("Trash");

        if (!mTrash.exists()) {
            mTrash = store.getFolder("[Gmail]/Trash"); // If a folder labelled "Trash" doesn't exist we attempt to check if it is a Gmail account whose trash folder is differently named
            mUsesLabels = true; // Set flag to indicate that this account uses Labels rather than folders a la Gmail

            if (!mTrash.exists()) {
                mTrash = null; // No trash folder found. Emails will be deleted directly
                mUsesLabels = false;
            }
        }

        int num = mInbox.getMessageCount(); // Get number of messages in the Inbox

        if (num > mMaxNumOfEmails) {
            mMessages = mInbox.getMessages(num - mMaxNumOfEmails + 1, num); // Fetch latest mMaxNumOfEmails emails (seen and unseen both). The oldest email is indexed as 1 and so on.
        } else {
            mMessages = mInbox.getMessages();
        }

        FetchProfile fp = new FetchProfile();
        fp.add(IMAPFolder.FetchProfileItem.HEADERS); // Fetch header data
        fp.add(FetchProfile.Item.FLAGS); // Fetch flags

        mInbox.fetch(mMessages, fp);

        // Now that the messages have been fetched using the FetchProfile (that is the necessary information has been fetched with them) we sort the message in reverse chronological order

        Arrays.sort(mMessages, new MessageComparator()); // The sort is accomplished using an instance of a custom comparator that compares messages using DateSent

        mEmails = new SparseArray<Email>();

        for (int ii = 0; ii < mMessages.length; ii++) {
            Email email = new Email(mMessages[ii]);

            mEmails.put(ii, email);
        }

        return mEmails;
    } catch (MessagingException e) {
        Resources.Loge("Exception while attempting to connect to mail server", e);
        throw e;
    } // The two above exceptions are caught by this one if they are not explicitly stated above.
}

From source file:com.bmd.android.collection.SparseArrayCompatTest.java

public void testEquals() {

    final SparseArray<String> array = new SparseArray<String>();

    for (int i = 0; i < 5; i++) {

        array.append(i, String.valueOf(i));
    }//from   w  ww. ja  va 2 s  . c  o  m

    assertThat(AndroidCollections.iterate(mArray).isStrictlyEqualTo(AndroidCollections.iterate(array)))
            .isTrue();
    assertThat(AndroidCollections.iterate(array).isStrictlyEqualTo(AndroidCollections.iterate(mArray)))
            .isTrue();
    assertThat(AndroidCollections.iterate(array).only().key(2).remove()
            .isStrictlyEqualTo(AndroidCollections.iterate(mArray))).isFalse();
    assertThat(AndroidCollections.iterate(mArray).isStrictlyEqualTo(AndroidCollections.iterate(array)))
            .isFalse();

    final SparseArrayCompat<String> sparseArray = AndroidCollections.iterate(mArray).toSparseArray();
    assertThat(AndroidCollections.iterate(mArray).isEqualTo(mArray)).isTrue();
    assertThat(AndroidCollections.iterate(mArray).only().first(2).isEqualTo(mArray)).isFalse();
    assertThat(AndroidCollections.iterate(mArray).isEqualTo(sparseArray)).isTrue();
    assertThat(AndroidCollections.iterate(mArray).only().first(2).isEqualTo(sparseArray)).isFalse();

    final ArrayList<IntSparseObjectEntry<String>> list = AndroidCollections.iterate(mArray).toImmutableList();
    assertThat(AndroidCollections.iterate(mArray).isEqualTo(list)).isTrue();
    assertThat(AndroidCollections.iterate(mArray).only().first(2).isEqualTo(list)).isFalse();

    final ArrayList<ParcelableIntSparseObjectEntry<String>> parcelableList = AndroidCollections.iterate(mArray)
            .toParcelableList();
    assertThat(AndroidCollections.iterate(mArray).isEqualTo(parcelableList)).isTrue();
    assertThat(AndroidCollections.iterate(mArray).only().first(2).isEqualTo(parcelableList)).isFalse();

    final Map<Integer, String> map = AndroidCollections.iterate(mArray).toMap();
    assertThat(AndroidCollections.iterate(mArray).isEqualTo(map)).isTrue();
    assertThat(AndroidCollections.iterate(mArray).only().first(2).isEqualTo(map)).isFalse();

    final SortedMap<Integer, String> sortedMap = AndroidCollections.iterate(mArray).toSortedMap();
    assertThat(AndroidCollections.iterate(mArray).isEqualTo(sortedMap)).isTrue();
    assertThat(AndroidCollections.iterate(mArray).only().first(2).isEqualTo(sortedMap)).isFalse();

    mArray.append(7, "7");
    assertThat(AndroidCollections.iterate(mArray).isEqualTo(sparseArray)).isFalse();
    assertThat(AndroidCollections.iterate(mArray).but().last(1).isEqualTo(sparseArray)).isTrue();
    assertThat(AndroidCollections.iterate(mArray).isEqualTo(list)).isFalse();
    assertThat(AndroidCollections.iterate(mArray).but().last(1).isEqualTo(list)).isTrue();
    assertThat(AndroidCollections.iterate(mArray).isEqualTo(parcelableList)).isFalse();
    assertThat(AndroidCollections.iterate(mArray).but().last(1).isEqualTo(parcelableList)).isTrue();
    assertThat(AndroidCollections.iterate(mArray).isEqualTo(map)).isFalse();
    assertThat(AndroidCollections.iterate(mArray).but().last(1).isEqualTo(map)).isTrue();
    assertThat(AndroidCollections.iterate(mArray).isEqualTo(sortedMap)).isFalse();
    assertThat(AndroidCollections.iterate(mArray).but().last(1).isEqualTo(sortedMap)).isTrue();
}

From source file:com.actionbarsherlock.internal.view.menu.MenuBuilder.java

private void dispatchSaveInstanceState(Bundle outState) {
    if (mPresenters.isEmpty())
        return;/*from  w  w w. jav  a2s  .  co m*/

    SparseArray<Parcelable> presenterStates = new SparseArray<Parcelable>();

    for (WeakReference<MenuPresenter> ref : mPresenters) {
        final MenuPresenter presenter = ref.get();
        if (presenter == null) {
            mPresenters.remove(ref);
        } else {
            final int id = presenter.getId();
            if (id > 0) {
                final Parcelable state = presenter.onSaveInstanceState();
                if (state != null) {
                    presenterStates.put(id, state);
                }
            }
        }
    }

    outState.putSparseParcelableArray(PRESENTER_KEY, presenterStates);
}