Example usage for android.widget ArrayAdapter createFromResource

List of usage examples for android.widget ArrayAdapter createFromResource

Introduction

In this page you can find the example usage for android.widget ArrayAdapter createFromResource.

Prototype

public static @NonNull ArrayAdapter<CharSequence> createFromResource(@NonNull Context context,
        @ArrayRes int textArrayResId, @LayoutRes int textViewResId) 

Source Link

Document

Creates a new ArrayAdapter from external resources.

Usage

From source file:edu.princeton.jrpalmer.asmlibrary.Settings.java

@Override
protected void onResume() {

    if (Util.trafficCop(this))
        finish();//from   ww w . ja  v a 2  s  .  c  o  m
    IntentFilter uploadFilter;
    uploadFilter = new IntentFilter(
            getResources().getString(R.string.internal_message_id) + Util.MESSAGE_FIX_UPLOADED);
    uploadReceiver = new UploadReceiver();
    registerReceiver(uploadReceiver, uploadFilter);

    IntentFilter fixFilter;
    fixFilter = new IntentFilter(
            getResources().getString(R.string.internal_message_id) + Util.MESSAGE_FIX_RECORDED);
    fixReceiver = new FixReceiver();
    registerReceiver(fixReceiver, fixFilter);

    shareMyData = PropertyHolder.getShareData();

    toggleParticipationViews(shareMyData);

    int nUploads = PropertyHolder.getNUploads();

    final long participationTime = PropertyHolder.ptCheck();
    participationTimeText.setBase(SystemClock.elapsedRealtime() - participationTime);

    // service button
    boolean isServiceOn = PropertyHolder.isServiceOn();

    mServiceButton.setChecked(isServiceOn);
    mServiceButton.setOnClickListener(new ToggleButton.OnClickListener() {
        public void onClick(View view) {
            if (view.getId() != R.id.service_button)
                return;
            Context context = view.getContext();
            boolean on = ((ToggleButton) view).isChecked();
            String schedule = on ? Util.MESSAGE_SCHEDULE : Util.MESSAGE_UNSCHEDULE;
            // Log.e(TAG, schedule + on);

            // now schedule or unschedule
            Intent intent = new Intent(getString(R.string.internal_message_id) + schedule);
            context.sendBroadcast(intent);
            showSpinner(on, storeMyData);

            if (on && shareMyData) {
                final long ptNow = PropertyHolder.ptStart();
                participationTimeText.setBase(SystemClock.elapsedRealtime() - ptNow);
                participationTimeText.start();

                ContentResolver ucr = getContentResolver();

                ucr.insert(Util.getUploadQueueUri(context), UploadContentValues.createUpload("ONF",
                        "on," + Util.iso8601(System.currentTimeMillis()) + "," + ptNow));
            } else {

                final long ptNow = PropertyHolder.ptStop();
                participationTimeText.setBase(SystemClock.elapsedRealtime() - ptNow);
                participationTimeText.stop();
                // stop uploader
                Intent stopUploaderIntent = new Intent(Settings.this, FileUploader.class);
                // Stop service if it is currently running
                stopService(stopUploaderIntent);

                if (shareMyData) {

                    ContentResolver ucr = getContentResolver();

                    ucr.insert(Util.getUploadQueueUri(context), UploadContentValues.createUpload("ONF",
                            "off," + Util.iso8601(System.currentTimeMillis()) + "," + ptNow));

                }

            }
            // If user turns CountdownDisplay on but GPS is not on, remind
            // user to turn
            // GPS on
            if (on) {
                final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

                if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                    if (!manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
                        buildAlertMessageNoGpsNoNet();
                    } else
                        buildAlertMessageNoGps();
                }
            }

            return;
        }
    });

    // interval spinner
    int intspinner_item = android.R.layout.simple_spinner_item;
    int dropdown_item = android.R.layout.simple_spinner_dropdown_item;
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.interval_array,
            intspinner_item);
    adapter.setDropDownViewResource(dropdown_item);
    mIntervalSpinner.setAdapter(adapter);
    mIntervalSpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> parent, View v, int pos, long id) {
            int parentId = parent.getId();
            if (parentId != R.id.spinner_interval)
                return;
            if (pos > mInterval.length)
                return;
            if (!PropertyHolder.isServiceOn()) {
                PropertyHolder.setAlarmInterval(mInterval[pos]);
                return;
            }
            PropertyHolder.setAlarmInterval(mInterval[pos]);
            mServiceButton.setChecked(true);

            Intent intent = new Intent(getString(R.string.internal_message_id) + Util.MESSAGE_SCHEDULE);
            Context context = getApplicationContext();
            context.sendBroadcast(intent);
            showSpinner(true, storeMyData);

            if (shareMyData) {
                ContentResolver ucr = getContentResolver();

                ucr.insert(Util.getUploadQueueUri(context), UploadContentValues.createUpload("INT",
                        Util.iso8601(System.currentTimeMillis()) + "," + mInterval[pos]));
            }
        }

        public void onNothingSelected(AdapterView<?> parent) {
            // do nothing
        }
    });
    int pos = ai2pos(PropertyHolder.getAlarmInterval());
    mIntervalSpinner.setSelection(pos);
    showSpinner(isServiceOn, storeMyData);

    // mydata buttons

    // storage spinner

    storageDays = PropertyHolder.getStorageDays();

    mStorageSpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> parent, View v, int pos, long id) {
            int parentId = parent.getId();
            if (parentId != R.id.spinner_mydata)
                return;
            if (pos > MAX_STORAGE - MIN_STORAGE)
                return;
            PropertyHolder.setStorageDays(pos + MIN_STORAGE);
            PropertyHolder.setStoreMyData((pos + MIN_STORAGE) > 0);
        }

        public void onNothingSelected(AdapterView<?> parent) {
            // do nothing
        }
    });
    int storagepos = storageDays - MIN_STORAGE;
    mStorageSpinner.setSelection(storagepos);

    // NEW STUFF
    mToggleSatRadioGroup = (RadioGroup) findViewById(R.id.toggleSatRadioGroup);
    mToggleIconsRadioGroup = (RadioGroup) findViewById(R.id.toggleIconsRadioGroup);
    mToggleAccRadioGroup = (RadioGroup) findViewById(R.id.toggleAccRadioGroup);
    mLimitStartDateRadioGroup = (RadioGroup) findViewById(R.id.limitStartDateRadioGroup);
    mLimitEndDateRadioGroup = (RadioGroup) findViewById(R.id.limitEndDateRadioGroup);

    Intent i = getIntent();
    if (i.getBooleanExtra(MapMyData.DATES_BUTTON_MESSAGE, false)) {

        RelativeLayout dateSettingsArea = (RelativeLayout) findViewById(R.id.dateSettingsArea);
        dateSettingsArea.setFocusable(true);
        dateSettingsArea.setFocusableInTouchMode(true);
        dateSettingsArea.requestFocus();
    }

    if (shareMyData && isServiceOn) {
        participationTimeText.setBase(SystemClock.elapsedRealtime() - PropertyHolder.ptStart());
        participationTimeText.start();
    }

    nUploadsText.setText(String.valueOf(nUploads));

    if (nUploads >= Util.UPLOADS_TO_PRO && !PropertyHolder.getProVersion()
            && participationTime >= Util.TIME_TO_PRO) {
        Util.createProNotification(context);
        PropertyHolder.setProVersion(true);
        PropertyHolder.setNeedsDebriefingSurvey(true);
    }

    boolean proV = PropertyHolder.getProVersion();

    // 19 December 2013: end of research changes
    mShareDataRadioGroup.check(R.id.sharedataNo);

    mShareDataRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            if (checkedId == R.id.sharedataYes) {
                buildSharingOverAnnouncement();
            }
            mShareDataRadioGroup.check(R.id.sharedataNo);
        }
    });

    /*
     * if (proV) {
     * 
     * if (shareMyData) { mShareDataRadioGroup.check(R.id.sharedataYes); if
     * (PropertyHolder.isRegistered() == false ||
     * PropertyHolder.hasConsented() == false) { send2Intro(context); } }
     * else { mShareDataRadioGroup.check(R.id.sharedataNo); }
     * 
     * mShareDataRadioGroup .setOnCheckedChangeListener(new
     * OnCheckedChangeListener() {
     * 
     * @Override public void onCheckedChanged(RadioGroup group, int
     * checkedId) { shareMyData = (checkedId == R.id.sharedataYes);
     * PropertyHolder.setShareData(shareMyData);
     * toggleParticipationViews(shareMyData); final boolean on =
     * PropertyHolder.isServiceOn(); if (shareMyData) { if
     * (PropertyHolder.isRegistered() == false ||
     * PropertyHolder.hasConsented() == false) { send2Intro(context);
     * 
     * } if (on) {
     * 
     * final long ptNow = PropertyHolder.ptStart();
     * participationTimeText.setBase(SystemClock .elapsedRealtime() -
     * ptNow);
     * 
     * participationTimeText.start();
     * 
     * ContentResolver ucr = getContentResolver();
     * 
     * ucr.insert( Util.getUploadQueueUri(context),
     * UploadContentValues.createUpload( "ONF", "on," + Util.iso8601(System
     * .currentTimeMillis()) + "," + ptNow));
     * 
     * } } else {
     * 
     * final long ptNow = PropertyHolder.ptStop();
     * participationTimeText.setBase(SystemClock .elapsedRealtime() -
     * ptNow); participationTimeText.stop(); // stop uploader Intent i = new
     * Intent(Settings.this, FileUploader.class); // Stop service if it is
     * currently running stopService(i);
     * 
     * if (on) { ContentResolver ucr = getContentResolver();
     * 
     * ucr.insert( Util.getUploadQueueUri(context),
     * UploadContentValues.createUpload( "ONF", "off," + Util.iso8601(System
     * .currentTimeMillis()) + "," + ptNow));
     * 
     * }
     * 
     * }
     * 
     * } }); } else { mShareDataRadioGroup.check(R.id.sharedataYes);
     * mShareDataRadioGroup .setOnCheckedChangeListener(new
     * OnCheckedChangeListener() {
     * 
     * @Override public void onCheckedChanged(RadioGroup group, int
     * checkedId) { if (checkedId == R.id.sharedataNo) {
     * mShareDataRadioGroup.check(R.id.sharedataYes);
     * showCurrentlySharingDialog(); } } });
     * 
     * }
     */
    new CheckPendingUploadsSizeTask().execute(context);
    new CheckUserDbSizeTask().execute(context);

    deletePendingUploadsButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            ContentResolver cr = getContentResolver();
            final int nDeleted = cr.delete(Util.getUploadQueueUri(context), "1", null);

            // Log.i("Settings", "number of rows deleted=" + nDeleted);
            Util.toast(context, String.valueOf(nDeleted) + " "
                    + getResources().getString(R.string.locations_deleted) + ".");

            updateStorageSizes();

        }

    });

    deleteUserDbButton = (ImageButton) findViewById(R.id.deleteMyDbButton);

    deleteUserDbButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            ContentResolver cr = getContentResolver();
            final int nDeleted = cr.delete(Util.getFixesUri(context), "1", null);

            Util.toast(context, String.valueOf(nDeleted) + " "
                    + getResources().getString(R.string.locations_deleted) + ".");
            updateStorageSizes();

        }

    });

    uploadButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            if (Util.isOnline(context)) {
                Intent i = new Intent(Settings.this, FileUploader.class);
                startService(i);

                new UploadMessageTask().execute(context);
            } else {
                Util.toast(context, getResources().getString(R.string.offline_warning));
            }

        }

    });

    mToggleSatRadioGroup.check(PropertyHolder.getMapSat() ? R.id.toggleSatYes : R.id.toggleSatNo);

    mToggleSatRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            PropertyHolder.setMapSat(checkedId == R.id.toggleSatYes);
        }
    });

    mToggleIconsRadioGroup.check(PropertyHolder.getMapIcons() ? R.id.toggleIconsYes : R.id.toggleIconsNo);

    mToggleIconsRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            PropertyHolder.setMapIcons(checkedId == R.id.toggleIconsYes);
        }
    });

    mToggleAccRadioGroup.check(PropertyHolder.getMapAcc() ? R.id.toggleAccYes : R.id.toggleAccNo);

    mToggleAccRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            PropertyHolder.setMapAcc(checkedId == R.id.toggleAccYes);
        }
    });

    mStartDateButton = (Button) findViewById(R.id.startDateButton);
    mEndDateButton = (Button) findViewById(R.id.endDateButton);

    boolean limitStartDate = PropertyHolder.getLimitStartDate();
    boolean limitEndDate = PropertyHolder.getLimitEndDate();

    if (!limitStartDate)
        mStartDateButton.setVisibility(View.GONE);
    else {
        mStartDateButton.setVisibility(View.VISIBLE);

    }
    if (!limitEndDate)
        mEndDateButton.setVisibility(View.GONE);
    else {
        mEndDateButton.setVisibility(View.VISIBLE);
    }

    mLimitStartDateRadioGroup.check(limitStartDate ? R.id.limitStartDateYes : R.id.limitStartDateNo);

    mLimitStartDateRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            PropertyHolder.setLimitStartDate(checkedId == R.id.limitStartDateYes);

            if (checkedId != R.id.limitStartDateYes)
                mStartDateButton.setVisibility(View.GONE);
            else {
                mStartDateButton.setVisibility(View.VISIBLE);
            }
        }
    });

    mLimitEndDateRadioGroup.check(limitEndDate ? R.id.limitEndDateYes : R.id.limitEndDateNo);

    mLimitEndDateRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            PropertyHolder.setLimitEndDate(checkedId == R.id.limitEndDateYes);

            if (checkedId != R.id.limitEndDateYes)
                mEndDateButton.setVisibility(View.GONE);
            else {
                mEndDateButton.setVisibility(View.VISIBLE);
            }
        }
    });

    mStartDateButton.setText(Util.userDateNoTime(PropertyHolder.getMapStartDate()));
    mStartDateButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            DialogFragment newFragment = new StartDatePickerFragment();
            newFragment.show(getSupportFragmentManager(), "datePicker");

        }

    });

    mEndDateButton.setText(Util.userDateNoTime(PropertyHolder.getMapEndDate()));
    mEndDateButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            DialogFragment newFragment = new EndDatePickerFragment();
            newFragment.show(getSupportFragmentManager(), "datePicker");

        }

    });

    if (PropertyHolder.getNeedsDebriefingSurvey()) {
        buildProAnnouncement();
        PropertyHolder.setNeedsDebriefingSurvey(false);
    }

    super.onResume();

}

From source file:com.nuvolect.securesuite.main.ContactListActivity.java

/**
 * Start the GUI, method assumes that a master account is already set
 *//* w  w  w.j a va 2  s.co  m*/
private void startGui() {

    SqlCipher.getInstance(m_ctx);
    /**
     * Detect app upgrade and provide a placeholder for managing upgrades, database changes, etc.
     */
    boolean appUpgraded = LicenseUtil.appUpgraded(m_act);

    if (appUpgraded) {

        Toast.makeText(getApplicationContext(), "Application upgraded", Toast.LENGTH_LONG).show();

        // Execute upgrade methods
    }

    // Set default settings
    PreferenceManager.setDefaultValues(this, R.xml.settings, false);

    // Set the progress bar to off, otherwise some devices will default to on
    setProgressBarIndeterminateVisibility(false);

    // Load group data into memory, used for group titles and people counts
    MyGroups.loadGroupMemory();

    boolean isFirstTime = Persist.isStartingUp(m_ctx);
    if (isFirstTime) {

        String account = LicensePersist.getLicenseAccount(m_ctx);
        Cryp.setCurrentAccount(account);
        MyGroups.addBaseGroupsToNewAccount(m_ctx, account);
        Cryp.setCurrentGroup(MyGroups.getDefaultGroup(account));

        try {
            // Import a default contact when starting first time
            InputStream vcf = getResources().getAssets().open(CConst.APP_VCF);
            ImportVcard.importVcf(m_ctx, vcf, Cryp.getCurrentGroup());

        } catch (IOException e) {
            LogUtil.logException(ContactListActivity.class, e);
        }

        // First time, request phone management access
        PermissionUtil.requestFirstTimePermissions(m_act);
    }

    // Support for action bar pull down menu
    adapter = ArrayAdapter.createFromResource(this, R.array.action_bar_spinner_menu,
            android.R.layout.simple_spinner_dropdown_item);

    // Action bar spinner menu callback
    navigationListener = new OnNavigationListener() {

        // List items from resource
        String[] navItems = getResources().getStringArray(R.array.action_bar_spinner_menu);

        @Override
        public boolean onNavigationItemSelected(int position, long id) {

            if (DEBUG)
                LogUtil.log("ContactListActivity NavigationItemSelected: " + navItems[position]);

            // Do stuff when navigation item is selected
            switch (CConst.NavMenu.values()[position]) {

            case contacts: {

                // Persist the navigation selection for fragments to pick up
                Persist.setNavChoice(m_act, position, navItems[position]);

                break;
            }

            case groups: {

                // Persist the navigation selection for fragments to pick up
                Persist.setNavChoice(m_act, position, navItems[position]);

                // Dispatch to the main group list activity
                Intent intent = new Intent(m_act, GroupListActivity.class);
                startActivity(intent);

                // Remove this activity from the stack
                // Group list is the only activity on the stack
                m_act.finish();

                break;
            }
            case passwords: {

                actionBar.setSelectedNavigationItem(Persist.getNavChoice(m_act));
                PasswordFragment f = PasswordFragment.newInstance(m_act);
                f.start();
                break;
            }
            case calendar: {

                Intent intent = new Intent(m_act, CalendarActivity.class);
                startActivity(intent);
                break;
            }
            case finder: {

                Intent intent = new Intent(m_act, FinderActivity.class);
                startActivity(intent);
                break;
            }
            case server: {

                /**
                 * Restore the spinner such that the Password is never persisted
                 * and never shows.
                 */
                actionBar.setSelectedNavigationItem(Persist.getNavChoice(m_act));
                ServerFragment f = ServerFragment.newInstance(m_act);
                f.start();
                break;
            }
            default:
            }
            return true;
        }
    };

    actionBar = getActionBar();
    ActionBarUtil.setNavigationMode(actionBar, ActionBar.NAVIGATION_MODE_LIST);
    ActionBarUtil.setDisplayShowTitleEnabled(actionBar, false);
    ActionBarUtil.setListNavigationCallbacks(actionBar, adapter, navigationListener);
    AppTheme.applyActionBarTheme(m_act, actionBar);

    // Start with the previous contact or reset to a valid contact
    m_contact_id = Persist.getCurrentContactId(m_act);
    if (m_contact_id <= 0 || !SqlCipher.validContactId(m_contact_id)) {
        m_contact_id = SqlCipher.getFirstContactID();
        Persist.setCurrentContactId(m_act, m_contact_id);
    }

    // savedInstanceState is non-null when there is fragment state
    // saved from previous configurations of this activity
    // (e.g. when rotating the screen from portrait to landscape).
    // In this case, the fragment will automatically be re-added
    // to its container so we don't need to manually add it.
    // For more information, see the Fragments API guide at:
    //
    // http://developer.android.com/guide/components/fragments.html
    //
    if (isFirstTime || m_savedInstanceState == null) {

        if (findViewById(R.id.contact_detail_container) != null) {
            // Setup for single or dual fragments depending on display size
            // The detail container view will be present only in the large-screen layouts
            // (res/values-large and res/values-sw600dp). If this view is present, then the
            // activity should be in two-pane mode.
            mTwoPane = true;

            m_clf_fragment = startContactListFragment();

            // In two-pane mode, list items should be given the 'activated' state when touched.
            m_clf_fragment.setActivateOnItemClick(true);

            // In two-pane mode, show the detail view in this activity by
            // adding or replacing the detail fragment using a fragment transaction.
            startContactDetailFragment();

        } else {
            mTwoPane = false;
            m_clf_fragment = startContactListFragment();
        }
    }
}

From source file:com.digi.android.wva.fragments.EndpointOptionsDialog.java

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    if (mConfig == null && savedInstanceState == null) {
        Log.e(TAG, "mConfig is null, not showing dialog!");
        return null;
    }//from  w  w w . j  ava 2s  .  com

    LayoutInflater inf = getActivity().getLayoutInflater();
    View v = inf.inflate(R.layout.dialog_endpoint_options, null);

    // Suppresses warnings, and ensures the layout exists.
    assert v != null;
    final TextView subIntervalTV = (TextView) v.findViewById(R.id.textView_interval);
    final TextView alarmInfoTV = (TextView) v.findViewById(R.id.alarm_info);
    final CheckBox subscribedCB = (CheckBox) v.findViewById(R.id.subscribedCheckbox);
    final CheckBox alarmCB = (CheckBox) v.findViewById(R.id.alarmCheckbox);
    final EditText subInterval = (EditText) v.findViewById(R.id.subscriptionInterval);
    final EditText alarmThreshold = (EditText) v.findViewById(R.id.alarmThreshold);
    final Spinner typeSpinner = (Spinner) v.findViewById(R.id.alarmTypeSpinner);
    final LinearLayout makeAlarmSection = (LinearLayout) v.findViewById(R.id.section_make_alarm);
    final LinearLayout showAlarmSection = (LinearLayout) v.findViewById(R.id.section_show_alarm);
    final CheckBox dcSendCB = (CheckBox) v.findViewById(R.id.dcPushCheckbox);

    String alarmInfo = "No alarm yet";
    boolean isSubscribed = false;
    String endpointName = "UNKNOWN";
    int sinterval = 10;
    boolean alarmCreated = false;
    double threshold = 0;
    int alarmtypeidx = 0;

    boolean isSendingToDC = false;

    if (savedInstanceState != null && savedInstanceState.containsKey("config")) {
        mConfig = savedInstanceState.getParcelable("config");
    }

    if (mConfig != null) {
        endpointName = mConfig.getEndpoint();
        alarmInfo = mConfig.getAlarmSummary();

        if (mConfig.getSubscriptionConfig() != null) {
            isSubscribed = mConfig.getSubscriptionConfig().isSubscribed();
            sinterval = mConfig.getSubscriptionConfig().getInterval();
            isSendingToDC = mConfig.shouldBePushedToDeviceCloud();
        } else {
            // Not subscribed; default interval value from preferences.
            String i = PreferenceManager.getDefaultSharedPreferences(getActivity())
                    .getString("pref_default_interval", "0");
            try {
                sinterval = Integer.parseInt(i);
            } catch (NumberFormatException e) {
                Log.d(TAG, "Failed to parse default interval from preferences: " + i);
                sinterval = 0;
            }
        }

        if (mConfig.getAlarmConfig() != null) {
            alarmCreated = mConfig.getAlarmConfig().isCreated();
            threshold = mConfig.getAlarmConfig().getThreshold();
            String typestr = AlarmType.makeString(mConfig.getAlarmConfig().getType());
            for (int i = 0; i < alarmTypes.length; i++) {
                if (alarmTypes[i].toLowerCase(Locale.US).equals(typestr))
                    alarmtypeidx = i;
            }
        }
    }

    // Set up event listeners on EditText and CheckBox items

    subscribedCB.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            subInterval.setEnabled(isChecked);
            subIntervalTV.setEnabled(isChecked);
        }
    });

    alarmCB.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            typeSpinner.setEnabled(isChecked);
            alarmThreshold.setEnabled(false);
            // If type spinner is set to Change, we want threshold disabled again
            if (isChecked) {
                alarmThreshold.setEnabled(!shouldDisableAlarmThreshold(typeSpinner.getSelectedItemPosition()));
            }
        }
    });

    typeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long id) {
            if (alarmCB.isChecked() && shouldDisableAlarmThreshold(position))
                alarmThreshold.setEnabled(false);
            else if (!alarmCB.isChecked())
                alarmThreshold.setEnabled(false);
            else
                alarmThreshold.setEnabled(true);
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
        }
    });

    subIntervalTV.setEnabled(false);
    subInterval.setEnabled(false);
    alarmThreshold.setEnabled(false);
    typeSpinner.setEnabled(false);
    alarmInfoTV.setText(alarmInfo);

    // Click checkboxes, show data depending on if subscription or alarm
    // has been added already
    if (isSubscribed)
        subscribedCB.performClick();
    if (alarmCreated) {
        showAlarmSection.setVisibility(View.VISIBLE);
        makeAlarmSection.setVisibility(View.GONE);
        alarmCB.setText("Remove alarm");
    } else {
        makeAlarmSection.setVisibility(View.VISIBLE);
        showAlarmSection.setVisibility(View.GONE);
        alarmCB.setText("Create alarm");
    }

    dcSendCB.setChecked(isSendingToDC);

    subInterval.setText(Integer.toString(sinterval));

    alarmThreshold.setText(Double.toString(threshold));

    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(), R.array.alarm_types,
            android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    typeSpinner.setAdapter(adapter);
    typeSpinner.setSelection(alarmtypeidx);

    DialogInterface.OnClickListener clickListener = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int i) {
            // Fetch the EndpointsAdapter's configuration for this endpoint.
            // (We might have gotten mConfig from the saved instance bundle)
            EndpointConfiguration cfg = EndpointsAdapter.getInstance()
                    .findEndpointConfiguration(mConfig.getEndpoint());

            // Set whether this endpoint's data should be pushed to Device Cloud
            if (cfg != null) {
                cfg.setPushToDeviceCloud(dcSendCB.isChecked());
            }

            // Handle (un)subscribing

            if (isUnsubscribing(subscribedCB.isChecked())) {
                unsubscribe(mConfig.getEndpoint());
            } else if (subscribedCB.isChecked()) {
                if (handleMakingSubscription(subInterval)) {
                    // Subscription was successful... most likely.
                    Log.d(TAG, "Probably subscribed to endpoint.");
                } else {
                    // Invalid interval.
                    Toast.makeText(getActivity(),
                            getString(R.string.configure_endpoints_toast_invalid_sub_interval),
                            Toast.LENGTH_SHORT).show();
                }
            }

            // Handle adding/removing alarm as necessary

            if (isRemovingAlarm(alarmCB.isChecked())) {
                removeAlarm(mConfig.getEndpoint(), mConfig.getAlarmConfig().getType());
            } else if (alarmCB.isChecked()) {
                Editable thresholdText = alarmThreshold.getText();
                String thresholdString;
                if (thresholdText == null)
                    thresholdString = "";
                else
                    thresholdString = thresholdText.toString();

                double threshold;
                try {
                    threshold = Double.parseDouble(thresholdString);
                } catch (NumberFormatException e) {
                    Toast.makeText(getActivity(), getString(R.string.configure_endpoints_invalid_threshold),
                            Toast.LENGTH_SHORT).show();
                    return;
                }

                int alarmidx = typeSpinner.getSelectedItemPosition();
                if (alarmidx == -1) {
                    // But... how?
                    Log.wtf(TAG, "alarm type index -1 ?");
                    return;
                }
                String type = alarmTypes[alarmidx];
                AlarmType atype = AlarmType.fromString(type);

                createAlarm(mConfig.getEndpoint(), atype, threshold);
            }

            dialog.dismiss();
        }
    };

    return new AlertDialog.Builder(getActivity()).setView(v).setTitle("Endpoint: " + endpointName)
            .setPositiveButton("Save", clickListener)
            .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // Cancel means just dismiss the dialog.
                    dialog.dismiss();
                }
            }).create();
}

From source file:com.micabytes.app.BaseFragment.java

@NonNull
protected Spinner setSpinner(int resId, int arrId, int spIt, int spDd) throws UIObjectNotFoundException {
    View root = getView();/* ww  w .  ja  v  a 2  s  . c  o m*/
    if (root == null)
        throw new UIObjectNotFoundException(COULD_NOT_FIND_THE_ROOT_VIEW);
    Spinner spinner = (Spinner) root.findViewById(resId);
    if (spinner == null)
        throw new UIObjectNotFoundException(COULD_NOT_FIND_RES_ID + resId + IN_FIND_VIEW_BY_ID);
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity().getApplicationContext(),
            arrId, spIt);
    adapter.setDropDownViewResource(spDd);
    spinner.setAdapter(adapter);
    return spinner;
}

From source file:com.terraremote.terrafieldreport.OpenGroundReport.java

@OnItemSelected(R.id.checkInContactRoleSpinner)
void fieldSupervisorSpinnerSelected(int position) {
    position = mCheckInContactRoleSpinner.getSelectedItemPosition();
    if (position == 2) {
        // Create an ArrayAdapter using the string array and a default spinner layout
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(OpenGroundReport.this,
                R.array.check_in_contact_field_supervisor_names, android.R.layout.simple_spinner_item);
        // Specify the layout to use when the list of choices appears
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mCheckInContactNameSpinner.setVisibility(View.VISIBLE);
        mOtherContactName.setVisibility(View.GONE);
        mOtherContactName.setText("");
        // Apply the adapter to the spinner
        mCheckInContactNameSpinner.setAdapter(adapter);
    }/*from w  w w .j a v  a 2 s .  c  o m*/
}

From source file:com.hangulo.powercontact.ContactsListFragment.java

void setDistanceSpinnerAdapter() {
    // title must be changed by locale / ?? ? ?? ? .
    final int num_array_pref_range_distance_titles;
    final int num_array_pref_range_distance_values;

    Log.v(LOG_TAG, "setDistanceSpinnerAdapter distance");

    // set mile or meter by locale ?? ? ? ? .
    if (mCallback.getPowerContactSettings().getRealDistanceUnits() == Constants.DISTANCE_UNITS_METER) {
        num_array_pref_range_distance_titles = R.array.pref_range_distance_titles_meter;
        num_array_pref_range_distance_values = R.array.pref_range_distance_values_meter;
    } else {/*ww  w. j ava2 s.c om*/
        num_array_pref_range_distance_titles = R.array.pref_range_distance_titles_mile;
        num_array_pref_range_distance_values = R.array.pref_range_distance_values_mile;
    }

    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(),
            num_array_pref_range_distance_titles, android.R.layout.simple_spinner_item); // R.layout.spinner_item);

    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    mSpinnerDistance.setAdapter(adapter);
    //  
    mSpinnerDistance.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

            double distance = setSpinnerDistanceChanged(position, num_array_pref_range_distance_values); // change distance                 // ?.. ?? ..

            Log.v(LOG_TAG, "mSpinnerDistance/listener : loader restart distace:" + distance + "time"
                    + System.currentTimeMillis());

            mCallback.restartMainLoader(distance); // restart main loader  // ? .. ? ?   ?.    ? ?  ?.
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        }
    });

    String[] strArray = getResources().getStringArray(num_array_pref_range_distance_values);

    Double distance = getDistance(); // ?  .

    Log.v(LOG_TAG, "setDistanceSpinnerAdapter distance setSection" + distance);
    int i;
    for (i = 0; i < strArray.length; i++)
        if (Double.parseDouble(strArray[i]) == distance) {
            mSpinnerDistance.setSelection(i); // 2016.3.31 .
            // setSpinnerDistanceChanged(i, num_array_pref_range_distance_values); // change distance
            break;
        }

    adapter.notifyDataSetChanged(); // http://stackoverflow.com/questions/9443370/how-to-update-an-spinner-dynamically-in-android-correctly

}

From source file:edu.umich.oasis.testapp.TestActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_test);
    kvsValueField = (EditText) findViewById(R.id.kvs_value);
    shouldTaintBox = (CheckBox) findViewById(R.id.is_tainted);
    rootLayout = (RelativeLayout) findViewById(R.id.root_layout);
    sandboxCount = (Spinner) findViewById(R.id.sandbox_count);
    sandboxCountType = (Spinner) findViewById(R.id.sandbox_count_type);
    perfPassCount = (EditText) findViewById(R.id.perf_pass_count);
    taintPerfBox = (CheckBox) findViewById(R.id.perf_taint);

    // Set up adapter for sandbox count spinner
    CharSequence[] countList = new CharSequence[OASISConstants.NUM_SANDBOXES + 1];
    for (int i = 0; i <= OASISConstants.NUM_SANDBOXES; i++) {
        countList[i] = getResources().getQuantityString(R.plurals.sandbox_plurals, i, i);
    }/*from   w  w w  . j ava 2  s .c  om*/
    ArrayAdapter<CharSequence> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item,
            countList);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    sandboxCount.setAdapter(adapter);
    sandboxCount.setSelection(OASISConstants.NUM_SANDBOXES);

    adapter = ArrayAdapter.createFromResource(this, R.array.sandbox_count_labels,
            android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    sandboxCountType.setAdapter(adapter);

    setButtonsEnabled(false);
    connectToOASIS(null);
}

From source file:edu.umich.flowfence.testapp.TestActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_test);
    kvsValueField = (EditText) findViewById(R.id.kvs_value);
    shouldTaintBox = (CheckBox) findViewById(R.id.is_tainted);
    rootLayout = (RelativeLayout) findViewById(R.id.root_layout);
    sandboxCount = (Spinner) findViewById(R.id.sandbox_count);
    sandboxCountType = (Spinner) findViewById(R.id.sandbox_count_type);
    perfPassCount = (EditText) findViewById(R.id.perf_pass_count);
    taintPerfBox = (CheckBox) findViewById(R.id.perf_taint);

    // Set up adapter for sandbox count spinner
    CharSequence[] countList = new CharSequence[FlowfenceConstants.NUM_SANDBOXES + 1];
    for (int i = 0; i <= FlowfenceConstants.NUM_SANDBOXES; i++) {
        countList[i] = getResources().getQuantityString(R.plurals.sandbox_plurals, i, i);
    }//  ww  w .  ja v a 2  s.  c o m
    ArrayAdapter<CharSequence> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item,
            countList);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    sandboxCount.setAdapter(adapter);
    sandboxCount.setSelection(FlowfenceConstants.NUM_SANDBOXES);

    adapter = ArrayAdapter.createFromResource(this, R.array.sandbox_count_labels,
            android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    sandboxCountType.setAdapter(adapter);

    setButtonsEnabled(false);
    connectToFlowfence(null);
}

From source file:nl.sogeti.android.gpstracker.actions.NameTrack.java

@Override
protected Dialog onCreateDialog(int id) {
    Dialog dialog = null;//from  ww w  .  j  a v  a2 s. com
    LayoutInflater factory = null;
    View view = null;
    Builder builder = null;
    switch (id) {
    case DIALOG_TRACKNAME:
        builder = new AlertDialog.Builder(this);
        factory = LayoutInflater.from(this);
        view = factory.inflate(R.layout.namedialog, null);
        mTrackNameView = (EditText) view.findViewById(R.id.nameField);
        mHelmetRadioGroup = (RadioGroup) view.findViewById(R.id.helmetRadioGroup);
        mServiceRatingBar = (RatingBar) view.findViewById(R.id.serviceRatingBar);
        mOriginReasonSpinner = (Spinner) view.findViewById(R.id.originReasonSpinner);
        mDestinationReasonSpinner = (Spinner) view.findViewById(R.id.destinationReasonSpinner);
        mReasonAdapter = ArrayAdapter.createFromResource(this, R.array.Reason_choices,
                android.R.layout.simple_spinner_item);
        mReasonAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        mOriginReasonSpinner.setAdapter(mReasonAdapter);
        mDestinationReasonSpinner.setAdapter(mReasonAdapter);

        mStartStationAutoCompleteTextView = (AutoCompleteTextView) view
                .findViewById(R.id.startStationAutocomplete);

        mStartStationAutoCompleteTextView.setAdapter(mStartStationSimpleCursorAdapter);
        mStartStationAutoCompleteTextView.addTextChangedListener(this);
        mStartStationAutoCompleteTextView.addTextChangedListener(mStartStationTextWatcher);

        mEndStationAutoCompleteTextView = (AutoCompleteTextView) view.findViewById(R.id.endStationAutocomplete);

        mEndStationAutoCompleteTextView.setAdapter(mEndStationSimpleCursorAdapter);
        mEndStationAutoCompleteTextView.addTextChangedListener(this);
        mEndStationAutoCompleteTextView.addTextChangedListener(mEndStationTextWatcher);

        builder.setTitle(R.string.dialog_routename_title)
                //.setMessage( R.string.dialog_routename_message )
                .setIcon(android.R.drawable.ic_dialog_alert)
                .setPositiveButton(R.string.btn_okay, mTrackNameDialogListener)
                .setNeutralButton(R.string.btn_skip, mTrackNameDialogListener)
                .setNegativeButton(R.string.btn_cancel, mTrackNameDialogListener).setView(view);
        dialog = builder.create();
        dialog.setOnDismissListener(new OnDismissListener() {
            public void onDismiss(DialogInterface dialog) {
                if (!paused) {
                    finish();
                }
            }
        });
        return dialog;
    default:
        return super.onCreateDialog(id);
    }
}

From source file:com.terraremote.terrafieldreport.OpenGroundReport.java

@OnItemSelected(R.id.checkInContactRoleSpinner)
void aerialOperationsSpinnerSelected(int position) {
    position = mCheckInContactRoleSpinner.getSelectedItemPosition();
    if (position == 3) {
        // Create an ArrayAdapter using the string array and a default spinner layout
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(OpenGroundReport.this,
                R.array.check_in_contact_aerial_manager_names, android.R.layout.simple_spinner_item);
        // Specify the layout to use when the list of choices appears
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mCheckInContactNameSpinner.setVisibility(View.VISIBLE);
        mOtherContactName.setVisibility(View.GONE);
        mOtherContactName.setText("");
        // Apply the adapter to the spinner
        mCheckInContactNameSpinner.setAdapter(adapter);
    }/*from  w  w  w. java2 s .c  om*/
}