Example usage for android.widget Spinner setAdapter

List of usage examples for android.widget Spinner setAdapter

Introduction

In this page you can find the example usage for android.widget Spinner setAdapter.

Prototype

@Override
public void setAdapter(SpinnerAdapter adapter) 

Source Link

Document

Sets the SpinnerAdapter used to provide the data which backs this Spinner.

Usage

From source file:com.vuze.android.remote.activity.DrawerActivity.java

private void setupProfileSpinner() {

    Spinner spinner = (Spinner) findViewById(R.id.drawer_profile_spinner);
    if (spinner == null) {
        return;/*from  w  w  w.ja va2s  .  c  o  m*/
    }

    AppPreferences appPreferences = VuzeRemoteApp.getAppPreferences();
    if (appPreferences.getNumRemotes() <= 1) {
        spinner.setEnabled(false);
    }

    RemoteProfile remoteProfile = getSessionInfo().getRemoteProfile();

    final ActionBarArrayAdapter adapter = new ActionBarArrayAdapter(this);
    final int initialPos = adapter.refreshList(remoteProfile);

    // Note: If the adapter returns itemPosition for itemID, we have problems
    // when the user rotates the screen (something about restoring the drop
    // down list, firing the wrong id/position)
    // Most "solutions" on the internet say "ignore first call too onNavigationItemSelected"
    // but I've found this not to be consistent (in some cases there is no phantom
    // call)
    OnItemSelectedListener navigationListener = new OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int itemPosition, long itemId) {
            RemoteProfile remoteProfile = getSessionInfo().getRemoteProfile();
            RemoteProfile profile = adapter.getItem(itemPosition);
            if (profile != null && !profile.getID().equals(remoteProfile.getID())) {
                if (DEBUG_SPINNER) {
                    Log.d(TAG, remoteProfile.getNick() + "] Spinner Selected " + itemPosition + ":" + itemId
                            + "/" + profile.getNick() + " via " + AndroidUtils.getCompressedStackTrace());
                }
                finish();
                RemoteUtils.openRemote(DrawerActivity.this, profile, false);
                return;
            }
            if (DEBUG_SPINNER) {
                Log.d(TAG, remoteProfile.getNick() + "] Spinner Selected " + itemPosition + ":" + itemId + "/"
                        + (profile == null ? "null" : profile.getNick()) + " ignored");
            }
        }

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

    spinner.setAdapter(adapter);
    spinner.setOnItemSelectedListener(navigationListener);

    if (DEBUG_SPINNER) {
        Log.d(TAG, remoteProfile.getNick() + "] Spinner seting pos to " + initialPos);
    }
    // This doesn't seem to trigger naviationListener
    spinner.setSelection(initialPos);
    if (DEBUG_SPINNER) {
        Log.d(TAG, remoteProfile.getNick() + "] Spinner set pos to " + initialPos);
    }
}

From source file:com.mantz_it.rfanalyzer.ui.activity.MainActivity.java

public void showRecordingDialog() {
    if (!running || scheduler == null || demodulator == null || source == null) {
        toaster.showLong("Analyzer must be running to start recording");
        return;//  www .j a  v a 2 s.c  om
    }
    // Check for the WRITE_EXTERNAL_STORAGE permission:
    if (ContextCompat.checkSelfPermission(this,
            "android.permission.WRITE_EXTERNAL_STORAGE") != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[] { "android.permission.WRITE_EXTERNAL_STORAGE" },
                PERMISSION_REQUEST_RECORDING_WRITE_FILES);
        return; // wait for the permission response (handled in onRequestPermissionResult())
    }

    final String externalDir = Environment.getExternalStorageDirectory().getAbsolutePath();
    final int[] supportedSampleRates = rxSampleRate.getSupportedSampleRates();
    final double maxFreqMHz = rxFrequency.getMax() / 1000000f; // max frequency of the source in MHz
    final int sourceType = Integer.parseInt(preferences.getString(getString(R.string.pref_sourceType), "1"));
    final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss", Locale.US);

    // Get references to the GUI components:
    final ScrollView view = (ScrollView) this.getLayoutInflater().inflate(R.layout.start_recording, null);
    final EditText et_filename = (EditText) view.findViewById(R.id.et_recording_filename);
    final EditText et_frequency = (EditText) view.findViewById(R.id.et_recording_frequency);
    final Spinner sp_sampleRate = (Spinner) view.findViewById(R.id.sp_recording_sampleRate);
    final TextView tv_fixedSampleRateHint = (TextView) view.findViewById(R.id.tv_recording_fixedSampleRateHint);
    final CheckBox cb_stopAfter = (CheckBox) view.findViewById(R.id.cb_recording_stopAfter);
    final EditText et_stopAfter = (EditText) view.findViewById(R.id.et_recording_stopAfter);
    final Spinner sp_stopAfter = (Spinner) view.findViewById(R.id.sp_recording_stopAfter);

    // Setup the sample rate spinner:
    final ArrayAdapter<Integer> sampleRateAdapter = new ArrayAdapter<>(this,
            android.R.layout.simple_list_item_1);
    for (int sampR : supportedSampleRates)
        sampleRateAdapter.add(sampR);
    sampleRateAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    sp_sampleRate.setAdapter(sampleRateAdapter);

    // Add listener to the frequency textfield, the sample rate spinner and the checkbox:
    et_frequency.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) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (et_frequency.getText().length() == 0)
                return;
            double freq = Double.parseDouble(et_frequency.getText().toString());
            if (freq < maxFreqMHz)
                freq = freq * 1000000;
            et_filename.setText(simpleDateFormat.format(new Date()) + "_" + SOURCE_NAMES[sourceType] + "_"
                    + (long) freq + "Hz_" + sp_sampleRate.getSelectedItem() + "Sps.iq");
        }
    });
    sp_sampleRate.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            if (et_frequency.getText().length() == 0)
                return;
            double freq = Double.parseDouble(et_frequency.getText().toString());
            if (freq < maxFreqMHz)
                freq = freq * 1000000;
            et_filename.setText(simpleDateFormat.format(new Date()) + "_" + SOURCE_NAMES[sourceType] + "_"
                    + (long) freq + "Hz_" + sp_sampleRate.getSelectedItem() + "Sps.iq");
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        }
    });
    cb_stopAfter.setOnCheckedChangeListener((buttonView, isChecked) -> {
        et_stopAfter.setEnabled(isChecked);
        sp_stopAfter.setEnabled(isChecked);
    });

    // Set default frequency, sample rate and stop after values:
    et_frequency.setText(Long.toString(analyzerSurface.getVirtualFrequency()));
    int sampleRateIndex = 0;
    int lastSampleRate = preferences.getInt(getString(R.string.pref_recordingSampleRate), 1000000);
    for (; sampleRateIndex < supportedSampleRates.length; sampleRateIndex++) {
        if (supportedSampleRates[sampleRateIndex] >= lastSampleRate)
            break;
    }
    if (sampleRateIndex >= supportedSampleRates.length)
        sampleRateIndex = supportedSampleRates.length - 1;
    sp_sampleRate.setSelection(sampleRateIndex);
    cb_stopAfter.toggle(); // just to trigger the listener at least once!
    cb_stopAfter.setChecked(preferences.getBoolean(getString(R.string.pref_recordingStopAfterEnabled), false));
    et_stopAfter.setText(
            Integer.toString(preferences.getInt(getString(R.string.pref_recordingStopAfterValue), 10)));
    sp_stopAfter.setSelection(preferences.getInt(getString(R.string.pref_recordingStopAfterUnit), 0));

    // disable sample rate selection if demodulation is running:
    if (demodulationMode != Demodulator.DEMODULATION_OFF) {
        sampleRateAdapter.add(rxSampleRate.get()); // add the current sample rate in case it's not already in the list
        sp_sampleRate.setSelection(sampleRateAdapter.getPosition(rxSampleRate.get())); // select it
        sp_sampleRate.setEnabled(false); // disable the spinner
        tv_fixedSampleRateHint.setVisibility(View.VISIBLE);
    }

    // Show dialog:
    new AlertDialog.Builder(this).setTitle("Start recording").setView(view)
            .setPositiveButton("Record", (dialog, whichButton) -> {
                String filename = et_filename.getText().toString();
                final int stopAfterUnit = sp_stopAfter.getSelectedItemPosition();
                final int stopAfterValue = Integer.parseInt(et_stopAfter.getText().toString());
                //todo check filename

                // Set the frequency in the source:
                if (et_frequency.getText().length() == 0)
                    return;
                double freq = Double.parseDouble(et_frequency.getText().toString());
                if (freq < maxFreqMHz)
                    freq = freq * 1000000;
                if (freq <= rxFrequency.getMax() && freq >= rxFrequency.getMin())
                    rxFrequency.set((long) freq);
                else {
                    toaster.showLong("Frequency is invalid!");
                    return;
                }

                // Set the sample rate (only if demodulator is off):
                if (demodulationMode == Demodulator.DEMODULATION_OFF)
                    rxSampleRate.set((Integer) sp_sampleRate.getSelectedItem());

                // Open file and start recording:
                recordingFile = new File(externalDir + "/" + RECORDING_DIR + "/" + filename);
                recordingFile.getParentFile().mkdir(); // Create directory if it does not yet exist
                try {
                    scheduler.startRecording(new BufferedOutputStream(new FileOutputStream(recordingFile)));
                } catch (FileNotFoundException e) {
                    Log.e(LOGTAG, "showRecordingDialog: File not found: " + recordingFile.getAbsolutePath());
                }

                // safe preferences:
                SharedPreferences.Editor edit = preferences.edit();
                edit.putInt(getString(R.string.pref_recordingSampleRate),
                        (Integer) sp_sampleRate.getSelectedItem());
                edit.putBoolean(getString(R.string.pref_recordingStopAfterEnabled), cb_stopAfter.isChecked());
                edit.putInt(getString(R.string.pref_recordingStopAfterValue), stopAfterValue);
                edit.putInt(getString(R.string.pref_recordingStopAfterUnit), stopAfterUnit);
                edit.apply();

                analyzerSurface.setRecordingEnabled(true);

                updateActionBar();

                // if stopAfter was selected, start thread to supervise the recording:
                if (cb_stopAfter.isChecked()) {
                    final String recorderSuperviserName = "Supervisor Thread";
                    Thread supervisorThread = new Thread(() -> {
                        Log.i(LOGTAG, "recording_superviser: Supervisor Thread started. (Thread: "
                                + recorderSuperviserName + ")");
                        try {
                            long startTime = System.currentTimeMillis();
                            boolean stop = false;

                            // We check once per half a second if the stop criteria is met:
                            Thread.sleep(500);
                            while (recordingFile != null && !stop) {
                                switch (stopAfterUnit) { // see arrays.xml - recording_stopAfterUnit
                                case 0: /* MB */
                                    if (recordingFile.length() / 1000000 >= stopAfterValue)
                                        stop = true;
                                    break;
                                case 1: /* GB */
                                    if (recordingFile.length() / 1000000000 >= stopAfterValue)
                                        stop = true;
                                    break;
                                case 2: /* sec */
                                    if (System.currentTimeMillis() - startTime >= stopAfterValue * 1000)
                                        stop = true;
                                    break;
                                case 3: /* min */
                                    if (System.currentTimeMillis() - startTime >= stopAfterValue * 1000 * 60)
                                        stop = true;
                                    break;
                                }
                            }
                            // stop recording:
                            stopRecording();
                        } catch (InterruptedException e) {
                            // todo: shouldn't we call stopRecording() here? how about finally{}?
                            Log.e(LOGTAG, "recording_superviser: Interrupted!");
                        } catch (NullPointerException e) {
                            Log.e(LOGTAG, "recording_superviser: Recording file is null!");
                        }
                        Log.i(LOGTAG, "recording_superviser: Supervisor Thread stopped. (Thread: "
                                + recorderSuperviserName + ")");

                    }, recorderSuperviserName);
                    supervisorThread.start();
                }
            }).setNegativeButton("Cancel", (dialog, whichButton) -> {
                // do nothing
            }).show().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}

From source file:org.openhab.habdroid.ui.OpenHABWidgetAdapter.java

@SuppressWarnings("deprecation")
@Override//from  ww  w  .j  a v a2s  .  c o m
public View getView(int position, View convertView, ViewGroup parent) {
    /* TODO: This definitely needs some huge refactoring */
    final RelativeLayout widgetView;
    TextView labelTextView;
    TextView valueTextView;
    int widgetLayout;
    String[] splitString;
    OpenHABWidget openHABWidget = getItem(position);
    int screenWidth = ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE))
            .getDefaultDisplay().getWidth();
    switch (this.getItemViewType(position)) {
    case TYPE_FRAME:
        widgetLayout = R.layout.openhabwidgetlist_frameitem;
        break;
    case TYPE_GROUP:
        widgetLayout = R.layout.openhabwidgetlist_groupitem;
        break;
    case TYPE_SECTIONSWITCH:
        widgetLayout = R.layout.openhabwidgetlist_sectionswitchitem;
        break;
    case TYPE_SWITCH:
        widgetLayout = R.layout.openhabwidgetlist_switchitem;
        break;
    case TYPE_ROLLERSHUTTER:
        widgetLayout = R.layout.openhabwidgetlist_rollershutteritem;
        break;
    case TYPE_TEXT:
        widgetLayout = R.layout.openhabwidgetlist_textitem;
        break;
    case TYPE_SLIDER:
        widgetLayout = R.layout.openhabwidgetlist_slideritem;
        break;
    case TYPE_IMAGE:
        widgetLayout = R.layout.openhabwidgetlist_imageitem;
        break;
    case TYPE_SELECTION:
        widgetLayout = R.layout.openhabwidgetlist_selectionitem;
        break;
    case TYPE_SETPOINT:
        widgetLayout = R.layout.openhabwidgetlist_setpointitem;
        break;
    case TYPE_CHART:
        widgetLayout = R.layout.openhabwidgetlist_chartitem;
        break;
    case TYPE_VIDEO:
        widgetLayout = R.layout.openhabwidgetlist_videoitem;
        break;
    case TYPE_VIDEO_MJPEG:
        widgetLayout = R.layout.openhabwidgetlist_videomjpegitem;
        break;
    case TYPE_WEB:
        widgetLayout = R.layout.openhabwidgetlist_webitem;
        break;
    case TYPE_COLOR:
        widgetLayout = R.layout.openhabwidgetlist_coloritem;
        break;
    default:
        widgetLayout = R.layout.openhabwidgetlist_genericitem;
        break;
    }
    if (convertView == null) {
        widgetView = new RelativeLayout(getContext());
        String inflater = Context.LAYOUT_INFLATER_SERVICE;
        LayoutInflater vi;
        vi = (LayoutInflater) getContext().getSystemService(inflater);
        vi.inflate(widgetLayout, widgetView, true);
    } else {
        widgetView = (RelativeLayout) convertView;
    }

    // Process the colour attributes
    Integer iconColor = openHABWidget.getIconColor();
    Integer labelColor = openHABWidget.getLabelColor();
    Integer valueColor = openHABWidget.getValueColor();

    // Process widgets icon image
    MySmartImageView widgetImage = (MySmartImageView) widgetView.findViewById(R.id.widgetimage);
    // Some of widgets, for example Frame doesnt' have an icon, so...
    if (widgetImage != null) {
        if (openHABWidget.getIcon() != null) {
            // This is needed to escape possible spaces and everything according to rfc2396
            String iconUrl = openHABBaseUrl + "images/" + Uri.encode(openHABWidget.getIcon() + ".png");
            //                Log.d(TAG, "Will try to load icon from " + iconUrl);
            // Now set image URL
            widgetImage.setImageUrl(iconUrl, R.drawable.blank_icon, openHABUsername, openHABPassword);
            if (iconColor != null)
                widgetImage.setColorFilter(iconColor);
            else
                widgetImage.clearColorFilter();
        }
    }
    TextView defaultTextView = new TextView(widgetView.getContext());
    // Get TextView for widget label and set it's color
    labelTextView = (TextView) widgetView.findViewById(R.id.widgetlabel);
    // Change label color only for non-frame widgets
    if (labelColor != null && labelTextView != null && this.getItemViewType(position) != TYPE_FRAME) {
        Log.d(TAG, String.format("Setting label color to %d", labelColor));
        labelTextView.setTextColor(labelColor);
    } else if (labelTextView != null && this.getItemViewType(position) != TYPE_FRAME)
        labelTextView.setTextColor(defaultTextView.getTextColors().getDefaultColor());
    // Get TextView for widget value and set it's color
    valueTextView = (TextView) widgetView.findViewById(R.id.widgetvalue);
    if (valueColor != null && valueTextView != null) {
        Log.d(TAG, String.format("Setting value color to %d", valueColor));
        valueTextView.setTextColor(valueColor);
    } else if (valueTextView != null)
        valueTextView.setTextColor(defaultTextView.getTextColors().getDefaultColor());
    defaultTextView = null;
    switch (getItemViewType(position)) {
    case TYPE_FRAME:
        if (labelTextView != null) {
            labelTextView.setText(openHABWidget.getLabel());
            if (valueColor != null)
                labelTextView.setTextColor(valueColor);
        }
        widgetView.setClickable(false);
        if (openHABWidget.getLabel().length() > 0) { // hide empty frames
            widgetView.setVisibility(View.VISIBLE);
            labelTextView.setVisibility(View.VISIBLE);
        } else {
            widgetView.setVisibility(View.GONE);
            labelTextView.setVisibility(View.GONE);
        }
        break;
    case TYPE_GROUP:
        if (labelTextView != null && valueTextView != null) {
            splitString = openHABWidget.getLabel().split("\\[|\\]");
            labelTextView.setText(splitString[0]);
            if (splitString.length > 1) { // We have some value
                valueTextView.setText(splitString[1]);
            } else {
                // This is needed to clean up cached TextViews
                valueTextView.setText("");
            }
        }
        break;
    case TYPE_SECTIONSWITCH:
        splitString = openHABWidget.getLabel().split("\\[|\\]");
        if (labelTextView != null)
            labelTextView.setText(splitString[0]);
        if (splitString.length > 1 && valueTextView != null) { // We have some value
            valueTextView.setText(splitString[1]);
        } else {
            // This is needed to clean up cached TextViews
            valueTextView.setText("");
        }
        RadioGroup sectionSwitchRadioGroup = (RadioGroup) widgetView.findViewById(R.id.sectionswitchradiogroup);
        // As we create buttons in this radio in runtime, we need to remove all
        // exiting buttons first
        sectionSwitchRadioGroup.removeAllViews();
        sectionSwitchRadioGroup.setTag(openHABWidget);
        Iterator<OpenHABWidgetMapping> sectionMappingIterator = openHABWidget.getMappings().iterator();
        while (sectionMappingIterator.hasNext()) {
            OpenHABWidgetMapping widgetMapping = sectionMappingIterator.next();
            SegmentedControlButton segmentedControlButton = (SegmentedControlButton) LayoutInflater
                    .from(sectionSwitchRadioGroup.getContext())
                    .inflate(R.layout.openhabwidgetlist_sectionswitchitem_button, sectionSwitchRadioGroup,
                            false);
            segmentedControlButton.setText(widgetMapping.getLabel());
            segmentedControlButton.setTag(widgetMapping.getCommand());
            if (openHABWidget.getItem() != null && widgetMapping.getCommand() != null) {
                if (widgetMapping.getCommand().equals(openHABWidget.getItem().getState())) {
                    segmentedControlButton.setChecked(true);
                } else {
                    segmentedControlButton.setChecked(false);
                }
            } else {
                segmentedControlButton.setChecked(false);
            }
            segmentedControlButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    Log.i(TAG, "Button clicked");
                    RadioGroup group = (RadioGroup) view.getParent();
                    if (group.getTag() != null) {
                        OpenHABWidget radioWidget = (OpenHABWidget) group.getTag();
                        SegmentedControlButton selectedButton = (SegmentedControlButton) view;
                        if (selectedButton.getTag() != null) {
                            sendItemCommand(radioWidget.getItem(), (String) selectedButton.getTag());
                        }
                    }
                }
            });
            sectionSwitchRadioGroup.addView(segmentedControlButton);
        }

        sectionSwitchRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                OpenHABWidget radioWidget = (OpenHABWidget) group.getTag();
                SegmentedControlButton selectedButton = (SegmentedControlButton) group.findViewById(checkedId);
                if (selectedButton != null) {
                    Log.d(TAG, "Selected " + selectedButton.getText());
                    Log.d(TAG, "Command = " + (String) selectedButton.getTag());
                    //                  radioWidget.getItem().sendCommand((String)selectedButton.getTag());
                    sendItemCommand(radioWidget.getItem(), (String) selectedButton.getTag());
                }
            }
        });
        break;
    case TYPE_SWITCH:
        if (labelTextView != null)
            labelTextView.setText(openHABWidget.getLabel());
        SwitchCompat switchSwitch = (SwitchCompat) widgetView.findViewById(R.id.switchswitch);
        if (openHABWidget.hasItem()) {
            if (openHABWidget.getItem().getStateAsBoolean()) {
                switchSwitch.setChecked(true);
            } else {
                switchSwitch.setChecked(false);
            }
        }
        switchSwitch.setTag(openHABWidget.getItem());
        switchSwitch.setOnTouchListener(new OnTouchListener() {
            public boolean onTouch(View v, MotionEvent motionEvent) {
                SwitchCompat switchSwitch = (SwitchCompat) v;
                OpenHABItem linkedItem = (OpenHABItem) switchSwitch.getTag();
                if (motionEvent.getActionMasked() == MotionEvent.ACTION_UP)
                    if (!switchSwitch.isChecked()) {
                        sendItemCommand(linkedItem, "ON");
                    } else {
                        sendItemCommand(linkedItem, "OFF");
                    }
                return false;
            }
        });
        break;
    case TYPE_COLOR:
        if (labelTextView != null)
            labelTextView.setText(openHABWidget.getLabel());
        ImageButton colorUpButton = (ImageButton) widgetView.findViewById(R.id.colorbutton_up);
        ImageButton colorDownButton = (ImageButton) widgetView.findViewById(R.id.colorbutton_down);
        ImageButton colorColorButton = (ImageButton) widgetView.findViewById(R.id.colorbutton_color);
        colorUpButton.setTag(openHABWidget.getItem());
        colorDownButton.setTag(openHABWidget.getItem());
        colorColorButton.setTag(openHABWidget.getItem());
        colorUpButton.setOnTouchListener(new OnTouchListener() {
            public boolean onTouch(View v, MotionEvent motionEvent) {
                ImageButton colorButton = (ImageButton) v;
                OpenHABItem colorItem = (OpenHABItem) colorButton.getTag();
                if (motionEvent.getActionMasked() == MotionEvent.ACTION_UP)
                    sendItemCommand(colorItem, "ON");
                return false;
            }
        });
        colorDownButton.setOnTouchListener(new OnTouchListener() {
            public boolean onTouch(View v, MotionEvent motionEvent) {
                ImageButton colorButton = (ImageButton) v;
                OpenHABItem colorItem = (OpenHABItem) colorButton.getTag();
                if (motionEvent.getActionMasked() == MotionEvent.ACTION_UP)
                    sendItemCommand(colorItem, "OFF");
                return false;
            }
        });
        colorColorButton.setOnTouchListener(new OnTouchListener() {
            public boolean onTouch(View v, MotionEvent motionEvent) {
                ImageButton colorButton = (ImageButton) v;
                OpenHABItem colorItem = (OpenHABItem) colorButton.getTag();
                if (colorItem != null) {
                    if (motionEvent.getActionMasked() == MotionEvent.ACTION_UP) {
                        Log.d(TAG, "Time to launch color picker!");
                        ColorPickerDialog colorDialog = new ColorPickerDialog(widgetView.getContext(),
                                new OnColorChangedListener() {
                                    public void colorChanged(float[] hsv, View v) {
                                        Log.d(TAG, "New color HSV = " + hsv[0] + ", " + hsv[1] + ", " + hsv[2]);
                                        String newColor = String.valueOf(hsv[0]) + ","
                                                + String.valueOf(hsv[1] * 100) + ","
                                                + String.valueOf(hsv[2] * 100);
                                        OpenHABItem colorItem = (OpenHABItem) v.getTag();
                                        sendItemCommand(colorItem, newColor);
                                    }
                                }, colorItem.getStateAsHSV());
                        colorDialog.setTag(colorItem);
                        colorDialog.show();
                    }
                }
                return false;
            }
        });
        break;
    case TYPE_ROLLERSHUTTER:
        if (labelTextView != null)
            labelTextView.setText(openHABWidget.getLabel());
        ImageButton rollershutterUpButton = (ImageButton) widgetView.findViewById(R.id.rollershutterbutton_up);
        ImageButton rollershutterStopButton = (ImageButton) widgetView
                .findViewById(R.id.rollershutterbutton_stop);
        ImageButton rollershutterDownButton = (ImageButton) widgetView
                .findViewById(R.id.rollershutterbutton_down);
        rollershutterUpButton.setTag(openHABWidget.getItem());
        rollershutterStopButton.setTag(openHABWidget.getItem());
        rollershutterDownButton.setTag(openHABWidget.getItem());
        rollershutterUpButton.setOnTouchListener(new OnTouchListener() {
            public boolean onTouch(View v, MotionEvent motionEvent) {
                ImageButton rollershutterButton = (ImageButton) v;
                OpenHABItem rollershutterItem = (OpenHABItem) rollershutterButton.getTag();
                if (motionEvent.getActionMasked() == MotionEvent.ACTION_UP)
                    sendItemCommand(rollershutterItem, "UP");
                return false;
            }
        });
        rollershutterStopButton.setOnTouchListener(new OnTouchListener() {
            public boolean onTouch(View v, MotionEvent motionEvent) {
                ImageButton rollershutterButton = (ImageButton) v;
                OpenHABItem rollershutterItem = (OpenHABItem) rollershutterButton.getTag();
                if (motionEvent.getActionMasked() == MotionEvent.ACTION_UP)
                    sendItemCommand(rollershutterItem, "STOP");
                return false;
            }
        });
        rollershutterDownButton.setOnTouchListener(new OnTouchListener() {
            public boolean onTouch(View v, MotionEvent motionEvent) {
                ImageButton rollershutterButton = (ImageButton) v;
                OpenHABItem rollershutterItem = (OpenHABItem) rollershutterButton.getTag();
                if (motionEvent.getActionMasked() == MotionEvent.ACTION_UP)
                    sendItemCommand(rollershutterItem, "DOWN");
                return false;
            }
        });
        break;
    case TYPE_TEXT:
        splitString = openHABWidget.getLabel().split("\\[|\\]");
        if (labelTextView != null)
            if (splitString.length > 0) {
                labelTextView.setText(splitString[0]);
            } else {
                labelTextView.setText(openHABWidget.getLabel());
            }
        if (valueTextView != null)
            if (splitString.length > 1) {
                // If value is not empty, show TextView
                valueTextView.setVisibility(View.VISIBLE);
                valueTextView.setText(splitString[1]);
            } else {
                // If value is empty, hide TextView to fix vertical alignment of label
                valueTextView.setVisibility(View.GONE);
                valueTextView.setText("");
            }
        break;
    case TYPE_SLIDER:
        splitString = openHABWidget.getLabel().split("\\[|\\]");
        if (labelTextView != null)
            labelTextView.setText(splitString[0]);
        SeekBar sliderSeekBar = (SeekBar) widgetView.findViewById(R.id.sliderseekbar);
        if (openHABWidget.hasItem()) {
            sliderSeekBar.setTag(openHABWidget.getItem());
            sliderSeekBar.setProgress(openHABWidget.getItem().getStateAsFloat().intValue());
            sliderSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                }

                public void onStartTrackingTouch(SeekBar seekBar) {
                    Log.d(TAG, "onStartTrackingTouch position = " + seekBar.getProgress());
                }

                public void onStopTrackingTouch(SeekBar seekBar) {
                    Log.d(TAG, "onStopTrackingTouch position = " + seekBar.getProgress());
                    OpenHABItem sliderItem = (OpenHABItem) seekBar.getTag();
                    //                     sliderItem.sendCommand(String.valueOf(seekBar.getProgress()));
                    if (sliderItem != null && seekBar != null)
                        sendItemCommand(sliderItem, String.valueOf(seekBar.getProgress()));
                }
            });
            if (volumeUpWidget == null) {
                volumeUpWidget = sliderSeekBar;
                volumeDownWidget = sliderSeekBar;
            }
        }
        break;
    case TYPE_IMAGE:
        MySmartImageView imageImage = (MySmartImageView) widgetView.findViewById(R.id.imageimage);
        imageImage.setImageUrl(ensureAbsoluteURL(openHABBaseUrl, openHABWidget.getUrl()), false,
                openHABUsername, openHABPassword);
        //          ViewGroup.LayoutParams imageLayoutParams = imageImage.getLayoutParams();
        //          float imageRatio = imageImage.getDrawable().getIntrinsicWidth()/imageImage.getDrawable().getIntrinsicHeight();
        //          imageLayoutParams.height = (int) (screenWidth/imageRatio);
        //          imageImage.setLayoutParams(imageLayoutParams);
        if (openHABWidget.getRefresh() > 0) {
            imageImage.setRefreshRate(openHABWidget.getRefresh());
            refreshImageList.add(imageImage);
        }
        break;
    case TYPE_CHART:
        MySmartImageView chartImage = (MySmartImageView) widgetView.findViewById(R.id.chartimage);
        //Always clear the drawable so no images from recycled views appear
        chartImage.setImageDrawable(null);
        OpenHABItem chartItem = openHABWidget.getItem();
        Random random = new Random();
        String chartUrl = "";
        if (chartItem != null) {
            if (chartItem.getType().equals("GroupItem")) {
                chartUrl = openHABBaseUrl + "chart?groups=" + chartItem.getName() + "&period="
                        + openHABWidget.getPeriod() + "&random=" + String.valueOf(random.nextInt());
            } else {
                chartUrl = openHABBaseUrl + "chart?items=" + chartItem.getName() + "&period="
                        + openHABWidget.getPeriod() + "&random=" + String.valueOf(random.nextInt());
            }
            if (openHABWidget.getService() != null && openHABWidget.getService().length() > 0) {
                chartUrl += "&service=" + openHABWidget.getService();
            }
        }
        Log.d(TAG, "Chart url = " + chartUrl);
        if (chartImage == null)
            Log.e(TAG, "chartImage == null !!!");
        ViewGroup.LayoutParams chartLayoutParams = chartImage.getLayoutParams();
        chartLayoutParams.height = (int) (screenWidth / 2);
        chartImage.setLayoutParams(chartLayoutParams);
        chartUrl += "&w=" + String.valueOf(screenWidth);
        chartUrl += "&h=" + String.valueOf(screenWidth / 2);
        chartImage.setImageUrl(chartUrl, false, openHABUsername, openHABPassword);
        // TODO: This is quite dirty fix to make charts look full screen width on all displays
        if (openHABWidget.getRefresh() > 0) {
            chartImage.setRefreshRate(openHABWidget.getRefresh());
            refreshImageList.add(chartImage);
        }
        Log.d(TAG, "chart size = " + chartLayoutParams.width + " " + chartLayoutParams.height);
        break;
    case TYPE_VIDEO:
        VideoView videoVideo = (VideoView) widgetView.findViewById(R.id.videovideo);
        Log.d(TAG, "Opening video at " + openHABWidget.getUrl());
        // TODO: This is quite dirty fix to make video look maximum available size on all screens
        WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
        ViewGroup.LayoutParams videoLayoutParams = videoVideo.getLayoutParams();
        videoLayoutParams.height = (int) (wm.getDefaultDisplay().getWidth() / 1.77);
        videoVideo.setLayoutParams(videoLayoutParams);
        // We don't have any event handler to know if the VideoView is on the screen
        // so we manage an array of all videos to stop them when user leaves the page
        if (!videoWidgetList.contains(videoVideo))
            videoWidgetList.add(videoVideo);
        // Start video
        if (!videoVideo.isPlaying()) {
            videoVideo.setVideoURI(Uri.parse(openHABWidget.getUrl()));
            videoVideo.start();
        }
        Log.d(TAG, "Video height is " + videoVideo.getHeight());
        break;
    case TYPE_VIDEO_MJPEG:
        Log.d(TAG, "Video is mjpeg");
        ImageView mjpegImage = (ImageView) widgetView.findViewById(R.id.mjpegimage);
        MjpegStreamer mjpegStreamer = new MjpegStreamer(openHABWidget.getUrl(), this.openHABUsername,
                this.openHABPassword, this.getContext());
        mjpegStreamer.setTargetImageView(mjpegImage);
        mjpegStreamer.start();
        if (!mjpegWidgetList.contains(mjpegStreamer))
            mjpegWidgetList.add(mjpegStreamer);
        break;
    case TYPE_WEB:
        WebView webWeb = (WebView) widgetView.findViewById(R.id.webweb);
        if (openHABWidget.getHeight() > 0) {
            ViewGroup.LayoutParams webLayoutParams = webWeb.getLayoutParams();
            webLayoutParams.height = openHABWidget.getHeight() * 80;
            webWeb.setLayoutParams(webLayoutParams);
        }
        webWeb.setWebViewClient(
                new AnchorWebViewClient(openHABWidget.getUrl(), this.openHABUsername, this.openHABPassword));
        webWeb.getSettings().setJavaScriptEnabled(true);
        webWeb.loadUrl(openHABWidget.getUrl());
        break;
    case TYPE_SELECTION:
        int spinnerSelectedIndex = -1;
        if (labelTextView != null)
            labelTextView.setText(openHABWidget.getLabel());
        final Spinner selectionSpinner = (Spinner) widgetView.findViewById(R.id.selectionspinner);
        selectionSpinner.setOnItemSelectedListener(null);
        ArrayList<String> spinnerArray = new ArrayList<String>();
        Iterator<OpenHABWidgetMapping> mappingIterator = openHABWidget.getMappings().iterator();
        while (mappingIterator.hasNext()) {
            OpenHABWidgetMapping openHABWidgetMapping = mappingIterator.next();
            spinnerArray.add(openHABWidgetMapping.getLabel());
            if (openHABWidgetMapping.getCommand() != null && openHABWidget.getItem() != null)
                if (openHABWidgetMapping.getCommand().equals(openHABWidget.getItem().getState())) {
                    spinnerSelectedIndex = spinnerArray.size() - 1;
                }
        }
        ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this.getContext(),
                android.R.layout.simple_spinner_item, spinnerArray);
        spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        selectionSpinner.setAdapter(spinnerAdapter);
        selectionSpinner.setTag(openHABWidget);
        if (spinnerSelectedIndex >= 0) {
            Log.d(TAG, "Setting spinner selected index to " + String.valueOf(spinnerSelectedIndex));
            selectionSpinner.setSelection(spinnerSelectedIndex);
        } else {
            Log.d(TAG, "Not setting spinner selected index");
        }
        selectionSpinner.post(new Runnable() {
            @Override
            public void run() {
                selectionSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
                    public void onItemSelected(AdapterView<?> parent, View view, int index, long id) {
                        Log.d(TAG, "Spinner item click on index " + index);
                        Spinner spinner = (Spinner) parent;
                        String selectedLabel = (String) spinner.getAdapter().getItem(index);
                        Log.d(TAG, "Spinner onItemSelected selected label = " + selectedLabel);
                        OpenHABWidget openHABWidget = (OpenHABWidget) parent.getTag();
                        if (openHABWidget != null) {
                            Log.d(TAG, "Label selected = " + openHABWidget.getMapping(index).getLabel());
                            Iterator<OpenHABWidgetMapping> mappingIterator = openHABWidget.getMappings()
                                    .iterator();
                            while (mappingIterator.hasNext()) {
                                OpenHABWidgetMapping openHABWidgetMapping = mappingIterator.next();
                                if (openHABWidgetMapping.getLabel().equals(selectedLabel)) {
                                    Log.d(TAG, "Spinner onItemSelected found match with "
                                            + openHABWidgetMapping.getCommand());
                                    if (openHABWidget.getItem() != null
                                            && openHABWidget.getItem().getState() != null) {
                                        // Only send the command for selection of selected command will change the state
                                        if (!openHABWidget.getItem().getState()
                                                .equals(openHABWidgetMapping.getCommand())) {
                                            Log.d(TAG,
                                                    "Spinner onItemSelected selected label command != current item state");
                                            sendItemCommand(openHABWidget.getItem(),
                                                    openHABWidgetMapping.getCommand());
                                        }
                                    } else if (openHABWidget.getItem() != null
                                            && openHABWidget.getItem().getState() == null) {
                                        Log.d(TAG,
                                                "Spinner onItemSelected selected label command and state == null");
                                        sendItemCommand(openHABWidget.getItem(),
                                                openHABWidgetMapping.getCommand());
                                    }
                                }
                            }
                        }
                        //               if (!openHABWidget.getItem().getState().equals(openHABWidget.getMapping(index).getCommand()))
                        //                  sendItemCommand(openHABWidget.getItem(),
                        //                        openHABWidget.getMapping(index).getCommand());
                    }

                    public void onNothingSelected(AdapterView<?> arg0) {
                    }
                });
            }
        });
        break;
    case TYPE_SETPOINT:
        splitString = openHABWidget.getLabel().split("\\[|\\]");
        if (labelTextView != null)
            labelTextView.setText(splitString[0]);
        if (valueTextView != null)
            if (splitString.length > 1) {
                // If value is not empty, show TextView
                valueTextView.setVisibility(View.VISIBLE);
                valueTextView.setText(splitString[1]);
            }
        Button setPointMinusButton = (Button) widgetView.findViewById(R.id.setpointbutton_minus);
        Button setPointPlusButton = (Button) widgetView.findViewById(R.id.setpointbutton_plus);
        setPointMinusButton.setTag(openHABWidget);
        setPointPlusButton.setTag(openHABWidget);
        setPointMinusButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                Log.d(TAG, "Minus");
                OpenHABWidget setPointWidget = (OpenHABWidget) v.getTag();
                float currentValue = setPointWidget.getItem().getStateAsFloat();
                currentValue = currentValue - setPointWidget.getStep();
                if (currentValue < setPointWidget.getMinValue())
                    currentValue = setPointWidget.getMinValue();
                if (currentValue > setPointWidget.getMaxValue())
                    currentValue = setPointWidget.getMaxValue();
                sendItemCommand(setPointWidget.getItem(), String.valueOf(currentValue));

            }
        });
        setPointPlusButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                Log.d(TAG, "Plus");
                OpenHABWidget setPointWidget = (OpenHABWidget) v.getTag();
                float currentValue = setPointWidget.getItem().getStateAsFloat();
                currentValue = currentValue + setPointWidget.getStep();
                if (currentValue < setPointWidget.getMinValue())
                    currentValue = setPointWidget.getMinValue();
                if (currentValue > setPointWidget.getMaxValue())
                    currentValue = setPointWidget.getMaxValue();
                sendItemCommand(setPointWidget.getItem(), String.valueOf(currentValue));
            }
        });
        if (volumeUpWidget == null) {
            volumeUpWidget = setPointPlusButton;
            volumeDownWidget = setPointMinusButton;
        }
        break;
    default:
        if (labelTextView != null)
            labelTextView.setText(openHABWidget.getLabel());
        break;
    }
    LinearLayout dividerLayout = (LinearLayout) widgetView.findViewById(R.id.listdivider);
    if (dividerLayout != null) {
        if (position < this.getCount() - 1) {
            if (this.getItemViewType(position + 1) == TYPE_FRAME) {
                dividerLayout.setVisibility(View.GONE); // hide dividers before frame widgets
            } else {
                dividerLayout.setVisibility(View.VISIBLE); // show dividers for all others
            }
        } else { // last widget in the list, hide divider
            dividerLayout.setVisibility(View.GONE);
        }
    }
    return widgetView;
}

From source file:org.onebusaway.android.ui.TripPlanFragment.java

private void advancedSettings() {

    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getActivity());

    final TypedArray transitModeResource = getContext().getResources()
            .obtainTypedArray(R.array.transit_mode_array);
    final boolean unitsAreImperial = !PreferenceUtils.getUnitsAreMetricFromPreferences(getContext());

    dialogBuilder.setTitle(R.string.trip_plan_advanced_settings)
            .setView(R.layout.trip_plan_advanced_settings_dialog);

    dialogBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
        @Override//from w  w w. j ava 2  s. c  om
        public void onClick(DialogInterface dialogInterface, int which) {

            Dialog dialog = (Dialog) dialogInterface;

            boolean optimizeTransfers = ((CheckBox) dialog.findViewById(R.id.checkbox_minimize_transfers))
                    .isChecked();

            Spinner spinnerTravelBy = (Spinner) dialog.findViewById(R.id.spinner_travel_by);

            int modeId = transitModeResource.getResourceId(spinnerTravelBy.getSelectedItemPosition(), 0);

            boolean wheelchair = ((CheckBox) dialog.findViewById(R.id.checkbox_wheelchair_acccesible))
                    .isChecked();

            String maxWalkString = ((EditText) dialog.findViewById(R.id.number_maximum_walk_distance)).getText()
                    .toString();
            double maxWalkDistance;
            if (TextUtils.isEmpty(maxWalkString)) {
                maxWalkDistance = Double.MAX_VALUE;
            } else {
                double d = Double.parseDouble(maxWalkString);
                maxWalkDistance = unitsAreImperial ? ConversionUtils.feetToMeters(d) : d;
            }

            mBuilder.setOptimizeTransfers(optimizeTransfers).setModeSetById(modeId)
                    .setWheelchairAccessible(wheelchair).setMaxWalkDistance(maxWalkDistance);

            checkRequestAndSubmit();
        }
    });

    final AlertDialog dialog = dialogBuilder.create();

    dialog.show();

    CheckBox minimizeTransfersCheckbox = (CheckBox) dialog.findViewById(R.id.checkbox_minimize_transfers);
    Spinner spinnerTravelBy = (Spinner) dialog.findViewById(R.id.spinner_travel_by);
    CheckBox wheelchairCheckbox = (CheckBox) dialog.findViewById(R.id.checkbox_wheelchair_acccesible);
    EditText maxWalkEditText = (EditText) dialog.findViewById(R.id.number_maximum_walk_distance);

    minimizeTransfersCheckbox.setChecked(mBuilder.getOptimizeTransfers());

    wheelchairCheckbox.setChecked(mBuilder.getWheelchairAccessible());

    ArrayAdapter adapter = ArrayAdapter.createFromResource(getActivity(), R.array.transit_mode_array,
            android.R.layout.simple_spinner_item);

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

    int modeSetId = mBuilder.getModeSetId();
    if (modeSetId != -1) {
        for (int i = 0; i < transitModeResource.length(); i++) {
            if (transitModeResource.getResourceId(i, -1) == modeSetId) {
                spinnerTravelBy.setSelection(i);
                break;
            }
        }
    }

    Double maxWalk = mBuilder.getMaxWalkDistance();
    if (maxWalk != null && Double.MAX_VALUE != maxWalk) {
        if (unitsAreImperial) {
            maxWalk = ConversionUtils.metersToFeet(maxWalk);
        }
        maxWalkEditText.setText(String.format("%d", maxWalk.longValue()));
    }

    if (unitsAreImperial) {
        TextView label = (TextView) dialog.findViewById(R.id.label_minimum_walk_distance);
        label.setText(getString(R.string.feet_abbreviation));
    }
}

From source file:de.schildbach.wallet.ui.WalletActivity.java

private Dialog createRestoreWalletDialog() {
    final View view = getLayoutInflater().inflate(R.layout.restore_wallet_dialog, null);
    final Spinner fileView = (Spinner) view.findViewById(R.id.import_keys_from_storage_file);
    final EditText passwordView = (EditText) view.findViewById(R.id.import_keys_from_storage_password);

    final DialogBuilder dialog = new DialogBuilder(this);
    dialog.setTitle(R.string.import_keys_dialog_title);
    dialog.setView(view);//w w w . ja  va  2s .c  om
    dialog.setPositiveButton(R.string.import_keys_dialog_button_import, new OnClickListener() {
        @Override
        public void onClick(final DialogInterface dialog, final int which) {
            final File file = (File) fileView.getSelectedItem();
            final String password = passwordView.getText().toString().trim();
            passwordView.setText(null); // get rid of it asap

            if (WalletUtils.BACKUP_FILE_FILTER.accept(file))
                restoreWalletFromProtobuf(file);
            else if (WalletUtils.KEYS_FILE_FILTER.accept(file))
                restorePrivateKeysFromBase58(file);
            else if (Crypto.OPENSSL_FILE_FILTER.accept(file))
                restoreWalletFromEncrypted(file, password);
        }
    });
    dialog.setNegativeButton(R.string.button_cancel, new OnClickListener() {
        @Override
        public void onClick(final DialogInterface dialog, final int which) {
            passwordView.setText(null); // get rid of it asap
        }
    });
    dialog.setOnCancelListener(new OnCancelListener() {
        @Override
        public void onCancel(final DialogInterface dialog) {
            passwordView.setText(null); // get rid of it asap
        }
    });

    fileView.setAdapter(new FileAdapter(this) {
        @Override
        public View getDropDownView(final int position, View row, final ViewGroup parent) {
            final File file = getItem(position);
            final boolean isExternal = Constants.Files.EXTERNAL_WALLET_BACKUP_DIR.equals(file.getParentFile());
            final boolean isEncrypted = Crypto.OPENSSL_FILE_FILTER.accept(file);

            if (row == null)
                row = inflater.inflate(R.layout.restore_wallet_file_row, null);

            final TextView filenameView = (TextView) row
                    .findViewById(R.id.wallet_import_keys_file_row_filename);
            filenameView.setText(file.getName());

            final TextView securityView = (TextView) row
                    .findViewById(R.id.wallet_import_keys_file_row_security);
            final String encryptedStr = context
                    .getString(isEncrypted ? R.string.import_keys_dialog_file_security_encrypted
                            : R.string.import_keys_dialog_file_security_unencrypted);
            final String storageStr = context
                    .getString(isExternal ? R.string.import_keys_dialog_file_security_external
                            : R.string.import_keys_dialog_file_security_internal);
            securityView.setText(encryptedStr + ", " + storageStr);

            final TextView createdView = (TextView) row.findViewById(R.id.wallet_import_keys_file_row_created);
            createdView.setText(context.getString(
                    isExternal ? R.string.import_keys_dialog_file_created_manual
                            : R.string.import_keys_dialog_file_created_automatic,
                    DateUtils.getRelativeTimeSpanString(context, file.lastModified(), true)));

            return row;
        }
    });

    return dialog.create();
}

From source file:com.normalexception.app.rx8club.dialog.MoveThreadDialog.java

/**
 * Constructor for method that is used to move a thread from one
 * forum to another   //from  w  ww  .ja v  a  2s. co  m
 * @param ctx         The source context/activity   
 * @param securitytoken   The security token for the session
 * @param src_thread   The source thread
 * @param tTitle      The new thread title
 * @param options      The options from the move dialog
 */
public MoveThreadDialog(final Fragment ctx, final String securitytoken, final String src_thread, String tTitle,
        final Map<String, Integer> options) {
    builder = new AlertDialog.Builder(ctx.getActivity());

    // Set up the input
    final TextView lbl_title = new TextView(ctx.getActivity());
    final EditText title = new EditText(ctx.getActivity());
    final TextView lbl_dest = new TextView(ctx.getActivity());
    final Spinner destination = new Spinner(ctx.getActivity());

    // Lets make sure the user didn't accidentally click this
    DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            switch (which) {
            case DialogInterface.BUTTON_POSITIVE:
                newTitle = title.getText().toString();
                String selectText = destination.getSelectedItem().toString();
                selection = options.get(selectText);

                AsyncTask<Void, String, Void> updaterTask = new AsyncTask<Void, String, Void>() {
                    @Override
                    protected Void doInBackground(Void... params) {
                        try {
                            HtmlFormUtils.adminMoveThread(securitytoken, src_thread, newTitle,
                                    Integer.toString(selection));
                        } catch (Exception e) {
                            Log.e(TAG, "Error Submitting Form For Move", e);
                        }
                        return null;
                    }

                    @Override
                    protected void onPostExecute(Void result) {
                        ctx.getFragmentManager().popBackStack();
                        CategoryFragment cFrag = (CategoryFragment) ((ThreadFragment) ctx).getParentCategory();
                        cFrag.refreshView();
                    }
                };
                updaterTask.execute();
                break;
            case DialogInterface.BUTTON_NEGATIVE:
                break;
            }
        }
    };

    // Specify the type of input expected
    lbl_title.setText("Thread Title");
    lbl_title.setTextColor(Color.WHITE);
    lbl_dest.setText("Desination");
    lbl_dest.setTextColor(Color.WHITE);
    title.setInputType(InputType.TYPE_CLASS_TEXT);
    title.setText(tTitle);

    List<String> values = new ArrayList<String>();
    values.addAll(options.keySet());

    ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(ctx.getActivity(),
            android.R.layout.simple_spinner_item, values);
    dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    destination.setAdapter(dataAdapter);

    LinearLayout ll = new LinearLayout(ctx.getActivity());
    ll.setOrientation(LinearLayout.VERTICAL);
    ll.addView(lbl_title);
    ll.addView(title);
    ll.addView(lbl_dest);
    ll.addView(destination);

    builder.setView(ll);

    builder.setTitle(R.string.dialogMoveThread).setPositiveButton(R.string.Move, dialogClickListener)
            .setNegativeButton(R.string.cancel, dialogClickListener);
}

From source file:usbong.android.utils.UsbongScreenProcessor.java

public void init() {
    //Reference: http://www.anddev.org/tinytut_-_get_resources_by_name__getidentifier_-t460.html; last accessed 14 Sept 2011
    Resources myRes = udtea.getResources();
    Drawable myDrawableImage;//  w w  w  .jav a2s .  co  m

    //added by Mike, Feb. 13, 2013
    udtea.isAnOptionalNode = UsbongUtils.isAnOptionalNode(udtea.currUsbongNode);

    String myStringToken = "";
    //      if (usedBackButton) {

    //        System.out.println(">>>>>> udtea.currAnswer: "+udtea.currAnswer);

    StringTokenizer st = new StringTokenizer(udtea.currAnswer, ",");
    if ((st != null) && (st.hasMoreTokens())) {
        myStringToken = st.nextToken();
        udtea.currAnswer = udtea.currAnswer.replace(myStringToken + ",", "");
    }

    StringTokenizer st_two = new StringTokenizer(udtea.currAnswer, ";");

    if (st_two != null) {
        if (udtea.currAnswer.length() > 1) {
            myStringToken = st_two.nextToken(); //get next element (i.e. 1 in "Y,1;")                
        } else {
            myStringToken = "";
        }
    }

    if (udtea.currScreen == udtea.MULTIPLE_RADIO_BUTTONS_SCREEN) {
        udtea.setContentView(R.layout.multiple_radio_buttons_screen);
        udtea.initBackNextButtons();
        TextView myMultipleRadioButtonsScreenTextView = (TextView) udtea
                .findViewById(R.id.radio_buttons_textview);
        myMultipleRadioButtonsScreenTextView = (TextView) UsbongUtils.applyTagsInView(
                UsbongDecisionTreeEngineActivity.getInstance(), myMultipleRadioButtonsScreenTextView,
                UsbongUtils.IS_TEXTVIEW, udtea.currUsbongNode);
        RadioGroup radioGroup = (RadioGroup) udtea.findViewById(R.id.multiple_radio_buttons_radiogroup);
        int totalRadioButtonsInContainer = udtea.radioButtonsContainer.size();
        for (int i = 0; i < totalRadioButtonsInContainer; i++) {
            View radioButtonView = new RadioButton(udtea.getBaseContext());
            RadioButton radioButton = (RadioButton) UsbongUtils.applyTagsInView(
                    UsbongDecisionTreeEngineActivity.getInstance(), radioButtonView, UsbongUtils.IS_RADIOBUTTON,
                    udtea.radioButtonsContainer.elementAt(i).toString());
            radioButton.setTextSize(20);
            radioButton.setId(i);
            radioButton.setTextColor(Color.parseColor("#4a452a"));

            int myStringTokenInt;
            try {
                myStringTokenInt = Integer.parseInt(myStringToken);
            } catch (NumberFormatException e) {//if myStringToken is not an int;
                myStringTokenInt = -1;
            }

            if ((!myStringToken.equals("")) && (i == myStringTokenInt)) {
                radioButton.setChecked(true);
            } else {
                radioButton.setChecked(false);
            }

            radioGroup.addView(radioButton);
        }
    } else if (udtea.currScreen == udtea.MULTIPLE_RADIO_BUTTONS_WITH_ANSWER_SCREEN) {
        udtea.setContentView(R.layout.multiple_radio_buttons_screen);
        udtea.initBackNextButtons();
        String myMultipleRadioButtonsWithAnswerScreenStringToken = "";
        //             Log.d(">>>>>>>>udtea.currUsbongNode", udtea.currUsbongNode);
        udtea.currUsbongNodeWithoutAnswer = udtea.currUsbongNode.replace("Answer=", "~");
        StringTokenizer myMultipleRadioButtonsWithAnswerScreenStringTokenizer = new StringTokenizer(
                udtea.currUsbongNodeWithoutAnswer, "~");
        if (myMultipleRadioButtonsWithAnswerScreenStringTokenizer != null) {
            myMultipleRadioButtonsWithAnswerScreenStringToken = myMultipleRadioButtonsWithAnswerScreenStringTokenizer
                    .nextToken();

            while (myMultipleRadioButtonsWithAnswerScreenStringTokenizer.hasMoreTokens()) { //get last element (i.e. 0 in "radioButtonsWithAnswer~You see your teacher approaching you. What do you do?Answer=0")
                myMultipleRadioButtonsWithAnswerScreenStringToken = myMultipleRadioButtonsWithAnswerScreenStringTokenizer
                        .nextToken();
            }
        }
        udtea.myMultipleRadioButtonsWithAnswerScreenAnswer = myMultipleRadioButtonsWithAnswerScreenStringToken
                .toString();
        //             Log.d(">>>>>>>>udtea.myMultipleRadioButtonsWithAnswerScreenAnswer", udtea.myMultipleRadioButtonsWithAnswerScreenAnswer);
        udtea.currUsbongNodeWithoutAnswer = udtea.currUsbongNodeWithoutAnswer.substring(0,
                udtea.currUsbongNodeWithoutAnswer.length()
                        - udtea.myMultipleRadioButtonsWithAnswerScreenAnswer.length() - 1); //do a -1 for the last tilde             
        //             Log.d(">>>>>>>>udtea.currUsbongNodeWithoutAnswer", udtea.currUsbongNodeWithoutAnswer);
        TextView myMultipleRadioButtonsWithAnswerScreenTextView = (TextView) udtea
                .findViewById(R.id.radio_buttons_textview);
        myMultipleRadioButtonsWithAnswerScreenTextView = (TextView) UsbongUtils.applyTagsInView(
                UsbongDecisionTreeEngineActivity.getInstance(), myMultipleRadioButtonsWithAnswerScreenTextView,
                UsbongUtils.IS_TEXTVIEW, udtea.currUsbongNodeWithoutAnswer);
        RadioGroup myMultipleRadioButtonsWithAnswerRadioGroup = (RadioGroup) udtea
                .findViewById(R.id.multiple_radio_buttons_radiogroup);
        int myMultipleRadioButtonsWithAnswerTotalRadioButtonsInContainer = udtea.radioButtonsContainer.size();
        for (int i = 0; i < myMultipleRadioButtonsWithAnswerTotalRadioButtonsInContainer; i++) {
            View radioButtonView = new RadioButton(udtea.getBaseContext());
            RadioButton radioButton = (RadioButton) UsbongUtils.applyTagsInView(
                    UsbongDecisionTreeEngineActivity.getInstance(), radioButtonView, UsbongUtils.IS_RADIOBUTTON,
                    udtea.radioButtonsContainer.elementAt(i).toString());
            radioButton.setTextSize(20);
            radioButton.setId(i);
            radioButton.setTextColor(Color.parseColor("#4a452a"));

            if ((!myStringToken.equals("")) && (i == Integer.parseInt(myStringToken))) {
                radioButton.setChecked(true);
            } else {
                radioButton.setChecked(false);
            }

            myMultipleRadioButtonsWithAnswerRadioGroup.addView(radioButton);
        }
    } else if (udtea.currScreen == udtea.LINK_SCREEN) {
        //use same contentView as multiple_radio_buttons_screen
        udtea.setContentView(R.layout.multiple_radio_buttons_screen);
        udtea.initBackNextButtons();
        TextView myLinkScreenTextView = (TextView) udtea.findViewById(R.id.radio_buttons_textview);
        myLinkScreenTextView = (TextView) UsbongUtils.applyTagsInView(
                UsbongDecisionTreeEngineActivity.getInstance(), myLinkScreenTextView, UsbongUtils.IS_TEXTVIEW,
                udtea.currUsbongNode);

        RadioGroup myLinkScreenRadioGroup = (RadioGroup) udtea
                .findViewById(R.id.multiple_radio_buttons_radiogroup);
        int myLinkScreenTotalRadioButtonsInContainer = udtea.radioButtonsContainer.size();
        for (int i = 0; i < myLinkScreenTotalRadioButtonsInContainer; i++) {
            View radioButtonView = new RadioButton(udtea.getBaseContext());
            RadioButton radioButton = (RadioButton) UsbongUtils.applyTagsInView(
                    UsbongDecisionTreeEngineActivity.getInstance(), radioButtonView, UsbongUtils.IS_RADIOBUTTON,
                    UsbongUtils.trimUsbongNodeName(udtea.radioButtonsContainer.elementAt(i).toString()));

            Log.d(">>>>>radioButton", radioButton.getText().toString());

            //                  radioButton.setChecked(false);
            radioButton.setTextSize(20);
            radioButton.setId(i);
            radioButton.setTextColor(Color.parseColor("#4a452a"));

            if ((!myStringToken.equals("")) && (i == Integer.parseInt(myStringToken))) {
                radioButton.setChecked(true);
            } else {
                radioButton.setChecked(false);
            }

            myLinkScreenRadioGroup.addView(radioButton);
        }
    } else if (udtea.currScreen == udtea.MULTIPLE_CHECKBOXES_SCREEN) {
        udtea.setContentView(R.layout.multiple_checkboxes_screen);
        udtea.initBackNextButtons();
        TextView myMultipleCheckBoxesScreenTextView = (TextView) udtea.findViewById(R.id.checkboxes_textview);
        myMultipleCheckBoxesScreenTextView = (TextView) UsbongUtils.applyTagsInView(
                UsbongDecisionTreeEngineActivity.getInstance(), myMultipleCheckBoxesScreenTextView,
                UsbongUtils.IS_TEXTVIEW, udtea.currUsbongNode);
        LinearLayout myMultipleCheckboxesLinearLayout = (LinearLayout) udtea
                .findViewById(R.id.multiple_checkboxes_linearlayout);
        int totalCheckBoxesInContainer = udtea.checkBoxesContainer.size();
        StringTokenizer myMultipleCheckboxStringTokenizer = new StringTokenizer(myStringToken, ",");
        Vector<String> myCheckedAnswers = new Vector<String>();
        //             int counter=0;             
        while (myMultipleCheckboxStringTokenizer.countTokens() > 0) {
            String myMultipleCheckboxStringToken = myMultipleCheckboxStringTokenizer.nextToken();
            if (myMultipleCheckboxStringToken != null) {
                myCheckedAnswers.add(myMultipleCheckboxStringToken);
            } else {
                break;
            }
            //                counter++;
        }
        for (int i = 0; i < totalCheckBoxesInContainer; i++) {
            CheckBox checkBox = new CheckBox(udtea.getBaseContext());
            //                  checkBox.setText(StringEscapeUtils.unescapeJava(udtea.checkBoxesContainer.elementAt(i).toString()));
            checkBox = (CheckBox) UsbongUtils.applyTagsInView(UsbongDecisionTreeEngineActivity.getInstance(),
                    checkBox, UsbongUtils.IS_CHECKBOX,
                    StringEscapeUtils.unescapeJava(udtea.checkBoxesContainer.elementAt(i).toString()));

            for (int k = 0; k < myCheckedAnswers.size(); k++) {
                try {
                    if (i == Integer.parseInt(myCheckedAnswers.elementAt(k))) {
                        checkBox.setChecked(true);
                    }
                } catch (NumberFormatException e) {//if myCheckedAnswers.elementAt(k) is not an int;
                    continue;
                }
            }

            checkBox.setTextSize(20);
            checkBox.setTextColor(Color.parseColor("#4a452a"));
            myMultipleCheckboxesLinearLayout.addView(checkBox);
        }
    } else if (udtea.currScreen == udtea.AUDIO_RECORD_SCREEN) {
        udtea.setContentView(R.layout.audio_recorder_screen);
        udtea.initRecordAudioScreen();
        udtea.initBackNextButtons();
        TextView myAudioRecorderTextView = (TextView) udtea.findViewById(R.id.audio_recorder_textview);
        myAudioRecorderTextView = (TextView) UsbongUtils.applyTagsInView(
                UsbongDecisionTreeEngineActivity.getInstance(), myAudioRecorderTextView,
                UsbongUtils.IS_TEXTVIEW, udtea.currUsbongNode);
        Button recordButton = (Button) udtea.findViewById(R.id.record_button);
        Button stopButton = (Button) udtea.findViewById(R.id.stop_button);
        Button playButton = (Button) udtea.findViewById(R.id.play_button);
        if (udtea.currLanguageBeingUsed == UsbongUtils.LANGUAGE_FILIPINO) {
            recordButton.setText((String) udtea.getResources().getText(R.string.UsbongRecordTextViewFILIPINO));
            stopButton.setText((String) udtea.getResources().getText(R.string.UsbongStopTextViewFILIPINO));
            playButton.setText((String) udtea.getResources().getText(R.string.UsbongPlayTextViewFILIPINO));
        } else if (udtea.currLanguageBeingUsed == UsbongUtils.LANGUAGE_JAPANESE) {
            recordButton.setText((String) udtea.getResources().getText(R.string.UsbongRecordTextViewJAPANESE));
            stopButton.setText((String) udtea.getResources().getText(R.string.UsbongStopTextViewJAPANESE));
            playButton.setText((String) udtea.getResources().getText(R.string.UsbongPlayTextViewJAPANESE));
        } else { //if (udtea.currLanguageBeingUsed==UsbongUtils.LANGUAGE_ENGLISH) {
            recordButton.setText((String) udtea.getResources().getText(R.string.UsbongRecordTextViewENGLISH));
            stopButton.setText((String) udtea.getResources().getText(R.string.UsbongStopTextViewENGLISH));
            playButton.setText((String) udtea.getResources().getText(R.string.UsbongPlayTextViewENGLISH));
        }
    } else if (udtea.currScreen == udtea.PHOTO_CAPTURE_SCREEN) {
        udtea.setContentView(R.layout.photo_capture_screen);
        if (!udtea.performedCapturePhoto) {
            udtea.initTakePhotoScreen();
        }
        udtea.initBackNextButtons();
        TextView myPhotoCaptureScreenTextView = (TextView) udtea.findViewById(R.id.photo_capture_textview);
        myPhotoCaptureScreenTextView = (TextView) UsbongUtils.applyTagsInView(
                UsbongDecisionTreeEngineActivity.getInstance(), myPhotoCaptureScreenTextView,
                UsbongUtils.IS_TEXTVIEW, udtea.currUsbongNode);
        Button photoCaptureButton = (Button) udtea.findViewById(R.id.photo_capture_button);
        if (udtea.currLanguageBeingUsed == UsbongUtils.LANGUAGE_FILIPINO) {
            photoCaptureButton
                    .setText((String) udtea.getResources().getText(R.string.UsbongTakePhotoTextViewFILIPINO));
        } else if (udtea.currLanguageBeingUsed == UsbongUtils.LANGUAGE_JAPANESE) {
            photoCaptureButton
                    .setText((String) udtea.getResources().getText(R.string.UsbongTakePhotoTextViewJAPANESE));
        } else { //if (udtea.currLanguageBeingUsed==UsbongUtils.LANGUAGE_ENGLISH) {
            photoCaptureButton
                    .setText((String) udtea.getResources().getText(R.string.UsbongTakePhotoTextViewENGLISH));
        }
    } else if (udtea.currScreen == udtea.PAINT_SCREEN) {
        udtea.setContentView(R.layout.paint_screen);
        if (!udtea.performedRunPaint) {
            udtea.initPaintScreen();
        }
        udtea.initBackNextButtons();
        TextView myPaintScreenTextView = (TextView) udtea.findViewById(R.id.paint_textview);
        myPaintScreenTextView = (TextView) UsbongUtils.applyTagsInView(
                UsbongDecisionTreeEngineActivity.getInstance(), myPaintScreenTextView, UsbongUtils.IS_TEXTVIEW,
                udtea.currUsbongNode);
        Button paintButton = (Button) udtea.findViewById(R.id.paint_button);
        if (udtea.currLanguageBeingUsed == UsbongUtils.LANGUAGE_FILIPINO) {
            paintButton.setText((String) udtea.getResources().getText(R.string.UsbongRunPaintTextViewFILIPINO));
        } else if (udtea.currLanguageBeingUsed == UsbongUtils.LANGUAGE_JAPANESE) {
            paintButton.setText((String) udtea.getResources().getText(R.string.UsbongRunPaintTextViewJAPANESE));
        } else { //if (udtea.currLanguageBeingUsed==UsbongUtils.LANGUAGE_ENGLISH) {
            paintButton.setText((String) udtea.getResources().getText(R.string.UsbongRunPaintTextViewENGLISH));
        }
    } else if (udtea.currScreen == udtea.QR_CODE_READER_SCREEN) {
        udtea.setContentView(R.layout.qr_code_reader_screen);
        if (!udtea.performedGetQRCode) {
            udtea.initQRCodeReaderScreen();
        }
        udtea.initBackNextButtons();
        TextView myQRCodeReaderScreenTextView = (TextView) udtea.findViewById(R.id.qr_code_reader_textview);
        myQRCodeReaderScreenTextView = (TextView) UsbongUtils.applyTagsInView(
                UsbongDecisionTreeEngineActivity.getInstance(), myQRCodeReaderScreenTextView,
                UsbongUtils.IS_TEXTVIEW, udtea.currUsbongNode);
        Button qrCodeReaderButton = (Button) udtea.findViewById(R.id.qr_code_reader_button);
        if (udtea.currLanguageBeingUsed == UsbongUtils.LANGUAGE_FILIPINO) {
            qrCodeReaderButton.setText(
                    (String) udtea.getResources().getText(R.string.UsbongQRCodeReaderTextViewFILIPINO));
        } else if (udtea.currLanguageBeingUsed == UsbongUtils.LANGUAGE_JAPANESE) {
            qrCodeReaderButton.setText(
                    (String) udtea.getResources().getText(R.string.UsbongQRCodeReaderTextViewJAPANESE));
        } else { //if (udtea.currLanguageBeingUsed==UsbongUtils.LANGUAGE_ENGLISH) {
            qrCodeReaderButton
                    .setText((String) udtea.getResources().getText(R.string.UsbongQRCodeReaderTextViewENGLISH));
        }
    } else if (udtea.currScreen == udtea.TEXTFIELD_SCREEN) {
        udtea.setContentView(R.layout.textfield_screen);
        udtea.initBackNextButtons();
        TextView myTextFieldScreenTextView = (TextView) udtea.findViewById(R.id.textfield_textview);
        myTextFieldScreenTextView = (TextView) UsbongUtils.applyTagsInView(
                UsbongDecisionTreeEngineActivity.getInstance(), myTextFieldScreenTextView,
                UsbongUtils.IS_TEXTVIEW, udtea.currUsbongNode);
        EditText myTextFieldScreenEditText = (EditText) udtea.findViewById(R.id.textfield_edittext);
        myTextFieldScreenEditText.setText(myStringToken);
    } else if (udtea.currScreen == udtea.TEXTFIELD_WITH_ANSWER_SCREEN) {
        udtea.setContentView(R.layout.textfield_screen);
        udtea.initBackNextButtons();
        String myTextFieldWithAnswerScreenStringToken = "";
        //             Log.d(">>>>>>>>udtea.currUsbongNode", udtea.currUsbongNode);
        udtea.currUsbongNodeWithoutAnswer = udtea.currUsbongNode.replace("Answer=", "~");
        StringTokenizer myTextFieldWithAnswerScreenStringTokenizer = new StringTokenizer(
                udtea.currUsbongNodeWithoutAnswer, "~");
        if (myTextFieldWithAnswerScreenStringTokenizer != null) {
            myTextFieldWithAnswerScreenStringToken = myTextFieldWithAnswerScreenStringTokenizer.nextToken();

            while (myTextFieldWithAnswerScreenStringTokenizer.hasMoreTokens()) { //get last element (i.e. Mike in "textFieldWithAnswer~Who is the founder of Usbong (nickname)?Answer=Mike")
                myTextFieldWithAnswerScreenStringToken = myTextFieldWithAnswerScreenStringTokenizer.nextToken();
            }
        }
        udtea.myTextFieldWithAnswerScreenAnswer = myTextFieldWithAnswerScreenStringToken.toString();
        udtea.currUsbongNodeWithoutAnswer = udtea.currUsbongNodeWithoutAnswer.substring(0,
                udtea.currUsbongNodeWithoutAnswer.length() - udtea.myTextFieldWithAnswerScreenAnswer.length()
                        - 1); //do a -1 for the last tilde             
        TextView myTextFieldWithAnswerScreenTextView = (TextView) udtea.findViewById(R.id.textfield_textview);
        myTextFieldWithAnswerScreenTextView = (TextView) UsbongUtils.applyTagsInView(
                UsbongDecisionTreeEngineActivity.getInstance(), myTextFieldWithAnswerScreenTextView,
                UsbongUtils.IS_TEXTVIEW, udtea.currUsbongNodeWithoutAnswer);
        EditText myTextFieldScreenWithAnswerEditText = (EditText) udtea.findViewById(R.id.textfield_edittext);
        myTextFieldScreenWithAnswerEditText.setText(myStringToken);
    } else if (udtea.currScreen == udtea.TEXTAREA_SCREEN) {
        udtea.setContentView(R.layout.textarea_screen);
        udtea.initBackNextButtons();
        TextView myTextAreaScreenTextView = (TextView) udtea.findViewById(R.id.textarea_textview);
        myTextAreaScreenTextView = (TextView) UsbongUtils.applyTagsInView(
                UsbongDecisionTreeEngineActivity.getInstance(), myTextAreaScreenTextView,
                UsbongUtils.IS_TEXTVIEW, udtea.currUsbongNode);
        EditText myTextAreaScreenEditText = (EditText) udtea.findViewById(R.id.textarea_edittext);
        myTextAreaScreenEditText.setText(myStringToken);
    } else if (udtea.currScreen == udtea.TEXTAREA_WITH_ANSWER_SCREEN) {
        udtea.setContentView(R.layout.textarea_screen);
        udtea.initBackNextButtons();
        String myTextAreaWithAnswerScreenStringToken = "";
        //             Log.d(">>>>>>>>udtea.currUsbongNode", udtea.currUsbongNode);
        udtea.currUsbongNodeWithoutAnswer = udtea.currUsbongNode.replace("Answer=", "~");
        StringTokenizer myTextAreaWithAnswerScreenStringTokenizer = new StringTokenizer(
                udtea.currUsbongNodeWithoutAnswer, "~");
        if (myTextAreaWithAnswerScreenStringTokenizer != null) {
            myTextAreaWithAnswerScreenStringToken = myTextAreaWithAnswerScreenStringTokenizer.nextToken();

            while (myTextAreaWithAnswerScreenStringTokenizer.hasMoreTokens()) { //get last element (i.e. Mike in "textFieldWithAnswer~Who is the founder of Usbong (nickname)?Answer=Mike")
                myTextAreaWithAnswerScreenStringToken = myTextAreaWithAnswerScreenStringTokenizer.nextToken();
            }
        }
        udtea.myTextAreaWithAnswerScreenAnswer = myTextAreaWithAnswerScreenStringToken.toString();
        udtea.currUsbongNodeWithoutAnswer = udtea.currUsbongNodeWithoutAnswer.substring(0,
                udtea.currUsbongNodeWithoutAnswer.length() - udtea.myTextAreaWithAnswerScreenAnswer.length()
                        - 1); //do a -1 for the last tilde             
        TextView myTextAreaWithAnswerScreenTextView = (TextView) udtea.findViewById(R.id.textarea_textview);
        myTextAreaWithAnswerScreenTextView = (TextView) UsbongUtils.applyTagsInView(
                UsbongDecisionTreeEngineActivity.getInstance(), myTextAreaWithAnswerScreenTextView,
                UsbongUtils.IS_TEXTVIEW, udtea.currUsbongNodeWithoutAnswer);
        EditText myTextAreaScreenWithAnswerEditText = (EditText) udtea.findViewById(R.id.textarea_edittext);
        myTextAreaScreenWithAnswerEditText.setText(myStringToken);
    } else if (udtea.currScreen == udtea.TEXTFIELD_WITH_UNIT_SCREEN) {
        udtea.setContentView(R.layout.textfield_with_unit_screen);
        udtea.initBackNextButtons();
        TextView myTextFieldWithUnitScreenTextView = (TextView) udtea.findViewById(R.id.textfield_textview);
        myTextFieldWithUnitScreenTextView = (TextView) UsbongUtils.applyTagsInView(
                UsbongDecisionTreeEngineActivity.getInstance(), myTextFieldWithUnitScreenTextView,
                UsbongUtils.IS_TEXTVIEW, udtea.currUsbongNode);
        EditText myEditText = (EditText) udtea.findViewById(R.id.textfield_edittext);
        myEditText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        myEditText.setText(myStringToken);
        TextView myUnitScreenTextView = (TextView) udtea.findViewById(R.id.textfieldunit_textview);
        myUnitScreenTextView.setText(udtea.textFieldUnit);
    } else if (udtea.currScreen == udtea.TEXTFIELD_NUMERICAL_SCREEN) {
        udtea.setContentView(R.layout.textfield_screen);
        udtea.initBackNextButtons();
        TextView myTextFieldNumericalScreenTextView = (TextView) udtea.findViewById(R.id.textfield_textview);
        myTextFieldNumericalScreenTextView = (TextView) UsbongUtils.applyTagsInView(
                UsbongDecisionTreeEngineActivity.getInstance(), myTextFieldNumericalScreenTextView,
                UsbongUtils.IS_TEXTVIEW, udtea.currUsbongNode);
        EditText myTextFieldNumericalScreenEditText = (EditText) udtea.findViewById(R.id.textfield_edittext);
        myTextFieldNumericalScreenEditText
                .setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        myTextFieldNumericalScreenEditText.setText(myStringToken);
    } else if (udtea.currScreen == udtea.CLASSIFICATION_SCREEN) {
        udtea.setContentView(R.layout.classification_screen);
        udtea.initBackNextButtons();
        TextView myClassificationScreenTextView = (TextView) udtea.findViewById(R.id.classification_textview);
        myClassificationScreenTextView = (TextView) UsbongUtils.applyTagsInView(
                UsbongDecisionTreeEngineActivity.getInstance(), myClassificationScreenTextView,
                UsbongUtils.IS_TEXTVIEW, udtea.currUsbongNode);
        LinearLayout myClassificationLinearLayout = (LinearLayout) udtea
                .findViewById(R.id.classification_linearlayout);
        int totalClassificationsInContainer = udtea.classificationContainer.size();
        for (int i = 0; i < totalClassificationsInContainer; i++) {
            TextView myTextView = new TextView(udtea.getBaseContext());
            //consider removing this code below; not needed; Mike, May 23, 2013
            myTextView = (TextView) UsbongUtils.applyTagsInView(UsbongDecisionTreeEngineActivity.getInstance(),
                    myTextView, UsbongUtils.IS_TEXTVIEW, udtea.currUsbongNode);

            int bulletCount = i + 1;
            if (UsbongUtils.USE_UNESCAPE) {
                myTextView.setText(bulletCount + ") " + StringEscapeUtils
                        .unescapeJava(udtea.classificationContainer.elementAt(i).toString()));
            } else {
                myTextView.setText(bulletCount + ") " + UsbongUtils
                        .trimUsbongNodeName(udtea.classificationContainer.elementAt(i).toString()));
            }

            //add 5 so that the text does not touch the left border
            myTextView.setPadding(udtea.padding_in_px, 0, 0, 0);
            myTextView.setTextSize(24);
            //                 myTextView.setTextColor(Color.WHITE);
            myTextView.setTextColor(Color.parseColor("#4a452a"));
            myClassificationLinearLayout.addView(myTextView);
        }
    } else if (udtea.currScreen == udtea.DCAT_SUMMARY_SCREEN) {
        udtea.setContentView(R.layout.dcat_summary_screen);
        udtea.initBackNextButtons();
        TextView myDCATSummaryScreenTextView = (TextView) udtea.findViewById(R.id.dcat_summary_textview);
        myDCATSummaryScreenTextView = (TextView) UsbongUtils.applyTagsInView(
                UsbongDecisionTreeEngineActivity.getInstance(), myDCATSummaryScreenTextView,
                UsbongUtils.IS_TEXTVIEW, udtea.currUsbongNode);
        udtea.myDcatSummaryStringBuffer = new StringBuffer();
        String weightsString = "1.9;2.1;2.6;1.8;2.4;1.8;.7;1.0;1.6;2.6;6.9;5.7;3.3;2.2;3.3;3.3;2;2;1.7;1.9;3.9;1.3;2.5;.8";
        StringTokenizer myWeightsStringTokenizer = new StringTokenizer(weightsString, ";");
        String myWeightString = myWeightsStringTokenizer.nextToken();
        //            
        //            while (st.hasMoreTokens()) {
        //               myStringToken = st.nextToken(); 
        //            }
        //
        double myWeightedScoreInt = 0;
        double myNegotiatedWeightedScoreInt = 0;
        double[][] dcatSum = new double[8][4];
        final int sumWeightedRatingIndex = 0;
        final int sumWeightedScoreIndex = 1;
        final int sumNegotiatedRatingIndex = 2;
        final int sumNegotiatedScoreIndex = 3;
        int currStandard = 0;//standard 1
        //            boolean hasReachedNegotiated=false;
        boolean hasReachedStandardTotal = false;
        LinearLayout myDCATSummaryLinearLayout = (LinearLayout) udtea
                .findViewById(R.id.dcat_summary_linearlayout);
        int totalElementsInDCATSummaryBasedOnUsbongNodeContainer = udtea.usbongNodeContainer.size();
        //              for (int i=0; i<totalElementsInDCATSummaryBasedOnUsbongNodeContainer.usbongNodeContainer; i++) {                 
        for (int i = 0; i < totalElementsInDCATSummaryBasedOnUsbongNodeContainer; i++) {

            TextView myTextView = new TextView(udtea.getBaseContext());
            myTextView.setPadding(udtea.padding_in_px, 0, 0, 0); //add 5 so that the text does not touch the left border
            myTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 24);
            myTextView.setTextColor(Color.parseColor("#4a452a"));

            //the only way to check if the element is already the last item in the standard
            //is if the next element in the node container has "STANDARD", but not the first standard
            if ((i + 1 >= totalElementsInDCATSummaryBasedOnUsbongNodeContainer) || (i
                    + 1 < totalElementsInDCATSummaryBasedOnUsbongNodeContainer)
                    && ((udtea.usbongNodeContainer.elementAt(i + 1).toString().contains("STANDARD")))
                    && (!(udtea.usbongNodeContainer.elementAt(i + 1).toString().contains("STANDARD ONE")))) {
                int tempCurrStandard = currStandard + 1; //do a +1 since currStandard begins at 0

                TextView myIssuesTextView = new TextView(udtea.getBaseContext());

                //added by Mike, May 31, 2013
                if (!udtea.usbongAnswerContainer.elementAt(i).toString().contains("dcat_end,")) {

                    String s = udtea.usbongAnswerContainer.elementAt(i).toString().replace(";", "");
                    s = s.replace("A,", "");
                    if (!s.equals("")) {
                        myIssuesTextView = (TextView) UsbongUtils.applyTagsInView(
                                UsbongDecisionTreeEngineActivity.getInstance(), myIssuesTextView,
                                UsbongUtils.IS_TEXTVIEW, "ISSUES: " + s + "{br}");
                    } else {
                        myIssuesTextView = (TextView) UsbongUtils.applyTagsInView(
                                UsbongDecisionTreeEngineActivity.getInstance(), myIssuesTextView,
                                UsbongUtils.IS_TEXTVIEW, "ISSUES: none{br}");
                    }

                    myIssuesTextView.setPadding(udtea.padding_in_px, 0, 0, 0); //add 5 so that the text does not touch the left border
                    myIssuesTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 24);
                    myIssuesTextView.setTextColor(Color.parseColor("#4a452a"));
                    myDCATSummaryLinearLayout.addView(myIssuesTextView);
                    udtea.myDcatSummaryStringBuffer.append(myIssuesTextView.getText().toString() + "\n");
                }

                if (myWeightsStringTokenizer.hasMoreElements()) {
                    //get the next weight
                    myWeightString = myWeightsStringTokenizer.nextToken();
                }

                myTextView = (TextView) UsbongUtils.applyTagsInView(
                        UsbongDecisionTreeEngineActivity.getInstance(), myTextView, UsbongUtils.IS_TEXTVIEW,
                        "//--------------------" + " STANDARD " + tempCurrStandard + " (TOTAL){br}"
                                + "Total (Rating): "
                                + String.format("%.2f", dcatSum[currStandard][sumWeightedRatingIndex]) + "{br}"
                                + "Total (Weighted Score): "
                                + String.format("%.2f", dcatSum[currStandard][sumWeightedScoreIndex]) + "{br}"
                                + "Total (Negotiated Rating): "
                                + String.format("%.2f", dcatSum[currStandard][sumNegotiatedRatingIndex])
                                + "{br}" + "Total (Negotiated WS): "
                                + String.format("%.2f", dcatSum[currStandard][sumNegotiatedScoreIndex]) + "{br}"
                                + "//--------------------");
                hasReachedStandardTotal = true;
                currStandard++;
            }

            if (hasReachedStandardTotal) {
                hasReachedStandardTotal = false;
            } else if (udtea.usbongNodeContainer.elementAt(i).toString().contains("ISSUES")) {
                String s = udtea.usbongAnswerContainer.elementAt(i).toString().replace(";", "");
                s = s.replace("A,", "");
                if (!s.equals("")) {
                    myTextView = (TextView) UsbongUtils.applyTagsInView(
                            UsbongDecisionTreeEngineActivity.getInstance(), myTextView, UsbongUtils.IS_TEXTVIEW,
                            "ISSUES: " + s + "{br}");
                } else {
                    myTextView = (TextView) UsbongUtils.applyTagsInView(
                            UsbongDecisionTreeEngineActivity.getInstance(), myTextView, UsbongUtils.IS_TEXTVIEW,
                            "ISSUES: none{br}");
                }

                if (myWeightsStringTokenizer.hasMoreElements()) {
                    //get the next weight
                    myWeightString = myWeightsStringTokenizer.nextToken();
                }
            } else if (udtea.usbongNodeContainer.elementAt(i).toString().contains("Weighted")) {
                TextView myWeightedTextView = new TextView(udtea.getBaseContext());
                myWeightedTextView = (TextView) UsbongUtils.applyTagsInView(
                        UsbongDecisionTreeEngineActivity.getInstance(), myWeightedTextView,
                        UsbongUtils.IS_TEXTVIEW,
                        udtea.usbongNodeContainer.elementAt(i).toString().replace("{br}(Weighted Score)", ""));
                myWeightedTextView.setPadding(udtea.padding_in_px, 0, 0, 0); //add 5 so that the text does not touch the left border
                myWeightedTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 24);
                myWeightedTextView.setTextColor(Color.parseColor("#4a452a"));

                myDCATSummaryLinearLayout.addView(myWeightedTextView);
                udtea.myDcatSummaryStringBuffer.append(myWeightedTextView.getText().toString() + "\n");

                int weightedAnswer;
                //added by Mike, July 8, 2013
                try {
                    weightedAnswer = Integer
                            .parseInt(udtea.usbongAnswerContainer.elementAt(i).toString().replace(";", ""));
                } catch (Exception e) { //if there's no answer selected
                    weightedAnswer = 0;
                }
                if (weightedAnswer <= 0) {
                    weightedAnswer = 0;
                }

                //the weight is in double
                myWeightedScoreInt = weightedAnswer * Double.parseDouble(myWeightString);
                if (myWeightedScoreInt <= 0) {
                    myWeightedScoreInt = 0;
                    myTextView.setBackgroundColor(Color.YELLOW);
                }

                dcatSum[currStandard][sumWeightedRatingIndex] += weightedAnswer;
                dcatSum[currStandard][sumWeightedScoreIndex] += myWeightedScoreInt;

                myTextView = (TextView) UsbongUtils.applyTagsInView(
                        UsbongDecisionTreeEngineActivity.getInstance(), myTextView, UsbongUtils.IS_TEXTVIEW,
                        "Weighted: " + myWeightedScoreInt);
            } else if (udtea.usbongNodeContainer.elementAt(i).toString().contains("Negotiated")) {
                //added by Mike, July 8, 2013
                int negotiatedAnswer;
                try {
                    negotiatedAnswer = Integer
                            .parseInt(udtea.usbongAnswerContainer.elementAt(i).toString().replace(";", ""));
                } catch (Exception e) { //if there's no answer selected
                    negotiatedAnswer = 0;
                }
                if (negotiatedAnswer <= 0) {
                    negotiatedAnswer = 0;
                }

                //the weight is in double
                myNegotiatedWeightedScoreInt = negotiatedAnswer * Double.parseDouble(myWeightString);
                if (myNegotiatedWeightedScoreInt <= 0) {
                    myNegotiatedWeightedScoreInt = 0;
                    myTextView.setBackgroundColor(Color.YELLOW);
                }

                dcatSum[currStandard][sumNegotiatedRatingIndex] += negotiatedAnswer;
                dcatSum[currStandard][sumNegotiatedScoreIndex] += myNegotiatedWeightedScoreInt;

                myTextView = (TextView) UsbongUtils.applyTagsInView(
                        UsbongDecisionTreeEngineActivity.getInstance(), myTextView, UsbongUtils.IS_TEXTVIEW,
                        "Negotiated: " + myNegotiatedWeightedScoreInt);
                //                    hasReachedNegotiated=true;
            } else {
                myTextView = (TextView) UsbongUtils.applyTagsInView(
                        UsbongDecisionTreeEngineActivity.getInstance(), myTextView, UsbongUtils.IS_TEXTVIEW,
                        udtea.usbongNodeContainer.elementAt(i).toString() + "{br}");
            }

            //                 if (!hasReachedStandardTotal) {
            myDCATSummaryLinearLayout.addView(myTextView);
            udtea.myDcatSummaryStringBuffer.append(myTextView.getText().toString() + "\n");
            Log.d(">>>>>myTextView.getText().toString()", myTextView.getText().toString());
            //                 }
            //                 else {
            //                    hasReachedStandardTotal=false;
            //                 }
        }
    } else if (udtea.currScreen == udtea.DATE_SCREEN) {
        udtea.setContentView(R.layout.date_screen);
        udtea.initBackNextButtons();
        TextView myDateScreenTextView = (TextView) udtea.findViewById(R.id.date_textview);
        myDateScreenTextView = (TextView) UsbongUtils.applyTagsInView(
                UsbongDecisionTreeEngineActivity.getInstance(), myDateScreenTextView, UsbongUtils.IS_TEXTVIEW,
                udtea.currUsbongNode);
        //Reference: http://code.google.com/p/android/issues/detail?id=2037
        //last accessed: 21 Aug. 2012
        Configuration userConfig = new Configuration();
        Settings.System.getConfiguration(udtea.getContentResolver(), userConfig);
        Calendar date = Calendar.getInstance(userConfig.locale);
        //Reference: http://www.androidpeople.com/android-spinner-default-value;
        //last accessed: 21 Aug. 2012              
        //month-------------------------------
        int month = date.get(Calendar.MONTH); //first month of the year is 0
        Spinner dateMonthSpinner = (Spinner) udtea.findViewById(R.id.date_month_spinner);
        udtea.monthAdapter = ArrayAdapter.createFromResource(((Activity) udtea), R.array.months_array,
                android.R.layout.simple_spinner_item);
        //              udtea.monthAdapter  = ArrayAdapter.createFromResource(
        //                this, R.array.months_array, R.layout.date_textview);
        udtea.monthAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        dateMonthSpinner.setAdapter(udtea.monthAdapter);
        dateMonthSpinner.setSelection(month);
        //              System.out.println(">>>>>>>>>>>>>> month"+month);
        //              Log.d(">>>>>>myStringToken",myStringToken);
        for (int i = 0; i < udtea.monthAdapter.getCount(); i++) {
            //                 Log.d(">>>>>>udtea.monthAdapter ",udtea.monthAdapter .getItem(i).toString());

            if (myStringToken.contains(udtea.monthAdapter.getItem(i).toString())) {
                dateMonthSpinner.setSelection(i);

                //added by Mike, March 4, 2013
                myStringToken = myStringToken.replace(udtea.monthAdapter.getItem(i).toString(), "");
            }
        }
        //-------------------------------------
        //day----------------------------------
        //Reference: http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Calendar.html#MONTH
        //last accessed: 21 Aug 2012
        int day = date.get(Calendar.DAY_OF_MONTH); //first day of the month is 1
        day = day - 1; //do this to offset, when retrieving the day in strings.xml
        Spinner dateDaySpinner = (Spinner) udtea.findViewById(R.id.date_day_spinner);
        udtea.dayAdapter = ArrayAdapter.createFromResource(((Activity) udtea), R.array.day_array,
                android.R.layout.simple_spinner_item);
        udtea.dayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        dateDaySpinner.setAdapter(udtea.dayAdapter);
        dateDaySpinner.setSelection(day);
        //              System.out.println(">>>>>>>>>>>>>> day"+day);
        //              Log.d(">>>>>myStringToken",myStringToken);
        //              System.out.println(">>>>>>>> myStringToken"+myStringToken);
        StringTokenizer myDateStringTokenizer = new StringTokenizer(myStringToken, ",");
        String myDayStringToken = "";
        if (!myStringToken.equals("")) {
            myDayStringToken = myDateStringTokenizer.nextToken();
        }
        for (int i = 0; i < udtea.dayAdapter.getCount(); i++) {
            if (myDayStringToken.contains(udtea.dayAdapter.getItem(i).toString())) {
                dateDaySpinner.setSelection(i);

                myStringToken = myStringToken.replace(udtea.dayAdapter.getItem(i).toString() + ",", "");
                //                    System.out.println(">>>>>>>>>>>myStringToken: "+myStringToken);
            }
        }
        //-------------------------------------            
        //year---------------------------------
        int year = date.get(Calendar.YEAR);
        EditText myDateYearEditText = (EditText) udtea.findViewById(R.id.date_edittext);
        myDateYearEditText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        //added by Mike, March 4, 2013
        if (myStringToken.equals("")) {
            myDateYearEditText.setText("" + year);
        } else {
            myDateYearEditText.setText(myStringToken);
        }
    } else if (udtea.currScreen == udtea.TEXT_DISPLAY_SCREEN) {
        udtea.setContentView(R.layout.text_display_screen);
        udtea.initBackNextButtons();
        TextView myTextDisplayScreenTextView = (TextView) udtea.findViewById(R.id.text_display_textview);
        myTextDisplayScreenTextView = (TextView) UsbongUtils.applyTagsInView(
                UsbongDecisionTreeEngineActivity.getInstance(), myTextDisplayScreenTextView,
                UsbongUtils.IS_TEXTVIEW, udtea.currUsbongNode);

        //         Log.d(">>>>>","inside udtea.currScreen == udtea.TEXT_DISPLAY_SCREEN");
        //         myTextDisplayScreenTextView = (TextView) UsbongUtils.applyHintsInView(UsbongDecisionTreeEngineActivity.getInstance(), myTextDisplayScreenTextView, UsbongUtils.IS_TEXTVIEW);
        //         Log.d(">>>>>","after myTextDisplayScreenTextView");

    } else if (udtea.currScreen == udtea.TIMESTAMP_DISPLAY_SCREEN) {
        udtea.setContentView(R.layout.timestamp_display_screen);
        udtea.initBackNextButtons();
        TextView myTimeDisplayScreenTextView = (TextView) udtea.findViewById(R.id.time_display_textview);
        udtea.timestampString = UsbongUtils.getCurrTimeStamp();
        myTimeDisplayScreenTextView = (TextView) UsbongUtils.applyTagsInView(
                UsbongDecisionTreeEngineActivity.getInstance(), myTimeDisplayScreenTextView,
                UsbongUtils.IS_TEXTVIEW, udtea.currUsbongNode + "{br}" + udtea.timestampString);

    } else if (udtea.currScreen == udtea.SIMPLE_ENCRYPT_SCREEN) {
        udtea.setContentView(R.layout.simple_encrypt_screen);
        udtea.initBackNextButtons();
        TextView myEncryptScreenTextView = (TextView) udtea.findViewById(R.id.encrypt_textview);
        myEncryptScreenTextView = (TextView) UsbongUtils.applyTagsInView(
                UsbongDecisionTreeEngineActivity.getInstance(), myEncryptScreenTextView,
                UsbongUtils.IS_TEXTVIEW, udtea.currUsbongNode);

        String message = "";
        if (udtea.currLanguageBeingUsed == UsbongUtils.LANGUAGE_FILIPINO) {
            message = (String) udtea.getResources().getText(R.string.UsbongEncryptAlertMessageFILIPINO);
        } else if (udtea.currLanguageBeingUsed == UsbongUtils.LANGUAGE_JAPANESE) {
            message = (String) udtea.getResources().getText(R.string.UsbongEncryptAlertMessageJAPANESE);
        } else { //if (udtea.currLanguageBeingUsed==UsbongUtils.LANGUAGE_ENGLISH) {
            message = (String) udtea.getResources().getText(R.string.UsbongEncryptAlertMessageENGLISH);
        }

        new AlertDialog.Builder(udtea).setTitle("Hey!").setMessage(message)
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                }).show();

    } else if (udtea.currScreen == udtea.IMAGE_DISPLAY_SCREEN) {
        udtea.setContentView(R.layout.image_display_screen);
        udtea.initBackNextButtons();
        ImageView myImageDisplayScreenImageView = (ImageView) udtea.findViewById(R.id.special_imageview);
        //              if (!UsbongUtils.setImageDisplay(myImageDisplayScreenImageView, myTree+".utree/res/" +UsbongUtils.getResName(udtea.currUsbongNode))) {
        if (!UsbongUtils.setImageDisplay(myImageDisplayScreenImageView, udtea.myTree,
                UsbongUtils.getResName(udtea.currUsbongNode))) {
            //Reference: http://www.anddev.org/tinytut_-_get_resources_by_name__getidentifier_-t460.html; last accessed 14 Sept 2011
            //                 Resources myRes = getResources();
            myDrawableImage = myRes
                    .getDrawable(myRes.getIdentifier("no_image", "drawable", udtea.myPackageName));
            myImageDisplayScreenImageView.setImageDrawable(myDrawableImage);
        }
    } else if (udtea.currScreen == udtea.CLICKABLE_IMAGE_DISPLAY_SCREEN) {
        udtea.setContentView(R.layout.clickable_image_display_screen);
        udtea.initBackNextButtons();
        ImageButton myClickableImageDisplayScreenImageButton = (ImageButton) udtea
                .findViewById(R.id.clickable_image_display_imagebutton);
        if (!UsbongUtils.setClickableImageDisplay(myClickableImageDisplayScreenImageButton, udtea.myTree,
                UsbongUtils.getResName(udtea.currUsbongNode))) {
            //Reference: http://www.anddev.org/tinytut_-_get_resources_by_name__getidentifier_-t460.html; last accessed 14 Sept 2011
            //                 Resources myRes = getResources();
            myDrawableImage = myRes
                    .getDrawable(myRes.getIdentifier("no_image", "drawable", udtea.myPackageName));
            myClickableImageDisplayScreenImageButton.setBackgroundDrawable(myDrawableImage);
        }
        myClickableImageDisplayScreenImageButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //                      myMessage = UsbongUtils.applyTagsInString(udtea.currUsbongNode).toString();                   

                TextView tv = (TextView) UsbongUtils.applyTagsInView(
                        UsbongDecisionTreeEngineActivity.getInstance(),
                        new TextView(UsbongDecisionTreeEngineActivity.getInstance()), UsbongUtils.IS_TEXTVIEW,
                        udtea.currUsbongNode);
                if (tv.toString().equals("")) {
                    tv.setText("No message.");
                }
                tv.setTextSize((UsbongDecisionTreeEngineActivity.getInstance().getResources()
                        .getDimension(R.dimen.textsize)));

                new AlertDialog.Builder(udtea).setTitle("Hey!")
                        //                     .setMessage(myMessage)
                        .setView(tv).setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                            }
                        }).show();
            }
        });
    } else if (udtea.currScreen == udtea.TEXT_CLICKABLE_IMAGE_DISPLAY_SCREEN) {
        udtea.setContentView(R.layout.text_clickable_image_display_screen);
        udtea.initBackNextButtons();
        TextView myTextClickableImageDisplayTextView = (TextView) udtea
                .findViewById(R.id.text_clickable_image_display_textview);
        myTextClickableImageDisplayTextView = (TextView) UsbongUtils.applyTagsInView(
                UsbongDecisionTreeEngineActivity.getInstance(), myTextClickableImageDisplayTextView,
                UsbongUtils.IS_TEXTVIEW, udtea.currUsbongNode);
        ImageButton myTextClickableImageDisplayScreenImageButton = (ImageButton) udtea
                .findViewById(R.id.clickable_image_display_imagebutton);
        if (!UsbongUtils.setClickableImageDisplay(myTextClickableImageDisplayScreenImageButton, udtea.myTree,
                UsbongUtils.getResName(udtea.currUsbongNode))) {
            //Reference: http://www.anddev.org/tinytut_-_get_resources_by_name__getidentifier_-t460.html; last accessed 14 Sept 2011
            //                 Resources myRes = getResources();
            myDrawableImage = myRes
                    .getDrawable(myRes.getIdentifier("no_image", "drawable", udtea.myPackageName));
            myTextClickableImageDisplayScreenImageButton.setBackgroundDrawable(myDrawableImage);
        }
        myTextClickableImageDisplayScreenImageButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //                      myMessage = UsbongUtils.applyTagsInString(udtea.currUsbongNode).toString();                   

                TextView tv = (TextView) UsbongUtils.applyTagsInView(
                        UsbongDecisionTreeEngineActivity.getInstance(), new TextView(udtea),
                        UsbongUtils.IS_TEXTVIEW, UsbongUtils.getAlertName(udtea.currUsbongNode));
                if (tv.toString().equals("")) {
                    tv.setText("No message.");
                }
                tv.setTextSize((UsbongDecisionTreeEngineActivity.getInstance().getResources()
                        .getDimension(R.dimen.textsize)));

                new AlertDialog.Builder(udtea).setTitle("Hey!")
                        //                     .setMessage(myMessage)
                        .setView(tv).setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                            }
                        }).show();
            }
        });
    } else if (udtea.currScreen == udtea.CLICKABLE_IMAGE_TEXT_DISPLAY_SCREEN) {
        udtea.setContentView(R.layout.clickable_image_text_display_screen);
        udtea.initBackNextButtons();
        TextView myClickableImageTextDisplayTextView = (TextView) udtea
                .findViewById(R.id.clickable_image_text_display_textview);
        myClickableImageTextDisplayTextView = (TextView) UsbongUtils.applyTagsInView(
                UsbongDecisionTreeEngineActivity.getInstance(), myClickableImageTextDisplayTextView,
                UsbongUtils.IS_TEXTVIEW, udtea.currUsbongNode);
        ImageButton myClickableImageTextDisplayScreenImageButton = (ImageButton) udtea
                .findViewById(R.id.clickable_image_display_imagebutton);
        if (!UsbongUtils.setClickableImageDisplay(myClickableImageTextDisplayScreenImageButton, udtea.myTree,
                UsbongUtils.getResName(udtea.currUsbongNode))) {
            //Reference: http://www.anddev.org/tinytut_-_get_resources_by_name__getidentifier_-t460.html; last accessed 14 Sept 2011
            //                 Resources myRes = getResources();
            myDrawableImage = myRes
                    .getDrawable(myRes.getIdentifier("no_image", "drawable", udtea.myPackageName));
            myClickableImageTextDisplayScreenImageButton.setBackgroundDrawable(myDrawableImage);
        }
        myClickableImageTextDisplayScreenImageButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //                      myMessage = UsbongUtils.applyTagsInString(udtea.currUsbongNode).toString();                   

                TextView tv = (TextView) UsbongUtils.applyTagsInView(
                        UsbongDecisionTreeEngineActivity.getInstance(), new TextView(udtea),
                        UsbongUtils.IS_TEXTVIEW, UsbongUtils.getAlertName(udtea.currUsbongNode));
                if (tv.toString().equals("")) {
                    tv.setText("No message.");
                }
                tv.setTextSize((UsbongDecisionTreeEngineActivity.getInstance().getResources()
                        .getDimension(R.dimen.textsize)));

                new AlertDialog.Builder(udtea).setTitle("Hey!")
                        //                     .setMessage(myMessage)
                        .setView(tv).setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                            }
                        }).show();
            }
        });
    } else if (udtea.currScreen == udtea.VIDEO_FROM_FILE_SCREEN) {
        udtea.setContentView(R.layout.video_from_file_screen);
        udtea.initBackNextButtons();
        VideoView myVideoFromFileScreenVideoView = (VideoView) udtea
                .findViewById(R.id.video_from_file_videoview);
        myVideoFromFileScreenVideoView.setVideoPath(
                UsbongUtils.getPathOfVideoFile(udtea.myTree, UsbongUtils.getResName(udtea.currUsbongNode)));
        //added by Mike, Sept. 9, 2013
        myVideoFromFileScreenVideoView.setMediaController(new MediaController(((Activity) udtea)));
        myVideoFromFileScreenVideoView.start();
    } else if (udtea.currScreen == udtea.VIDEO_FROM_FILE_WITH_TEXT_SCREEN) {
        udtea.setContentView(R.layout.video_from_file_with_text_screen);
        udtea.initBackNextButtons();
        TextView myVideoFromFileWithTextTextView = (TextView) udtea
                .findViewById(R.id.video_from_file_with_text_textview);
        myVideoFromFileWithTextTextView = (TextView) UsbongUtils.applyTagsInView(
                UsbongDecisionTreeEngineActivity.getInstance(), myVideoFromFileWithTextTextView,
                UsbongUtils.IS_TEXTVIEW, udtea.currUsbongNode);
        VideoView myVideoFromFileWithTextScreenVideoView = (VideoView) udtea
                .findViewById(R.id.video_from_file_with_text_videoview);
        myVideoFromFileWithTextScreenVideoView.setVideoPath(
                UsbongUtils.getPathOfVideoFile(udtea.myTree, UsbongUtils.getResName(udtea.currUsbongNode)));
        myVideoFromFileWithTextScreenVideoView.setMediaController(new MediaController(((Activity) udtea)));
        myVideoFromFileWithTextScreenVideoView.start();
    } else if (udtea.currScreen == udtea.TEXT_IMAGE_DISPLAY_SCREEN) {
        udtea.setContentView(R.layout.text_image_display_screen);
        udtea.initBackNextButtons();
        TextView myTextImageDisplayTextView = (TextView) udtea.findViewById(R.id.text_image_display_textview);
        myTextImageDisplayTextView = (TextView) UsbongUtils.applyTagsInView(
                UsbongDecisionTreeEngineActivity.getInstance(), myTextImageDisplayTextView,
                UsbongUtils.IS_TEXTVIEW, udtea.currUsbongNode);
        ImageView myTextImageDisplayImageView = (ImageView) udtea.findViewById(R.id.image_display_imageview);
        //              if (!UsbongUtils.setImageDisplay(myTextImageDisplayImageView, myTree+".utree/res/" +UsbongUtils.getResName(udtea.currUsbongNode))) {
        if (!UsbongUtils.setImageDisplay(myTextImageDisplayImageView, udtea.myTree,
                UsbongUtils.getResName(udtea.currUsbongNode))) {
            //Reference: http://www.anddev.org/tinytut_-_get_resources_by_name__getidentifier_-t460.html; last accessed 14 Sept 2011
            //                 Resources myRes = getResources();
            myDrawableImage = myRes
                    .getDrawable(myRes.getIdentifier("no_image", "drawable", udtea.myPackageName));
            myTextImageDisplayImageView.setImageDrawable(myDrawableImage);
        }
    } else if (udtea.currScreen == udtea.IMAGE_TEXT_DISPLAY_SCREEN) {
        udtea.setContentView(R.layout.image_text_display_screen);
        udtea.initBackNextButtons();
        TextView myImageTextDisplayTextView = (TextView) udtea.findViewById(R.id.image_text_display_textview);
        myImageTextDisplayTextView = (TextView) UsbongUtils.applyTagsInView(
                UsbongDecisionTreeEngineActivity.getInstance(), myImageTextDisplayTextView,
                UsbongUtils.IS_TEXTVIEW, udtea.currUsbongNode);
        ImageView myImageTextDisplayImageView = (ImageView) udtea.findViewById(R.id.image_display_imageview);

        if (!UsbongUtils.setImageDisplay(myImageTextDisplayImageView, udtea.myTree,
                UsbongUtils.getResName(udtea.currUsbongNode))) {
            //Reference: http://www.anddev.org/tinytut_-_get_resources_by_name__getidentifier_-t460.html; last accessed 14 Sept 2011
            //                 Resources myRes = getResources();
            myDrawableImage = myRes
                    .getDrawable(myRes.getIdentifier("no_image", "drawable", udtea.myPackageName));
            myImageTextDisplayImageView.setImageDrawable(myDrawableImage);
        }
    } else if (udtea.currScreen == udtea.GPS_LOCATION_SCREEN) {
        udtea.setContentView(R.layout.gps_location_screen);
        udtea.initBackNextButtons();
        TextView myGPSLocationTextView = (TextView) udtea.findViewById(R.id.gps_location_textview);
        myGPSLocationTextView = (TextView) UsbongUtils.applyTagsInView(
                UsbongDecisionTreeEngineActivity.getInstance(), myGPSLocationTextView, UsbongUtils.IS_TEXTVIEW,
                udtea.currUsbongNode);
        //         TextView myLongitudeTextView = (TextView)udtea.findViewById(R.id.longitude_textview);
        //         TextView myLatitudeTextView = (TextView)udtea.findViewById(R.id.latitude_textview);
        hasGottenGPSLocation = false;

        locationResult = new LocationResult() {
            @Override
            public void gotLocation(Location location) {
                //Got the location!
                System.out.println(">>>>>>>>>>>>>>>>>location: " + location);
                if (udtea.currScreen == udtea.GPS_LOCATION_SCREEN) {
                    if (location != null) {
                        myLongitude = location.getLongitude() + "";
                        myLatitude = location.getLatitude() + "";

                        myLongitudeTextView = (TextView) udtea.findViewById(R.id.longitude_textview);
                        myLatitudeTextView = (TextView) udtea.findViewById(R.id.latitude_textview);

                        hasGottenGPSLocation = true;

                        udtea.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                myLongitudeTextView.setText("long: " + myLongitude);
                                myLatitudeTextView.setText("lat: " + myLatitude);
                            }
                        });
                    } else {
                        Toast.makeText(UsbongDecisionTreeEngineActivity.getInstance(),
                                "Error getting location. Please make sure you are not inside a building.",
                                Toast.LENGTH_SHORT).show();
                    }
                } else {
                    hasGottenGPSLocation = true; //to stop the cycling progress bar
                }
            }
        };
        //         myLoadingProgressBar =  new ProgressBar(udtea);
        //         myLoadingProgressBar.setIndeterminate(false);
        //         myLoadingProgressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);         

        udtea.myLocation = new FedorMyLocation();
        udtea.myLocation.getLocation(udtea, locationResult);

        myLoadingProgressBar = (ProgressBar) udtea.findViewById(R.id.progressBar);
        new ProgressTask().execute();

    } else if (udtea.currScreen == udtea.YES_NO_DECISION_SCREEN) {
        udtea.setContentView(R.layout.yes_no_decision_screen);
        udtea.initBackNextButtons();
        TextView myYesNoDecisionScreenTextView = (TextView) udtea.findViewById(R.id.yes_no_decision_textview);
        myYesNoDecisionScreenTextView = (TextView) UsbongUtils.applyTagsInView(
                UsbongDecisionTreeEngineActivity.getInstance(), myYesNoDecisionScreenTextView,
                UsbongUtils.IS_TEXTVIEW, udtea.currUsbongNode);
        RadioButton myYesRadioButton = (RadioButton) udtea.findViewById(R.id.yes_radiobutton);
        myYesRadioButton.setText(udtea.yesStringValue);
        myYesRadioButton.setTextSize(20);
        RadioButton myNoRadioButton = (RadioButton) udtea.findViewById(R.id.no_radiobutton);
        myNoRadioButton.setText(udtea.noStringValue);
        myNoRadioButton.setTextSize(20);
        if (myStringToken.equals("N")) {
            myNoRadioButton.setChecked(true);
        } else if ((myStringToken.equals("Y"))) {
            myYesRadioButton.setChecked(true);
        }
    } else if (udtea.currScreen == udtea.SEND_TO_CLOUD_BASED_SERVICE_SCREEN) {
        udtea.setContentView(R.layout.yes_no_decision_screen);
        udtea.initBackNextButtons();
        TextView mySendToCloudBasedServiceScreenTextView = (TextView) udtea
                .findViewById(R.id.yes_no_decision_textview);
        mySendToCloudBasedServiceScreenTextView = (TextView) UsbongUtils.applyTagsInView(
                UsbongDecisionTreeEngineActivity.getInstance(), mySendToCloudBasedServiceScreenTextView,
                UsbongUtils.IS_TEXTVIEW, udtea.currUsbongNode);
        RadioButton mySendToCloudBasedServiceScreenYesRadioButton = (RadioButton) udtea
                .findViewById(R.id.yes_radiobutton);
        mySendToCloudBasedServiceScreenYesRadioButton.setText(udtea.yesStringValue);
        mySendToCloudBasedServiceScreenYesRadioButton.setTextSize(20);
        RadioButton mySendToCloudBasedServiceScreenNoRadioButton = (RadioButton) udtea
                .findViewById(R.id.no_radiobutton);
        mySendToCloudBasedServiceScreenNoRadioButton.setText(udtea.noStringValue);
        mySendToCloudBasedServiceScreenNoRadioButton.setTextSize(20);
        if (myStringToken.equals("N")) {
            mySendToCloudBasedServiceScreenNoRadioButton.setChecked(true);
        } else if ((myStringToken.equals("Y"))) {
            mySendToCloudBasedServiceScreenYesRadioButton.setChecked(true);
        }
    } else if (udtea.currScreen == udtea.SEND_TO_WEBSERVER_SCREEN) {
        udtea.setContentView(R.layout.send_to_webserver_screen);
        udtea.initBackNextButtons();
        TextView mySendToWebserverScreenTextView = (TextView) udtea
                .findViewById(R.id.send_to_webserver_textview);
        mySendToWebserverScreenTextView = (TextView) UsbongUtils.applyTagsInView(
                UsbongDecisionTreeEngineActivity.getInstance(), mySendToWebserverScreenTextView,
                UsbongUtils.IS_TEXTVIEW, udtea.currUsbongNode);
        TextView myWebserverURLScreenTextView = (TextView) udtea.findViewById(R.id.webserver_url_textview);

        if (!UsbongUtils.getDestinationServerURL().toString().equals("")) {
            myWebserverURLScreenTextView.setText("[" + UsbongUtils.getDestinationServerURL() + "]");
        } else {
            myWebserverURLScreenTextView.setText("[Warning: No URL specified in Settings.]");
        }

        RadioButton mySendToWebserverYesRadioButton = (RadioButton) udtea.findViewById(R.id.yes_radiobutton);
        mySendToWebserverYesRadioButton.setText(udtea.yesStringValue);
        mySendToWebserverYesRadioButton.setTextSize(20);
        RadioButton mySendToWebserverNoRadioButton = (RadioButton) udtea.findViewById(R.id.no_radiobutton);
        mySendToWebserverNoRadioButton.setText(udtea.noStringValue);
        mySendToWebserverNoRadioButton.setTextSize(20);
        if (myStringToken.equals("N")) {
            mySendToWebserverNoRadioButton.setChecked(true);
        } else if ((myStringToken.equals("Y"))) {
            mySendToWebserverYesRadioButton.setChecked(true);
        }
    } else if (udtea.currScreen == udtea.END_STATE_SCREEN) {
        udtea.setContentView(R.layout.end_state_screen);
        TextView endStateTextView = (TextView) udtea.findViewById(R.id.end_state_textview);
        if (udtea.currLanguageBeingUsed == UsbongUtils.LANGUAGE_FILIPINO) {
            endStateTextView
                    .setText((String) udtea.getResources().getText(R.string.UsbongEndStateTextViewFILIPINO));
        } else if (udtea.currLanguageBeingUsed == UsbongUtils.LANGUAGE_JAPANESE) {
            endStateTextView
                    .setText((String) udtea.getResources().getText(R.string.UsbongEndStateTextViewJAPANESE));
        } else { //if (udtea.currLanguageBeingUsed==UsbongUtils.LANGUAGE_ENGLISH) {
            endStateTextView
                    .setText((String) udtea.getResources().getText(R.string.UsbongEndStateTextViewENGLISH));
        }
        udtea.initBackNextButtons();
    }
    View myLayout = udtea.findViewById(R.id.parent_layout_id);
    if (!UsbongUtils.setBackgroundImage(myLayout, udtea.myTree, "bg")) {
        myLayout.setBackgroundResource(R.drawable.bg);//default bg
    }

    if ((!udtea.usedBackButton) && (!udtea.hasReturnedFromAnotherActivity)) {
        udtea.usbongNodeContainer.addElement(udtea.currUsbongNode);
        udtea.usbongNodeContainerCounter++;
    } else {
        udtea.usedBackButton = false;
        udtea.hasReturnedFromAnotherActivity = false;
    }
}

From source file:net.net76.lifeiq.TaskiQ.RegisterActivity.java

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

    inputFirstname = (EditText) findViewById(R.id.firstname);
    inputSurname = (EditText) findViewById(R.id.surname);
    inputUserID = (EditText) findViewById(R.id.userID);
    inputEmail = (EditText) findViewById(R.id.email);
    //1 inputPassword = (EditText) findViewById(R.id.password);
    //1inputPassword2 = (EditText) findViewById(R.id.password2);
    Spinner spinner = (Spinner) findViewById(R.id.spinner);
    EULA = (TextView) findViewById(R.id.EULA);

    SpannableString content = new SpannableString(EULA.getText().toString());
    content.setSpan(new UnderlineSpan(), 0, content.length(), 0);
    EULA.setText(content);//from   w w  w. j  a va 2  s .co  m
    EULA.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            PackageInfo versionInfo = getPackageInfo();
            // EULA title
            String title = RegisterActivity.this.getString(R.string.app_name) + " v " + versionInfo.versionName;

            // EULA text
            String message = RegisterActivity.this.getString(R.string.eula_string);

            android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(RegisterActivity.this)
                    .setTitle(title).setMessage(message).setCancelable(false)
                    .setPositiveButton(R.string.accept, new Dialog.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {

                            EULAAccept = true;
                            // Close dialog
                            dialogInterface.dismiss();

                        }
                    }).setNegativeButton(android.R.string.cancel, new Dialog.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                            EULAAccept = false;

                        }

                    });
            builder.create().show();
        }

    });

    // Create an ArrayAdapter using the string array and a default spinner layout
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.Country_array,
            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);
    // Apply the adapter to the spinner
    spinner.setAdapter(adapter);

    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            Log.v("item", (String) parent.getItemAtPosition(position));
            countryString = (String) parent.getItemAtPosition(position);
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
            // TODO Auto-generated method stub
        }
    });

    btnRegister = (Button) findViewById(R.id.btnRegister);
    btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen);

    // Progress dialog
    pDialog = new ProgressDialog(this);
    //pDialog.setCancelable(false);
    pDialog.setCanceledOnTouchOutside(false);

    // Session manager
    session = new SessionManager(getApplicationContext());

    // SQLite database handler
    db = new SQLiteHandler(getApplicationContext());

    // Check if user is already logged in or not
    if (session.isLoggedIn()) {
        // User is already logged in. Take him to main activity
        Intent intent = new Intent(RegisterActivity.this, MainActivity.class);
        startActivity(intent);
        finish();
    }

    // Register Button Click event
    btnRegister.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            String Firstname = inputFirstname.getText().toString();
            String Surname = inputSurname.getText().toString();
            String UserID = inputUserID.getText().toString();
            String email = inputEmail.getText().toString();
            //1    String password = inputPassword.getText().toString();
            //1   String password2 = inputPassword2.getText().toString();

            if (!Firstname.isEmpty() && !Surname.isEmpty() && !email.isEmpty() && !UserID.isEmpty()) {

                if (isEmailValid(email)) {

                    if (!UserID.contains(" ")) {

                        if (!countryString.equals("Select country of residence")) {
                            if (EULAAccept.equals(true)) {

                                if (isNetworkAvaliable(getApplicationContext())) {
                                    registerUser(Firstname, Surname, UserID, email, countryString);
                                } else {
                                    Toast.makeText(getApplicationContext(),
                                            "Currently there is no network. Please try later.",
                                            Toast.LENGTH_SHORT).show();
                                }
                            } else {
                                Toast.makeText(getApplicationContext(),
                                        "Please read and accept End User License Agreement.",
                                        Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            Toast.makeText(getApplicationContext(), "Please select a country of residence.",
                                    Toast.LENGTH_SHORT).show();
                        }

                    } else {
                        Toast.makeText(getApplicationContext(), "In the User ID no spaces are allowed.",
                                Toast.LENGTH_SHORT).show();
                    }

                } else {
                    Toast.makeText(getApplicationContext(), "Please enter a valid email address!",
                            Toast.LENGTH_SHORT).show();
                }

            } else {
                Toast.makeText(getApplicationContext(), "Please enter your details!", Toast.LENGTH_SHORT)
                        .show();
            }
        }
    });

    // Link to Login Screen
    btnLinkToLogin.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {
            Intent i = new Intent(getApplicationContext(), LoginActivity.class);
            startActivity(i);
            finish();
        }
    });

}

From source file:org.travey.travey.QuestionActivity.java

public void prepareQuestions() {
    //add items to spinner
    TextView textView0 = (TextView) findViewById(R.id.textview0);
    TextView textView1 = (TextView) findViewById(R.id.textview1);
    Spinner spinner1 = (Spinner) findViewById(R.id.spinner1);
    spinner1.setOnItemSelectedListener(this);
    TextView textView2 = (TextView) findViewById(R.id.textview2);
    Spinner spinner2 = (Spinner) findViewById(R.id.spinner2);
    spinner2.setOnItemSelectedListener(this);
    TextView textView3 = (TextView) findViewById(R.id.textview3);
    Spinner spinner3 = (Spinner) findViewById(R.id.spinner3);
    spinner3.setOnItemSelectedListener(this);
    TextView textView4 = (TextView) findViewById(R.id.textview4);
    Spinner spinner4 = (Spinner) findViewById(R.id.spinner4);
    spinner4.setOnItemSelectedListener(this);
    TextView textView5 = (TextView) findViewById(R.id.textview5);
    Spinner spinner5 = (Spinner) findViewById(R.id.spinner5);
    spinner5.setOnItemSelectedListener(this);
    TextView textView6 = (TextView) findViewById(R.id.textview6);
    Spinner spinner6 = (Spinner) findViewById(R.id.spinner6);
    spinner6.setOnItemSelectedListener(this);
    TextView textView7 = (TextView) findViewById(R.id.textview7);
    Spinner spinner7 = (Spinner) findViewById(R.id.spinner7);
    spinner7.setOnItemSelectedListener(this);
    TextView textView8 = (TextView) findViewById(R.id.textview8);
    Spinner spinner8 = (Spinner) findViewById(R.id.spinner8);
    spinner8.setOnItemSelectedListener(this);
    Intent i = getIntent();/*from w w  w .  j  a va 2 s  .c om*/
    String tripText = "This " + metersToPhrase(Integer.parseInt(i.getStringExtra("distance"))) + " trip, took "
            + roundDownTo5(((Long.parseLong(i.getStringExtra("finishTime"))
                    - Long.parseLong(i.getStringExtra("startTime"))) / (1000 * 60) % 60))
            + " minutes, and ended at "
            + dateToQuarters(new Date(Long.parseLong(i.getStringExtra("finishTime")))) + " on "
            + simpleDateFormat.format(new Date(Long.parseLong(i.getStringExtra("finishTime")))) + ".";
    textView0.setText(tripText);
    Log.i("**************", "number of questions:" + NUMBER_QUESTIONS);
    if (NUMBER_QUESTIONS >= 1) { //Q1
        textView1.setText(R.string.survey_question_1);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.survey_question_1_choices, R.layout.my_spinner);
        spinner1.setAdapter(adapter);
    } else {
        textView1.setVisibility(View.GONE);
        ((ViewManager) textView1.getParent()).removeView(textView1);
        spinner1.setVisibility(View.GONE);
        ((ViewManager) spinner1.getParent()).removeView(spinner1);
    }
    if (NUMBER_QUESTIONS >= 2) { //Q2
        textView2.setText(R.string.survey_question_2);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.survey_question_2_choices, R.layout.my_spinner);
        spinner2.setAdapter(adapter);
    } else {
        textView2.setVisibility(View.GONE);
        ((ViewManager) textView2.getParent()).removeView(textView2);
        spinner2.setVisibility(View.GONE);
        ((ViewManager) spinner2.getParent()).removeView(spinner2);
    }
    if (NUMBER_QUESTIONS >= 3) { //Q3
        textView3.setText(R.string.survey_question_3);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.survey_question_3_choices, R.layout.my_spinner);
        spinner3.setAdapter(adapter);
    } else {
        textView3.setVisibility(View.GONE);
        ((ViewManager) textView3.getParent()).removeView(textView3);
        spinner3.setVisibility(View.GONE);
        ((ViewManager) spinner3.getParent()).removeView(spinner3);
    }
    if (NUMBER_QUESTIONS >= 4) { //Q4
        textView4.setText(R.string.survey_question_4);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.survey_question_4_choices, R.layout.my_spinner);
        spinner4.setAdapter(adapter);
    } else {
        textView4.setVisibility(View.GONE);
        ((ViewManager) textView4.getParent()).removeView(textView4);
        spinner4.setVisibility(View.GONE);
        ((ViewManager) spinner4.getParent()).removeView(spinner4);
    }
    if (NUMBER_QUESTIONS >= 5) { //Q5
        textView5.setText(R.string.survey_question_5);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.survey_question_5_choices, R.layout.my_spinner);
        spinner5.setAdapter(adapter);
    } else {
        textView5.setVisibility(View.GONE);
        ((ViewManager) textView5.getParent()).removeView(textView5);
        spinner5.setVisibility(View.GONE);
        ((ViewManager) spinner5.getParent()).removeView(spinner5);
    }
    if (NUMBER_QUESTIONS >= 6) { //Q6
        textView6.setText(R.string.survey_question_6);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.survey_question_6_choices, R.layout.my_spinner);
        spinner6.setAdapter(adapter);
    } else {
        textView6.setVisibility(View.GONE);
        ((ViewManager) textView6.getParent()).removeView(textView6);
        spinner6.setVisibility(View.GONE);
        ((ViewManager) spinner6.getParent()).removeView(spinner6);
    }
    if (NUMBER_QUESTIONS >= 7) { //Q7
        textView7.setText(R.string.survey_question_7);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.survey_question_7_choices, R.layout.my_spinner);
        spinner7.setAdapter(adapter);
    } else {
        textView7.setVisibility(View.GONE);
        ((ViewManager) textView7.getParent()).removeView(textView7);
        spinner7.setVisibility(View.GONE);
        ((ViewManager) spinner7.getParent()).removeView(spinner7);
    }
    if (NUMBER_QUESTIONS >= 8) { //Q8
        textView8.setText(R.string.survey_question_8);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.survey_question_8_choices, R.layout.my_spinner);
        spinner8.setAdapter(adapter);
    } else {
        textView8.setVisibility(View.GONE);
        ((ViewManager) textView8.getParent()).removeView(textView8);
        spinner8.setVisibility(View.GONE);
        ((ViewManager) spinner8.getParent()).removeView(spinner8);
    }
}

From source file:com.mantz_it.rfanalyzer.MainActivity.java

public void showRecordingDialog() {
    if (!running || scheduler == null || demodulator == null || source == null) {
        Toast.makeText(MainActivity.this, "Analyzer must be running to start recording", Toast.LENGTH_LONG)
                .show();//from   w ww  .j ava 2s . c om
        return;
    }

    // Check for the WRITE_EXTERNAL_STORAGE permission:
    if (ContextCompat.checkSelfPermission(this,
            "android.permission.WRITE_EXTERNAL_STORAGE") != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[] { "android.permission.WRITE_EXTERNAL_STORAGE" },
                PERMISSION_REQUEST_RECORDING_WRITE_FILES);
        return; // wait for the permission response (handled in onRequestPermissionResult())
    }

    final String externalDir = Environment.getExternalStorageDirectory().getAbsolutePath();
    final int[] supportedSampleRates = source.getSupportedSampleRates();
    final double maxFreqMHz = source.getMaxFrequency() / 1000000f; // max frequency of the source in MHz
    final int sourceType = Integer.valueOf(preferences.getString(getString(R.string.pref_sourceType), "1"));
    final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss", Locale.US);

    // Get references to the GUI components:
    final ScrollView view = (ScrollView) this.getLayoutInflater().inflate(R.layout.start_recording, null);
    final EditText et_filename = (EditText) view.findViewById(R.id.et_recording_filename);
    final EditText et_frequency = (EditText) view.findViewById(R.id.et_recording_frequency);
    final Spinner sp_sampleRate = (Spinner) view.findViewById(R.id.sp_recording_sampleRate);
    final TextView tv_fixedSampleRateHint = (TextView) view.findViewById(R.id.tv_recording_fixedSampleRateHint);
    final CheckBox cb_stopAfter = (CheckBox) view.findViewById(R.id.cb_recording_stopAfter);
    final EditText et_stopAfter = (EditText) view.findViewById(R.id.et_recording_stopAfter);
    final Spinner sp_stopAfter = (Spinner) view.findViewById(R.id.sp_recording_stopAfter);

    // Setup the sample rate spinner:
    final ArrayAdapter<Integer> sampleRateAdapter = new ArrayAdapter<Integer>(this,
            android.R.layout.simple_list_item_1);
    for (int sampR : supportedSampleRates)
        sampleRateAdapter.add(sampR);
    sampleRateAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    sp_sampleRate.setAdapter(sampleRateAdapter);

    // Add listener to the frequency textfield, the sample rate spinner and the checkbox:
    et_frequency.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) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (et_frequency.getText().length() == 0)
                return;
            double freq = Double.valueOf(et_frequency.getText().toString());
            if (freq < maxFreqMHz)
                freq = freq * 1000000;
            et_filename.setText(simpleDateFormat.format(new Date()) + "_" + SOURCE_NAMES[sourceType] + "_"
                    + (long) freq + "Hz_" + sp_sampleRate.getSelectedItem() + "Sps.iq");
        }
    });
    sp_sampleRate.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            if (et_frequency.getText().length() == 0)
                return;
            double freq = Double.valueOf(et_frequency.getText().toString());
            if (freq < maxFreqMHz)
                freq = freq * 1000000;
            et_filename.setText(simpleDateFormat.format(new Date()) + "_" + SOURCE_NAMES[sourceType] + "_"
                    + (long) freq + "Hz_" + sp_sampleRate.getSelectedItem() + "Sps.iq");
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        }
    });
    cb_stopAfter.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            et_stopAfter.setEnabled(isChecked);
            sp_stopAfter.setEnabled(isChecked);
        }
    });

    // Set default frequency, sample rate and stop after values:
    et_frequency.setText("" + analyzerSurface.getVirtualFrequency());
    int sampleRateIndex = 0;
    int lastSampleRate = preferences.getInt(getString(R.string.pref_recordingSampleRate), 1000000);
    for (; sampleRateIndex < supportedSampleRates.length; sampleRateIndex++) {
        if (supportedSampleRates[sampleRateIndex] >= lastSampleRate)
            break;
    }
    if (sampleRateIndex >= supportedSampleRates.length)
        sampleRateIndex = supportedSampleRates.length - 1;
    sp_sampleRate.setSelection(sampleRateIndex);
    cb_stopAfter.toggle(); // just to trigger the listener at least once!
    cb_stopAfter.setChecked(preferences.getBoolean(getString(R.string.pref_recordingStopAfterEnabled), false));
    et_stopAfter.setText("" + preferences.getInt(getString(R.string.pref_recordingStopAfterValue), 10));
    sp_stopAfter.setSelection(preferences.getInt(getString(R.string.pref_recordingStopAfterUnit), 0));

    // disable sample rate selection if demodulation is running:
    if (demodulationMode != Demodulator.DEMODULATION_OFF) {
        sampleRateAdapter.add(source.getSampleRate()); // add the current sample rate in case it's not already in the list
        sp_sampleRate.setSelection(sampleRateAdapter.getPosition(source.getSampleRate())); // select it
        sp_sampleRate.setEnabled(false); // disable the spinner
        tv_fixedSampleRateHint.setVisibility(View.VISIBLE);
    }

    // Show dialog:
    new AlertDialog.Builder(this).setTitle("Start recording").setView(view)
            .setPositiveButton("Record", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    String filename = et_filename.getText().toString();
                    final int stopAfterUnit = sp_stopAfter.getSelectedItemPosition();
                    final int stopAfterValue = Integer.valueOf(et_stopAfter.getText().toString());
                    //todo check filename

                    // Set the frequency in the source:
                    if (et_frequency.getText().length() == 0)
                        return;
                    double freq = Double.valueOf(et_frequency.getText().toString());
                    if (freq < maxFreqMHz)
                        freq = freq * 1000000;
                    if (freq <= source.getMaxFrequency() && freq >= source.getMinFrequency())
                        source.setFrequency((long) freq);
                    else {
                        Toast.makeText(MainActivity.this, "Frequency is invalid!", Toast.LENGTH_LONG).show();
                        return;
                    }

                    // Set the sample rate (only if demodulator is off):
                    if (demodulationMode == Demodulator.DEMODULATION_OFF)
                        source.setSampleRate((Integer) sp_sampleRate.getSelectedItem());

                    // Open file and start recording:
                    recordingFile = new File(externalDir + "/" + RECORDING_DIR + "/" + filename);
                    recordingFile.getParentFile().mkdir(); // Create directory if it does not yet exist
                    try {
                        scheduler.startRecording(new BufferedOutputStream(new FileOutputStream(recordingFile)));
                    } catch (FileNotFoundException e) {
                        Log.e(LOGTAG,
                                "showRecordingDialog: File not found: " + recordingFile.getAbsolutePath());
                    }

                    // safe preferences:
                    SharedPreferences.Editor edit = preferences.edit();
                    edit.putInt(getString(R.string.pref_recordingSampleRate),
                            (Integer) sp_sampleRate.getSelectedItem());
                    edit.putBoolean(getString(R.string.pref_recordingStopAfterEnabled),
                            cb_stopAfter.isChecked());
                    edit.putInt(getString(R.string.pref_recordingStopAfterValue), stopAfterValue);
                    edit.putInt(getString(R.string.pref_recordingStopAfterUnit), stopAfterUnit);
                    edit.apply();

                    analyzerSurface.setRecordingEnabled(true);

                    updateActionBar();

                    // if stopAfter was selected, start thread to supervise the recording:
                    if (cb_stopAfter.isChecked()) {
                        Thread supervisorThread = new Thread() {
                            @Override
                            public void run() {
                                Log.i(LOGTAG, "recording_superviser: Supervisor Thread started. (Thread: "
                                        + this.getName() + ")");
                                try {
                                    long startTime = System.currentTimeMillis();
                                    boolean stop = false;

                                    // We check once per half a second if the stop criteria is met:
                                    Thread.sleep(500);
                                    while (recordingFile != null && !stop) {
                                        switch (stopAfterUnit) { // see arrays.xml - recording_stopAfterUnit
                                        case 0: /* MB */
                                            if (recordingFile.length() / 1000000 >= stopAfterValue)
                                                stop = true;
                                            break;
                                        case 1: /* GB */
                                            if (recordingFile.length() / 1000000000 >= stopAfterValue)
                                                stop = true;
                                            break;
                                        case 2: /* sec */
                                            if (System.currentTimeMillis() - startTime >= stopAfterValue * 1000)
                                                stop = true;
                                            break;
                                        case 3: /* min */
                                            if (System.currentTimeMillis() - startTime >= stopAfterValue * 1000
                                                    * 60)
                                                stop = true;
                                            break;
                                        }
                                    }
                                    // stop recording:
                                    stopRecording();
                                } catch (InterruptedException e) {
                                    Log.e(LOGTAG, "recording_superviser: Interrupted!");
                                } catch (NullPointerException e) {
                                    Log.e(LOGTAG, "recording_superviser: Recording file is null!");
                                }
                                Log.i(LOGTAG, "recording_superviser: Supervisor Thread stopped. (Thread: "
                                        + this.getName() + ")");
                            }
                        };
                        supervisorThread.start();
                    }
                }
            }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    // do nothing
                }
            }).show().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}