Example usage for android.content Intent getStringArrayExtra

List of usage examples for android.content Intent getStringArrayExtra

Introduction

In this page you can find the example usage for android.content Intent getStringArrayExtra.

Prototype

public String[] getStringArrayExtra(String name) 

Source Link

Document

Retrieve extended data from the intent.

Usage

From source file:com.owncloud.android.ui.activity.FileDisplayActivity.java

private void requestMultipleUpload(Intent data, int resultCode) {
    String[] filePaths = data.getStringArrayExtra(UploadFilesActivity.EXTRA_CHOSEN_FILES);
    if (filePaths != null) {
        String[] remotePaths = new String[filePaths.length];
        String remotePathBase = "";
        for (int j = mDirectories.getCount() - 2; j >= 0; --j) {
            remotePathBase += OCFile.PATH_SEPARATOR + mDirectories.getItem(j);
        }/*from w ww .  j a v  a  2 s .c  o m*/
        if (!remotePathBase.endsWith(OCFile.PATH_SEPARATOR))
            remotePathBase += OCFile.PATH_SEPARATOR;
        for (int j = 0; j < remotePaths.length; j++) {
            remotePaths[j] = remotePathBase + (new File(filePaths[j])).getName();
        }

        Intent i = new Intent(this, FileUploader.class);
        i.putExtra(FileUploader.KEY_ACCOUNT, getAccount());
        i.putExtra(FileUploader.KEY_LOCAL_FILE, filePaths);
        i.putExtra(FileUploader.KEY_REMOTE_FILE, remotePaths);
        i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_MULTIPLE_FILES);
        if (resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)
            i.putExtra(FileUploader.KEY_LOCAL_BEHAVIOUR, FileUploader.LOCAL_BEHAVIOUR_MOVE);
        startService(i);

    } else {
        Log_OC.d(TAG, "User clicked on 'Update' with no selection");
        Toast t = Toast.makeText(this, getString(R.string.filedisplay_no_file_selected), Toast.LENGTH_LONG);
        t.show();
        return;
    }
}

From source file:com.cerema.cloud2.ui.activity.FileDisplayActivity.java

private void requestMultipleUpload(Intent data, int resultCode) {
    String[] filePaths = data.getStringArrayExtra(UploadFilesActivity.EXTRA_CHOSEN_FILES);
    if (filePaths != null) {
        String[] remotePaths = new String[filePaths.length];
        String remotePathBase = getCurrentDir().getRemotePath();
        for (int j = 0; j < remotePaths.length; j++) {
            remotePaths[j] = remotePathBase + (new File(filePaths[j])).getName();
        }//from  www. j a va  2s. c  o  m

        Intent i = new Intent(this, FileUploader.class);
        i.putExtra(FileUploader.KEY_ACCOUNT, getAccount());
        i.putExtra(FileUploader.KEY_LOCAL_FILE, filePaths);
        i.putExtra(FileUploader.KEY_REMOTE_FILE, remotePaths);
        i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_MULTIPLE_FILES);
        if (resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)
            i.putExtra(FileUploader.KEY_LOCAL_BEHAVIOUR, FileUploader.LOCAL_BEHAVIOUR_MOVE);
        startService(i);

    } else {
        Log_OC.d(TAG, "User clicked on 'Update' with no selection");
        Toast t = Toast.makeText(this, getString(R.string.filedisplay_no_file_selected), Toast.LENGTH_LONG);
        t.show();
        return;
    }
}

From source file:com.gcm.client.RegistrationIntentService.java

@Override
protected void onHandleIntent(Intent intent) {
    try {/* www  .  ja v a2  s . co  m*/
        if (null != intent) {
            String action = intent.getAction();
            String senderId = GcmHelper.getInstance().getAuthorizedEntity();

            InstanceID instanceID = InstanceID.getInstance(this);
            if (ACTION_REGISTER.equals(action)) {
                String token = registerForToken(instanceID, senderId);
                //subscribe topics
                ArrayList<String> topics = GcmHelper.getInstance().getSubscribedTopics();
                if (null != topics && topics.isEmpty()) {
                    String[] stringArray = new String[topics.size()];
                    // Subscribe to topic channels
                    subscribeTopics(token, topics.toArray(stringArray));
                }
                // Notify UI that registration has completed, so the progress indicator can be hidden.
                Intent registrationComplete = new Intent(REGISTRATION_COMPLETE);
                LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
                if (GcmHelper.DEBUG_ENABLED)
                    Log.d(GcmHelper.TAG, "RegistrationIntentService: registration completed");
                return;
            } else if (ACTION_UNREGISTER.equals(action)) {
                unRegisterToken(instanceID, senderId);
                if (GcmHelper.DEBUG_ENABLED)
                    Log.d(GcmHelper.TAG, "RegistrationIntentService: successfully unregistered");
                return;
            }
            if (intent.hasExtra(EXTRA_TOPIC_LIST)) {
                final String topics[] = intent.getStringArrayExtra(EXTRA_TOPIC_LIST);
                String pushToken = GcmHelper.getInstance().getPushToken(getApplicationContext());
                if (TextUtils.isEmpty(pushToken)) {
                    return;
                }
                if (ACTION_UNSUBSCRIBE.equals(action)) {
                    unsubscribeTopics(pushToken, topics);
                    if (GcmHelper.DEBUG_ENABLED)
                        Log.d(GcmHelper.TAG, "RegistrationIntentService: unsubscribe completed");
                } else if (ACTION_SUBSCRIBE.equals(action)) {
                    subscribeTopics(pushToken, topics);
                    if (GcmHelper.DEBUG_ENABLED)
                        Log.d(GcmHelper.TAG, "RegistrationIntentService: subscription completed");
                }
            }
        }
    } catch (Exception e) {
        if (GcmHelper.DEBUG_ENABLED)
            Log.e(GcmHelper.TAG, "PushRegistrationService: Failed to complete token refresh", e);
    }
}

From source file:org.transdroid.core.gui.TorrentsActivity.java

/**
 * If required, add torrents from the supplied intent extras.
 *///from w w w . j a va 2s  .  c  o m
protected void addFromIntent() {
    Intent intent = getIntent();
    Uri dataUri = intent.getData();
    String data = intent.getDataString();
    String action = intent.getAction();

    // Adding multiple torrents at the same time (as found in the Intent extras Bundle)
    if (action != null && action.equals("org.transdroid.ADD_MULTIPLE")) {
        // Intent should have some extras pointing to possibly multiple torrents
        String[] urls = intent.getStringArrayExtra("TORRENT_URLS");
        String[] titles = intent.getStringArrayExtra("TORRENT_TITLES");
        if (urls != null) {
            for (int i = 0; i < urls.length; i++) {
                String title = (titles != null && titles.length >= i ? titles[i]
                        : NavigationHelper.extractNameFromUri(Uri.parse(urls[i])));
                if (intent.hasExtra("PRIVATE_SOURCE")) {
                    // This is marked by the Search Module as being a private source site; get the url locally first
                    addTorrentFromPrivateSource(urls[i], title, intent.getStringExtra("PRIVATE_SOURCE"));
                } else {
                    addTorrentByUrl(urls[i], title);
                }
            }
        }
        return;
    }

    // Add a torrent from a local or remote data URI?
    if (dataUri == null) {
        return;
    }
    if (dataUri.getScheme() == null) {
        SnackbarManager
                .show(Snackbar.with(this).text(R.string.error_invalid_url_form).colorResource(R.color.red));
        return;
    }

    // Get torrent title
    String title = NavigationHelper.extractNameFromUri(dataUri);
    if (intent.hasExtra("TORRENT_TITLE")) {
        title = intent.getStringExtra("TORRENT_TITLE");
    }

    // Adding a torrent from the Android downloads manager
    if (dataUri.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
        addTorrentFromDownloads(dataUri, title);
        return;
    }

    // Adding a torrent from http or https URL
    if (dataUri.getScheme().equals("http") || dataUri.getScheme().equals("https")) {

        String privateSource = getIntent().getStringExtra("PRIVATE_SOURCE");

        WebsearchSetting match = null;
        if (privateSource == null) {
            // Check if the target URL is also defined as a web search in the user's settings
            List<WebsearchSetting> websearches = applicationSettings.getWebsearchSettings();
            for (WebsearchSetting setting : websearches) {
                Uri uri = Uri.parse(setting.getBaseUrl());
                if (uri.getHost() != null && uri.getHost().equals(dataUri.getHost())) {
                    match = setting;
                    break;
                }
            }
        }

        // If the URL is also a web search and it defines cookies, use the cookies by downloading the targeted
        // torrent file (while supplies the cookies to the HTTP request) instead of sending the URL directly to the
        // torrent client. If instead it is marked (by the Torrent Search module) as being form a private site, use
        // the Search Module instead to download the url locally first.
        if (match != null && match.getCookies() != null) {
            addTorrentFromWeb(data, match, title);
        } else if (privateSource != null) {
            addTorrentFromPrivateSource(data, title, privateSource);
        } else {
            // Normally send the URL to the torrent client
            addTorrentByUrl(data, title);
        }
        return;
    }

    // Adding a torrent from magnet URL
    if (dataUri.getScheme().equals("magnet")) {
        addTorrentByMagnetUrl(data, title);
        return;
    }

    // Adding a local .torrent file; the title we show is just the file name
    if (dataUri.getScheme().equals("file")) {
        addTorrentByFile(data, title);
    }

}

From source file:com.google.android.exoplayer2.demo.MediaPlayerFragment.java

private void initializePlayer() {
    Intent intent = fragActivity.getIntent();
    boolean needNewPlayer = player == null;
    if (needNewPlayer) {
        boolean preferExtensionDecoders = intent.getBooleanExtra(PREFER_EXTENSION_DECODERS, false);
        UUID drmSchemeUuid = intent.hasExtra(DRM_SCHEME_UUID_EXTRA)
                ? UUID.fromString(intent.getStringExtra(DRM_SCHEME_UUID_EXTRA))
                : null;//from w ww. j  a  v a  2  s .co  m
        DrmSessionManager<FrameworkMediaCrypto> drmSessionManager = null;
        if (drmSchemeUuid != null) {
            String drmLicenseUrl = intent.getStringExtra(DRM_LICENSE_URL);
            String[] keyRequestPropertiesArray = intent.getStringArrayExtra(DRM_KEY_REQUEST_PROPERTIES);
            try {
                drmSessionManager = buildDrmSessionManager(drmSchemeUuid, drmLicenseUrl,
                        keyRequestPropertiesArray);
            } catch (UnsupportedDrmException e) {
                int errorStringId = Util.SDK_INT < 18 ? R.string.error_drm_not_supported
                        : (e.reason == UnsupportedDrmException.REASON_UNSUPPORTED_SCHEME
                                ? R.string.error_drm_unsupported_scheme
                                : R.string.error_drm_unknown);
                showToast(errorStringId);
                return;
            }
        }

        @SimpleExoPlayer.ExtensionRendererMode
        int extensionRendererMode = ((ExplorerApplication) fragActivity.getApplication())
                .useExtensionRenderers()
                        ? (preferExtensionDecoders ? SimpleExoPlayer.EXTENSION_RENDERER_MODE_PREFER
                                : SimpleExoPlayer.EXTENSION_RENDERER_MODE_ON)
                        : SimpleExoPlayer.EXTENSION_RENDERER_MODE_OFF;
        TrackSelection.Factory videoTrackSelectionFactory = new AdaptiveTrackSelection.Factory(BANDWIDTH_METER);
        trackSelector = new DefaultTrackSelector(videoTrackSelectionFactory);
        trackSelectionHelper = new TrackSelectionHelper(trackSelector, videoTrackSelectionFactory);
        player = ExoPlayerFactory.newSimpleInstance(fragActivity, trackSelector, new DefaultLoadControl(),
                drmSessionManager, extensionRendererMode);
        player.addListener(this);

        eventLogger = new EventLogger(trackSelector);
        player.addListener(eventLogger);
        player.setAudioDebugListener(eventLogger);
        player.setVideoDebugListener(eventLogger);
        player.setMetadataOutput(eventLogger);

        simpleExoPlayerView.setPlayer(player);
        player.setPlayWhenReady(shouldAutoPlay);
        debugViewHelper = new DebugTextViewHelper(player, debugTextView);
        debugViewHelper.start();
    }
    if (needNewPlayer || needRetrySource) {
        String action = intent.getAction();
        Uri[] uris;
        String[] extensions;
        if (Intent.ACTION_VIEW.equals(action)) {
            uris = new Uri[] { intent.getData() };
            extensions = new String[] { intent.getStringExtra(EXTENSION_EXTRA) };
        } else if (ACTION_VIEW.equals(action)) {
            uris = new Uri[] { intent.getData() };
            extensions = new String[] { intent.getStringExtra(EXTENSION_EXTRA) };
        } else if (ACTION_VIEW_LIST.equals(action)) {
            String[] uriStrings = intent.getStringArrayExtra(URI_LIST_EXTRA);
            uris = new Uri[uriStrings.length];
            for (int i = 0; i < uriStrings.length; i++) {
                uris[i] = Uri.parse(uriStrings[i]);
            }
            extensions = intent.getStringArrayExtra(EXTENSION_LIST_EXTRA);
            if (extensions == null) {
                extensions = new String[uriStrings.length];
            }
        } else {
            if (!Intent.ACTION_MAIN.equals(action)) {
                showToast(getString(R.string.unexpected_intent_action, action));
            }
            return;
        }
        if (Util.maybeRequestReadExternalStoragePermission(fragActivity, uris)) {
            // The player will be reinitialized if the permission is granted.
            return;
        }
        MediaSource[] mediaSources = new MediaSource[uris.length];
        for (int i = 0; i < uris.length; i++) {
            mediaSources[i] = buildMediaSource(uris[i], extensions[i]);
        }
        MediaSource mediaSource = mediaSources.length == 1 ? mediaSources[0]
                : new ConcatenatingMediaSource(mediaSources);
        boolean haveResumePosition = resumeWindow != C.INDEX_UNSET;
        if (haveResumePosition) {
            player.seekTo(resumeWindow, resumePosition);
        }
        player.prepare(mediaSource, !haveResumePosition, false);
        needRetrySource = false;
        updateButtonVisibilities();
    }
}

From source file:im.neon.services.EventStreamService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (null == intent) {
        Log.e(LOG_TAG, "onStartCommand : null intent");

        if (null != mActiveEventStreamService) {
            Log.e(LOG_TAG, "onStartCommand : null intent with an active events stream service");
        } else {//from   w w w.  j ava  2  s  .  c  om
            Log.e(LOG_TAG, "onStartCommand : null intent with no events stream service");
        }

        return START_NOT_STICKY;
    }

    StreamAction action = StreamAction.values()[intent.getIntExtra(EXTRA_STREAM_ACTION,
            StreamAction.IDLE.ordinal())];

    Log.d(LOG_TAG, "onStartCommand with action : " + action);

    if (intent.hasExtra(EXTRA_MATRIX_IDS)) {
        if (null == mMatrixIds) {
            mMatrixIds = new ArrayList<>(Arrays.asList(intent.getStringArrayExtra(EXTRA_MATRIX_IDS)));

            mSessions = new ArrayList<>();

            for (String matrixId : mMatrixIds) {
                mSessions.add(Matrix.getInstance(getApplicationContext()).getSession(matrixId));
            }

            Log.d(LOG_TAG, "onStartCommand : update the matrix ids list to " + mMatrixIds);
        }
    }

    switch (action) {
    case START:
    case RESUME:
        start();
        break;
    case STOP:
        Log.d(LOG_TAG, "## onStartCommand(): service stopped");
        stopSelf();
        break;
    case PAUSE:
        pause();
        break;
    case CATCHUP:
        catchup(true);
        break;
    case GCM_STATUS_UPDATE:
        gcmStatusUpdate();
    default:
        break;
    }

    return START_STICKY;
}

From source file:com.geecko.QuickLyric.MainActivity.java

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    String action = intent.getAction();
    String extra = intent.getStringExtra(Intent.EXTRA_TEXT);
    if (action != null) {
        switch (action) {
        case NfcAdapter.ACTION_NDEF_DISCOVERED:
            Lyrics receivedLyrics = getBeamedLyrics(intent);
            if (receivedLyrics != null)
                updateLyricsFragment(0, 0, false, receivedLyrics);
            break;
        case "android.intent.action.SEARCH":
            search(intent.getStringExtra(SearchManager.QUERY));
            break;
        case "android.intent.action.SEND":
            LyricsViewFragment lyricsViewFragment = (LyricsViewFragment) getFragmentManager()
                    .findFragmentByTag(LYRICS_FRAGMENT_TAG);
            new IdDecoder(this, lyricsViewFragment).execute(getIdUrl(extra));
            selectItem(0);//from www.j  av  a 2  s .  co m
            break;
        case "android.intent.action.VIEW":
            if (intent.getDataString().contains("spotify"))
                Spotify.onCallback(intent, this);
            break;
        case "com.geecko.QuickLyric.getLyrics":
            String[] metadata = intent.getStringArrayExtra("TAGS");
            if (metadata != null) {
                String artist = metadata[0];
                String track = metadata[1];
                LyricsViewFragment lyricsFragment = (LyricsViewFragment) getFragmentManager()
                        .findFragmentByTag(LYRICS_FRAGMENT_TAG);
                lyricsFragment.fetchLyrics(artist, track);
                selectItem(0);
            }
            break;
        case "com.geecko.QuickLyric.updateDBList":
            updateDBList();
            break;
        }
    }
}

From source file:com.android.documentsui.DocumentsActivity.java

private void buildDefaultState() {
    mState = new State();

    final Intent intent = getIntent();
    final String action = intent.getAction();
    if (Intent.ACTION_OPEN_DOCUMENT.equals(action)) {
        mState.action = ACTION_OPEN;/*from   w ww  .j  a v a2  s. c o m*/
    } else if (Intent.ACTION_CREATE_DOCUMENT.equals(action)) {
        mState.action = ACTION_CREATE;
    } else if (Intent.ACTION_GET_CONTENT.equals(action)) {
        mState.action = ACTION_GET_CONTENT;
    } else if (DocumentsContract.ACTION_MANAGE_ROOT.equals(action)) {
        mState.action = ACTION_MANAGE;
    }

    if (mState.action == ACTION_OPEN || mState.action == ACTION_GET_CONTENT) {
        mState.allowMultiple = intent.getBooleanExtra(Intent.EXTRA_ALLOW_MULTIPLE, false);
    }

    if (mState.action == ACTION_MANAGE) {
        mState.acceptMimes = new String[] { "*/*" };
        mState.allowMultiple = true;
    } else if (intent.hasExtra(Intent.EXTRA_MIME_TYPES)) {
        mState.acceptMimes = intent.getStringArrayExtra(Intent.EXTRA_MIME_TYPES);
    } else {
        mState.acceptMimes = new String[] { intent.getType() };
    }

    mState.localOnly = intent.getBooleanExtra(Intent.EXTRA_LOCAL_ONLY, false);
    mState.forceAdvanced = intent.getBooleanExtra(DocumentsContract.EXTRA_SHOW_ADVANCED, false);
    mState.showAdvanced = mState.forceAdvanced | SettingsActivity.getDisplayAdvancedDevices(this);
}

From source file:com.keylesspalace.tusky.activity.ComposeActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_compose);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);/*from   w w w .ja  va  2s . c o m*/

    ActionBar actionBar = getSupportActionBar();

    if (actionBar != null) {
        actionBar.setTitle(null);
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setDisplayShowHomeEnabled(true);
        Drawable closeIcon = AppCompatResources.getDrawable(this, R.drawable.ic_close_24dp);
        ThemeUtils.setDrawableTint(this, closeIcon, R.attr.compose_close_button_tint);
        actionBar.setHomeAsUpIndicator(closeIcon);
    }

    SharedPreferences preferences = getSharedPreferences(getString(R.string.preferences_file_key),
            Context.MODE_PRIVATE);

    floatingBtn = (Button) findViewById(R.id.floating_btn);
    pickBtn = (ImageButton) findViewById(R.id.compose_photo_pick);
    nsfwBtn = (Button) findViewById(R.id.action_toggle_nsfw);
    ImageButton visibilityBtn = (ImageButton) findViewById(R.id.action_toggle_visibility);

    floatingBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            sendStatus();
        }
    });
    pickBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onMediaPick();
        }
    });
    nsfwBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            toggleNsfw();
        }
    });
    visibilityBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showComposeOptions();
        }
    });

    String startingVisibility;
    boolean startingHideText;
    ArrayList<SavedQueuedMedia> savedMediaQueued = null;
    if (savedInstanceState != null) {
        showMarkSensitive = savedInstanceState.getBoolean("showMarkSensitive");
        startingVisibility = savedInstanceState.getString("statusVisibility");
        statusMarkSensitive = savedInstanceState.getBoolean("statusMarkSensitive");
        startingHideText = savedInstanceState.getBoolean("statusHideText");
        // Keep these until everything needed to put them in the queue is finished initializing.
        savedMediaQueued = savedInstanceState.getParcelableArrayList("savedMediaQueued");
        // These are for restoring an in-progress commit content operation.
        InputContentInfoCompat previousInputContentInfo = InputContentInfoCompat
                .wrap(savedInstanceState.getParcelable("commitContentInputContentInfo"));
        int previousFlags = savedInstanceState.getInt("commitContentFlags");
        if (previousInputContentInfo != null) {
            onCommitContentInternal(previousInputContentInfo, previousFlags);
        }
    } else {
        showMarkSensitive = false;
        startingVisibility = preferences.getString("rememberedVisibility", "public");
        statusMarkSensitive = false;
        startingHideText = false;
    }

    updateNsfwButtonColor();

    Intent intent = getIntent();
    String[] mentionedUsernames = null;
    inReplyToId = null;
    if (intent != null) {
        inReplyToId = intent.getStringExtra("in_reply_to_id");
        String replyVisibility = intent.getStringExtra("reply_visibility");

        if (replyVisibility != null && startingVisibility != null) {
            // Lowest possible visibility setting in response
            if (startingVisibility.equals("private") || replyVisibility.equals("private")) {
                startingVisibility = "private";
            } else if (startingVisibility.equals("unlisted") || replyVisibility.equals("unlisted")) {
                startingVisibility = "unlisted";
            } else {
                startingVisibility = replyVisibility;
            }
        }

        mentionedUsernames = intent.getStringArrayExtra("mentioned_usernames");
    }
    /* Only after the starting visibility is determined and the send button is initialised can
     * the status visibility be set. */
    setStatusVisibility(startingVisibility);

    textEditor = createEditText(null); // new String[] { "image/gif", "image/webp" }
    final int mentionColour = ThemeUtils.getColor(this, R.attr.compose_mention_color);
    if (savedInstanceState != null) {
        restoreTextEditorState(savedInstanceState.getParcelable("textEditorState"));
        highlightSpans(textEditor.getText(), mentionColour);
    }
    RelativeLayout editArea = (RelativeLayout) findViewById(R.id.compose_edit_area);
    /* Adding this at index zero because it implicitly gives it the lowest input priority. So,
     * when media previews are added in front of the editor, they can receive click events
     * without the text editor stealing the events from behind them. */
    editArea.addView(textEditor, 0);
    contentWarningEditor = (EditText) findViewById(R.id.field_content_warning);
    final TextView charactersLeft = (TextView) findViewById(R.id.characters_left);
    textEditor.addTextChangedListener(new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            int left = STATUS_CHARACTER_LIMIT - s.length() - contentWarningEditor.length();
            charactersLeft.setText(String.format(Locale.getDefault(), "%d", left));
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void afterTextChanged(Editable editable) {
            highlightSpans(editable, mentionColour);
        }
    });

    if (mentionedUsernames != null) {
        StringBuilder builder = new StringBuilder();
        for (String name : mentionedUsernames) {
            builder.append('@');
            builder.append(name);
            builder.append(' ');
        }
        textEditor.setText(builder);
        textEditor.setSelection(textEditor.length());
    }

    mediaPreviewBar = (LinearLayout) findViewById(R.id.compose_media_preview_bar);
    mediaQueued = new ArrayList<>();
    waitForMediaLatch = new CountUpDownLatch();

    contentWarningBar = findViewById(R.id.compose_content_warning_bar);
    contentWarningEditor.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            int left = STATUS_CHARACTER_LIMIT - s.length() - textEditor.length();
            charactersLeft.setText(String.format(Locale.getDefault(), "%d", left));
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    });
    showContentWarning(startingHideText);

    statusAlreadyInFlight = false;

    // These can only be added after everything affected by the media queue is initialized.
    if (savedMediaQueued != null) {
        for (SavedQueuedMedia item : savedMediaQueued) {
            addMediaToQueue(item.type, item.preview, item.uri, item.mediaSize);
        }
    }
}

From source file:com.github.michalbednarski.intentslab.providerlab.AdvancedQueryActivity.java

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.advanced_query);

    Intent intent = getIntent();
    Bundle instanceStateOrExtras = savedInstanceState != null ? savedInstanceState : intent.getExtras();
    if (instanceStateOrExtras == null) {
        instanceStateOrExtras = Bundle.EMPTY;
    }//from   w w w. j  a v  a  2 s .c o m

    // Uri
    mUriTextView = (AutoCompleteTextView) findViewById(R.id.uri);
    if (intent.getData() != null) {
        mUriTextView.setText(intent.getDataString());
    }
    mUriTextView.setAdapter(new UriAutocompleteAdapter(this));

    // Projection
    {
        mSpecifyProjectionCheckBox = (CheckBox) findViewById(R.id.specify_projection);
        mProjectionLayout = (LinearLayout) findViewById(R.id.projection_columns);

        // Bind events for master CheckBox and add new button
        findViewById(R.id.new_projection_column).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new UserProjectionColumn("");
            }
        });
        mSpecifyProjectionCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                mProjectionLayout.setVisibility(isChecked ? View.VISIBLE : View.GONE);
            }
        });

        // Get values to fill
        String[] availableProjectionColumns = intent.getStringArrayExtra(EXTRA_PROJECTION_AVAILABLE_COLUMNS);
        String[] specifiedProjectionColumns = instanceStateOrExtras.getStringArray(EXTRA_PROJECTION);

        if (specifiedProjectionColumns == null) {
            mSpecifyProjectionCheckBox.setChecked(false);
        }

        if (availableProjectionColumns != null && availableProjectionColumns.length == 0) {
            availableProjectionColumns = null;
        }
        if (availableProjectionColumns != null && specifiedProjectionColumns == null) {
            specifiedProjectionColumns = availableProjectionColumns;
        }

        // Create available column checkboxes
        int i = 0;
        if (availableProjectionColumns != null) {
            for (String availableProjectionColumn : availableProjectionColumns) {
                boolean isChecked = i < specifiedProjectionColumns.length
                        && availableProjectionColumn.equals(specifiedProjectionColumns[i]);
                new DefaultProjectionColumn(availableProjectionColumn, isChecked);
                if (isChecked) {
                    i++;
                }
            }
        }

        // Create user column text fields
        if (specifiedProjectionColumns != null && i < specifiedProjectionColumns.length) {
            for (int il = specifiedProjectionColumns.length; i < il; i++) {
                new UserProjectionColumn(specifiedProjectionColumns[i]);
            }
        }

    }

    // Selection
    {
        // Find views
        mSelectionCheckBox = (CheckBox) findViewById(R.id.selection_header);
        mSelectionText = (TextView) findViewById(R.id.selection);
        mSelectionLayout = findViewById(R.id.selection_layout);
        mSelectionArgsTable = (TableLayout) findViewById(R.id.selection_args);

        // Bind events for add button and master CheckBox
        findViewById(R.id.selection_add_arg).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new SelectionArg("", true);
            }
        });
        mSelectionCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                mSelectionLayout.setVisibility(isChecked ? View.VISIBLE : View.GONE);
            }
        });

        // Fill selection text view and CheckBox
        String selection = intent.getStringExtra(EXTRA_SELECTION);
        String[] selectionArgs = instanceStateOrExtras.getStringArray(EXTRA_SELECTION_ARGS);

        mSelectionCheckBox.setChecked(selection != null);
        if (selection != null) {
            mSelectionText.setText(selection);
        }

        // Fill selection arguments
        if ((selection != null || savedInstanceState != null) && selectionArgs != null
                && selectionArgs.length != 0) {
            for (String selectionArg : selectionArgs) {
                new SelectionArg(selectionArg);
            }
        }
    }

    // Content values
    {
        // Find views
        mContentValuesHeader = (TextView) findViewById(R.id.content_values_header);
        mContentValuesTable = (TableLayout) findViewById(R.id.content_values);
        mContentValuesTableHeader = (TableRow) findViewById(R.id.content_values_table_header);

        // Bind add new button event
        findViewById(R.id.new_content_value).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new ContentValue("", "", true);
            }
        });

        // Create table
        ContentValues contentValues = instanceStateOrExtras.getParcelable(EXTRA_CONTENT_VALUES);
        if (contentValues != null) {
            contentValues.valueSet();
            for (String key : Utils.getKeySet(contentValues)) {
                new ContentValue(key, contentValues.getAsString(key));
            }
        }
    }

    // Order
    {
        // Find views
        mSpecifyOrderCheckBox = (CheckBox) findViewById(R.id.specify_order);
        mOrderTextView = (TextView) findViewById(R.id.order);

        // Bind events
        mSpecifyOrderCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                mOrderTextView.setVisibility(isChecked ? View.VISIBLE : View.GONE);
            }
        });

        // Fill fields
        String order = intent.getStringExtra(EXTRA_SORT_ORDER);
        if (order == null) {
            mSpecifyOrderCheckBox.setChecked(false);
        } else {
            mOrderTextView.setText(order);
        }
    }

    // Method (affects previous views so they must be initialized first)
    mMethodSpinner = (Spinner) findViewById(R.id.method);
    mMethodSpinner
            .setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, METHOD_NAMES));
    mMethodSpinner.setOnItemSelectedListener(onMethodSpinnerItemSelectedListener);
    mMethodSpinner.setSelection(intent.getIntExtra(EXTRA_METHOD, METHOD_QUERY));
}