List of usage examples for android.widget Switch isChecked
@ViewDebug.ExportedProperty @Override public boolean isChecked()
From source file:com.facebook.samples.loginsample.accountkit.AccountKitLoginActivity.java
private AccountKitConfiguration.AccountKitConfigurationBuilder createAccountKitConfiguration( final LoginType loginType) { AccountKitConfiguration.AccountKitConfigurationBuilder configurationBuilder = new AccountKitConfiguration.AccountKitConfigurationBuilder( loginType, getResponseType()); final Switch titleTypeSwitch = (Switch) findViewById(R.id.title_type_switch); final Switch stateParamSwitch = (Switch) findViewById(R.id.state_param_switch); final Switch facebookNotificationsSwitch = (Switch) findViewById(R.id.facebook_notification_switch); final Switch useManualWhiteListBlacklist = (Switch) findViewById(R.id.whitelist_blacklist_switch); final Switch readPhoneStateSwitch = (Switch) findViewById(R.id.read_phone_state_switch); final Switch receiveSMS = (Switch) findViewById(R.id.receive_sms_switch); if (titleTypeSwitch != null && titleTypeSwitch.isChecked()) { configurationBuilder.setTitleType(com.facebook.accountkit.ui.AccountKitActivity.TitleType.APP_NAME); }//from w ww . j a v a 2 s . c o m if (advancedUISwitch != null && advancedUISwitch.isChecked()) { if (isReverbThemeSelected()) { if (switchLoginTypeReceiver == null) { switchLoginTypeReceiver = new BroadcastReceiver() { @Override public void onReceive(final Context context, final Intent intent) { final String loginTypeString = intent.getStringExtra(ReverbUIManager.LOGIN_TYPE_EXTRA); if (loginTypeString == null) { return; } final LoginType loginType = LoginType.valueOf(loginTypeString); if (loginType == null) { return; } onLogin(loginType); } }; LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver( switchLoginTypeReceiver, new IntentFilter(ReverbUIManager.SWITCH_LOGIN_TYPE_EVENT)); } configurationBuilder.setAdvancedUIManager( new ReverbUIManager(confirmButton, entryButton, loginType, textPosition, selectedThemeId)); } else { configurationBuilder.setAdvancedUIManager( new AccountKitSampleAdvancedUIManager(confirmButton, entryButton, textPosition, loginType)); } } if (stateParamSwitch != null && stateParamSwitch.isChecked()) { initialStateParam = UUID.randomUUID().toString(); configurationBuilder.setInitialAuthState(initialStateParam); } if (facebookNotificationsSwitch != null && !facebookNotificationsSwitch.isChecked()) { configurationBuilder.setFacebookNotificationsEnabled(false); } if (selectedThemeId > 0) { configurationBuilder.setTheme(selectedThemeId); } if (useManualWhiteListBlacklist != null && useManualWhiteListBlacklist.isChecked()) { final String[] blackList = getResources().getStringArray(R.array.blacklistedSmsCountryCodes); final String[] whiteList = getResources().getStringArray(R.array.whitelistedSmsCountryCodes); configurationBuilder.setSMSBlacklist(blackList); configurationBuilder.setSMSWhitelist(whiteList); } if (readPhoneStateSwitch != null && !(readPhoneStateSwitch.isChecked())) { configurationBuilder.setReadPhoneStateEnabled(false); } if (receiveSMS != null && !receiveSMS.isChecked()) { configurationBuilder.setReceiveSMS(false); } return configurationBuilder; }
From source file:nl.hnogames.domoticz.Adapters.DashboardAdapter.java
/** * Set the data for a dimmer//from w ww .j a v a 2 s.c om * * @param mDeviceInfo Device info * @param holder Holder to use */ private void setDimmerRowData(final DevicesInfo mDeviceInfo, final DataObjectHolder holder, final boolean isRGB) { String text; holder.isProtected = mDeviceInfo.isProtected(); if (holder.switch_name != null) holder.switch_name.setText(mDeviceInfo.getName()); if (holder.signal_level != null) { text = context.getString(R.string.last_update) + ": " + UsefulBits.getFormattedDate(context, mDeviceInfo.getLastUpdateDateTime().getTime()); holder.signal_level.setText(text); } if (holder.switch_battery_level != null) { text = context.getString(R.string.status) + ": " + String.valueOf(mDeviceInfo.getStatus()); holder.switch_battery_level.setText(text); } holder.switch_dimmer_level.setId(mDeviceInfo.getIdx() + ID_TEXTVIEW); String percentage = calculateDimPercentage(mDeviceInfo.getMaxDimLevel(), mDeviceInfo.getLevel()); holder.switch_dimmer_level.setText(percentage); Picasso.with(context) .load(DomoticzIcons.getDrawableIcon(mDeviceInfo.getTypeImg(), mDeviceInfo.getType(), mDeviceInfo.getSubType(), mDeviceInfo.getStatusBoolean(), mDeviceInfo.getUseCustomImage(), mDeviceInfo.getImage())) .into(holder.iconRow); if (!mDeviceInfo.getStatusBoolean()) holder.iconRow.setAlpha(0.5f); else holder.iconRow.setAlpha(1f); holder.dimmerOnOffSwitch.setId(mDeviceInfo.getIdx() + ID_SWITCH); holder.dimmerOnOffSwitch.setOnCheckedChangeListener(null); holder.dimmerOnOffSwitch.setChecked(mDeviceInfo.getStatusBoolean()); holder.dimmerOnOffSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean checked) { handleOnOffSwitchClick(compoundButton.getId(), checked); mDeviceInfo.setStatusBoolean(checked); if (checked) { holder.switch_dimmer_level.setVisibility(View.VISIBLE); holder.dimmer.setVisibility(View.VISIBLE); if (holder.dimmer.getProgress() <= 10) { holder.dimmer.setProgress(20);//dimmer turned on with default progress value } if (isRGB) holder.buttonColor.setVisibility(View.VISIBLE); } else { holder.switch_dimmer_level.setVisibility(View.GONE); holder.dimmer.setVisibility(View.GONE); if (isRGB) holder.buttonColor.setVisibility(View.GONE); } if (!checked) holder.iconRow.setAlpha(0.5f); else holder.iconRow.setAlpha(1f); } }); holder.dimmer.setProgress(mDeviceInfo.getLevel()); holder.dimmer.setMax(mDeviceInfo.getMaxDimLevel()); holder.dimmer.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { String percentage = calculateDimPercentage(seekBar.getMax(), progress); TextView switch_dimmer_level = (TextView) seekBar.getRootView() .findViewById(mDeviceInfo.getIdx() + ID_TEXTVIEW); if (switch_dimmer_level != null) switch_dimmer_level.setText(percentage); } @Override public void onStartTrackingTouch(SeekBar seekBar) { previousDimmerValue = seekBar.getProgress(); } @Override public void onStopTrackingTouch(SeekBar seekBar) { int progress = seekBar.getProgress(); Switch dimmerOnOffSwitch = null; try { dimmerOnOffSwitch = (Switch) seekBar.getRootView() .findViewById(mDeviceInfo.getIdx() + ID_SWITCH); if (progress == 0 && dimmerOnOffSwitch.isChecked()) { dimmerOnOffSwitch.setChecked(false); seekBar.setProgress(previousDimmerValue); } else if (progress > 0 && !dimmerOnOffSwitch.isChecked()) { dimmerOnOffSwitch.setChecked(true); } } catch (Exception ex) { /*else we don't use a switch, but buttons */} handleDimmerChange(mDeviceInfo.getIdx(), progress + 1, false); mDeviceInfo.setLevel(progress); } }); if (!mDeviceInfo.getStatusBoolean()) { holder.switch_dimmer_level.setVisibility(View.GONE); holder.dimmer.setVisibility(View.GONE); if (isRGB) holder.buttonColor.setVisibility(View.GONE); } else { holder.switch_dimmer_level.setVisibility(View.VISIBLE); holder.dimmer.setVisibility(View.VISIBLE); if (isRGB) holder.buttonColor.setVisibility(View.VISIBLE); } if (holder.buttonLog != null) { holder.buttonLog.setId(mDeviceInfo.getIdx()); holder.buttonLog.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { handleLogButtonClick(v.getId()); } }); } if (isRGB && holder.buttonColor != null) { holder.buttonColor.setId(mDeviceInfo.getIdx()); holder.buttonColor.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { handleColorButtonClick(v.getId()); } }); } }
From source file:de.bogutzky.psychophysiocollector.app.MainActivity.java
private void showSettings() { final SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE); int selfReportIntervalSpinnerPosition = sharedPref.getInt("selfReportIntervalSpinnerPosition", 2); int selfReportVarianceSpinnerPosition = sharedPref.getInt("selfReportVarianceSpinnerPosition", 0); int questionnaireSpinnerPosition = sharedPref.getInt("questionnaireSpinnerPosition", 0); //int baselineQuestionnaireSpinnerPosition = sharedPref.getInt("baselineQuestionnaireSpinnerPosition", 0); String activityName = sharedPref.getString("activityName", ""); String participantFirstName = sharedPref.getString("participantFirstName", ""); String participantLastName = sharedPref.getString("participantLastName", ""); boolean configureInterval = sharedPref.getBoolean("configureInterval", false); final Dialog dialog = new Dialog(this); dialog.setContentView(R.layout.settings); dialog.setTitle(getString(R.string.action_settings)); dialog.setCancelable(true);/* ww w.j a v a 2 s .c o m*/ WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); lp.copyFrom(dialog.getWindow().getAttributes()); lp.width = WindowManager.LayoutParams.MATCH_PARENT; lp.height = WindowManager.LayoutParams.MATCH_PARENT; dialog.getWindow().setAttributes(lp); selfReportIntervalSpinner = (Spinner) dialog.findViewById(R.id.self_report_interval_spinner); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.study_protocol_settings_self_report_interval_values, android.R.layout.simple_spinner_item); selfReportIntervalSpinner.setAdapter(adapter); selfReportIntervalSpinner.setSelection(selfReportIntervalSpinnerPosition); selfReportVarianceSpinner = (Spinner) dialog.findViewById(R.id.self_report_variance_spinner); ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(this, R.array.study_protocol_settings_self_report_variance_values, android.R.layout.simple_spinner_item); selfReportVarianceSpinner.setAdapter(adapter2); selfReportVarianceSpinner.setSelection(selfReportVarianceSpinnerPosition); questionnaireSpinner = (Spinner) dialog.findViewById(R.id.questionnaireSpinner); //baselineQuestionnaireSpinner = (Spinner) dialog.findViewById(R.id.baseline_questionnaireSpinner); String[] questionnaireTitles = new String[0]; try { questionnaireTitles = new String[questionnaireCount]; for (int i = 0; i < questionnaireCount; i++) { String questionnaireFilename = questionnaireFilenames[i]; String questionnairePath = "questionnaires/" + localeString + "/" + questionnaireFilename; try { JSONObject questionnaire = Utils .getJSONObjectFromInputStream(getAssets().open(questionnairePath)); String questionnaireTitle = questionnaire.getJSONObject("questionnaire").getString("title"); questionnaireTitles[i] = questionnaireTitle; } catch (JSONException e) { e.printStackTrace(); } } } catch (IOException e) { e.printStackTrace(); } ArrayAdapter<String> qSpinnerAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, questionnaireTitles); questionnaireSpinner.setAdapter(qSpinnerAdapter); questionnaireSpinner.setSelection(questionnaireSpinnerPosition); //baselineQuestionnaireSpinner.setAdapter(qSpinnerAdapter); //baselineQuestionnaireSpinner.setSelection(baselineQuestionnaireSpinnerPosition); final EditText participantFirstNameEditText = (EditText) dialog .findViewById(R.id.participant_first_name_edit_text); final EditText participantLastNameEditText = (EditText) dialog .findViewById(R.id.participant_last_name_edit_text); final EditText activityNameEditText = (EditText) dialog.findViewById(R.id.activity_name_edit_text); participantFirstNameEditText.setText(participantFirstName); participantLastNameEditText.setText(participantLastName); activityNameEditText.setText(activityName); final Switch configureIntervalSwitch = (Switch) dialog.findViewById(R.id.configure_interval_switch); configureIntervalSwitch.setChecked(configureInterval); if (configureInterval) { dialog.findViewById(R.id.configure_interval_layout).setVisibility(View.VISIBLE); dialog.findViewById(R.id.configure_variance_layout).setVisibility(View.VISIBLE); } else { dialog.findViewById(R.id.configure_interval_layout).setVisibility(View.GONE); dialog.findViewById(R.id.configure_variance_layout).setVisibility(View.GONE); } Button saveButton = (Button) dialog.findViewById(R.id.saveButton); saveButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { selfReportInterval = Integer.valueOf(selfReportIntervalSpinner.getSelectedItem().toString()); selfReportVariance = Integer.valueOf(selfReportVarianceSpinner.getSelectedItem().toString()); MainActivity.this.participantFirstName = participantFirstNameEditText.getText().toString().trim(); MainActivity.this.participantLastName = participantLastNameEditText.getText().toString().trim(); MainActivity.this.activityName = activityNameEditText.getText().toString().trim(); MainActivity.this.intervalConfigured = configureIntervalSwitch.isChecked(); SharedPreferences.Editor editor = sharedPref.edit(); editor.putInt("selfReportIntervalSpinnerPosition", selfReportIntervalSpinner.getSelectedItemPosition()); editor.putInt("selfReportVarianceSpinnerPosition", selfReportVarianceSpinner.getSelectedItemPosition()); editor.putInt("questionnaireSpinnerPosition", questionnaireSpinner.getSelectedItemPosition()); //editor.putInt("baselineQuestionnaireSpinnerPosition", baselineQuestionnaireSpinner.getSelectedItemPosition()); editor.putInt("selfReportInterval", Integer.valueOf(selfReportIntervalSpinner.getSelectedItem().toString())); editor.putInt("selfReportVariance", Integer.valueOf(selfReportVarianceSpinner.getSelectedItem().toString())); editor.putString("participantFirstName", participantFirstNameEditText.getText().toString().trim()); editor.putString("participantLastName", participantLastNameEditText.getText().toString().trim()); editor.putString("activityName", activityNameEditText.getText().toString().trim()); editor.putBoolean("configureInterval", configureIntervalSwitch.isChecked()); editor.apply(); dialog.dismiss(); } }); configureIntervalSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { dialog.findViewById(R.id.configure_interval_layout).setVisibility(View.VISIBLE); dialog.findViewById(R.id.configure_variance_layout).setVisibility(View.VISIBLE); } else { dialog.findViewById(R.id.configure_interval_layout).setVisibility(View.GONE); dialog.findViewById(R.id.configure_variance_layout).setVisibility(View.GONE); } } }); dialog.show(); }
From source file:com.almalence.plugins.capture.video.VideoCapturePlugin.java
public void TimeLapseDialog() { if (isRecording) return;//from w w w .j a va 2 s .c o m SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ApplicationScreen.getMainContext()); interval = Integer.valueOf(prefs.getString("timelapseInterval", "0")); measurementVal = Integer.valueOf(prefs.getString("timelapseMeasurementVal", "0")); // show time lapse settings timeLapseDialog = new TimeLapseDialog(ApplicationScreen.instance); timeLapseDialog.setContentView(R.layout.plugin_capture_video_timelapse_dialog); final NumberPicker np = (NumberPicker) timeLapseDialog.findViewById(R.id.numberPicker1); np.setMaxValue(16); np.setMinValue(0); np.setValue(interval); np.setDisplayedValues(stringInterval); np.setWrapSelectorWheel(false); np.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS); final NumberPicker np2 = (NumberPicker) timeLapseDialog.findViewById(R.id.numberPicker2); np2.setMaxValue(2); np2.setMinValue(0); np2.setValue(measurementVal); np2.setWrapSelectorWheel(false); np2.setDisplayedValues(stringMeasurement); np2.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS); final Switch sw = (Switch) timeLapseDialog.findViewById(R.id.timelapse_switcher); // disable/enable controls in dialog sw.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (!sw.isChecked()) { swChecked = false; } else { swChecked = true; } } }); np2.setOnScrollListener(new NumberPicker.OnScrollListener() { @Override public void onScrollStateChange(NumberPicker numberPicker, int scrollState) { sw.setChecked(true); } }); np.setOnScrollListener(new NumberPicker.OnScrollListener() { @Override public void onScrollStateChange(NumberPicker numberPicker, int scrollState) { sw.setChecked(true); } }); // disable control in dialog by default if (!swChecked) { sw.setChecked(false); } else { sw.setChecked(true); } timeLapseDialog.setOnDismissListener(new OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { if (swChecked) { measurementVal = np2.getValue(); interval = np.getValue(); SharedPreferences prefs = PreferenceManager .getDefaultSharedPreferences(ApplicationScreen.getMainContext()); Editor editor = prefs.edit(); editor.putString("timelapseMeasurementVal", String.valueOf(measurementVal)); editor.putString("timelapseInterval", String.valueOf(interval)); editor.commit(); timeLapseButton.setImageDrawable(ApplicationScreen.getAppResources() .getDrawable(R.drawable.plugin_capture_video_timelapse_active)); ApplicationScreen.getGUIManager().setShutterIcon(ShutterButton.RECORDER_START); } else { timeLapseButton.setImageDrawable(ApplicationScreen.getAppResources() .getDrawable(R.drawable.plugin_capture_video_timelapse_inactive)); ApplicationScreen.getGUIManager().setShutterIcon(ShutterButton.RECORDER_START); } } }); timeLapseDialog.show(); }
From source file:tv.piratemedia.flightcontroller.BluetoothControlFragment.java
@Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { timeoutHandler = new Handler(); throttle = (VerticalSeekBar) view.findViewById(R.id.throttle); final ColorPicker ledColor = (ColorPicker) view.findViewById(R.id.ledColor); final Switch ledOn = (Switch) view.findViewById(R.id.ledSwitch); throttle.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override/* www .j av a 2s . c o m*/ public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { ThrottleCache = progress; if (!blocking) { JSONObject msg = new JSONObject(); try { msg.put("action", "throttle"); msg.put("value", progress); } catch (JSONException e) { e.printStackTrace(); } sendMessage(msg.toString()); timeoutHandler.postDelayed(new Runnable() { @Override public void run() { blocking = false; JSONObject msg = new JSONObject(); try { msg.put("action", "throttle"); msg.put("value", ThrottleCache); } catch (JSONException e) { e.printStackTrace(); } sendMessage(msg.toString()); } }, 150); blocking = true; } } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { JSONObject msg = new JSONObject(); try { msg.put("action", "throttle"); msg.put("value", seekBar.getProgress()); } catch (JSONException e) { e.printStackTrace(); } sendMessage(msg.toString()); } }); ledColor.setShowOldCenterColor(false); ledColor.setOnColorChangedListener(new ColorPicker.OnColorChangedListener() { @Override public void onColorChanged(int i) { if (!blocking) { JSONObject msg = new JSONObject(); try { msg.put("action", "led"); msg.put("color", i); msg.put("on", ledOn.isChecked()); } catch (JSONException e) { e.printStackTrace(); } sendMessage(msg.toString()); timeoutHandler.postDelayed(new Runnable() { @Override public void run() { blocking = false; } }, 150); blocking = true; } } }); ledOn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { JSONObject msg = new JSONObject(); try { msg.put("action", "led"); msg.put("color", ledColor.getColor()); msg.put("on", isChecked); } catch (JSONException e) { e.printStackTrace(); } sendMessage(msg.toString()); } }); longitude = (TextView) view.findViewById(R.id.longitude); latitude = (TextView) view.findViewById(R.id.latitude); altitude = (TextView) view.findViewById(R.id.altitude); pitchCorrection = (TextView) view.findViewById(R.id.picth_correction); rollCorrection = (TextView) view.findViewById(R.id.roll_correction); LeftStick = (JoystickView) view.findViewById(R.id.left_stick); RightStick = (JoystickView) view.findViewById(R.id.right_stick); LeftStick.setOnJoystickMoveListener(new JoystickView.OnJoystickMoveListener() { @Override public void onValueChanged(int angle, int power, int direction) { JSONObject msg = new JSONObject(); try { msg.put("action", "movement"); msg.put("pitch", 0); msg.put("roll", 0); } catch (JSONException e) { e.printStackTrace(); } if (power == 0) { sendMessage(msg.toString()); } else { if (angle > -10 && angle < 10) { //just pitch forwards try { msg.put("pitch", Math.round((double) power / SpeedDivider)); } catch (JSONException e) { e.printStackTrace(); } } else if (angle < -170 || angle > 170) { //just pitch backwards try { msg.put("pitch", -Math.round((double) power / SpeedDivider)); } catch (JSONException e) { e.printStackTrace(); } } else if (angle < -80 && angle > -100) { //just roll Left try { msg.put("roll", -Math.round((double) power / SpeedDivider)); } catch (JSONException e) { e.printStackTrace(); } } else if (angle > 80 && angle < 100) { //just roll right try { msg.put("roll", Math.round((double) power / SpeedDivider)); } catch (JSONException e) { e.printStackTrace(); } } else { // combination int pitch = 0; int roll = 0; if (angle > 0 && angle < 90) { //forwards and right roll = Math.round(power * (float) angle / 90.0f); pitch = Math.round(power - roll); } else if (angle > 90 && angle < 180) { angle = angle - 90; //backwards and right pitch = Math.round(power * (float) angle / 90.0f); roll = Math.round(power - pitch); pitch = -pitch; } else if (angle < 0 && angle > -90) { angle = -angle; //forwards and left roll = Math.round(power * (float) angle / 90.0f); pitch = Math.round(power - roll); roll = -roll; } else { angle = (-angle) - 90; // backwards and right pitch = Math.round(power * (float) angle / 90.0f); roll = -Math.round(power - pitch); pitch = -pitch; } try { msg.put("pitch", Math.round((double) pitch / SpeedDivider)); msg.put("roll", Math.round((double) roll / SpeedDivider)); } catch (JSONException e) { e.printStackTrace(); } } sendMessage(msg.toString()); } } }, 150); RightStick.setOnJoystickMoveListener(new JoystickView.OnJoystickMoveListener() { @Override public void onValueChanged(int angle, int power, int direction) { JSONObject msg = new JSONObject(); try { msg.put("action", "movement"); msg.put("yaw", 0); } catch (JSONException e) { e.printStackTrace(); } int yaw = 0; int pitch = 0; if (angle > 0 && angle < 90) { //forwards and right yaw = Math.round(power * (float) angle / 90.0f); pitch = Math.round(power - yaw); } else if (angle > 90 && angle < 180) { angle = angle - 90; //backwards and right pitch = Math.round(power * (float) angle / 90.0f); yaw = Math.round(power - pitch); pitch = -pitch; } else if (angle < 0 && angle > -90) { angle = -angle; //forwards and left yaw = Math.round(power * (float) angle / 90.0f); pitch = Math.round(power - yaw); yaw = -yaw; } else { angle = (-angle) - 90; // backwards and right pitch = Math.round(power * (float) angle / 90.0f); yaw = -Math.round(power - pitch); pitch = -pitch; } try { msg.put("yaw", Math.round((double) yaw / SpeedDivider)); } catch (JSONException e) { e.printStackTrace(); } sendMessage(msg.toString()); } }, 150); }
From source file:net.opendasharchive.openarchive.ReviewMediaActivity.java
private void deleteMedia() { final Switch swDeleteLocal = new Switch(this); final Switch swDeleteRemote = new Switch(this); LinearLayout linearLayoutGroup = new LinearLayout(this); linearLayoutGroup.setOrientation(LinearLayout.VERTICAL); linearLayoutGroup.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); swDeleteLocal.setTextOn(getString(R.string.answer_yes)); swDeleteLocal.setTextOff(getString(R.string.answer_no)); TextView tvLocal = new TextView(this); tvLocal.setText(R.string.delete_local); LinearLayout linearLayout = new LinearLayout(this); linearLayout.setOrientation(LinearLayout.HORIZONTAL); linearLayout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); linearLayout.setGravity(Gravity.CENTER_HORIZONTAL); linearLayout.addView(tvLocal);/*from w ww .ja v a2s. c o m*/ linearLayout.addView(swDeleteLocal); linearLayoutGroup.addView(linearLayout); if (mMedia.getServerUrl() != null) { swDeleteRemote.setTextOn(getString(R.string.answer_yes)); swDeleteRemote.setTextOff(getString(R.string.answer_no)); TextView tvRemote = new TextView(this); tvRemote.setText(R.string.delete_remote); LinearLayout linearLayoutRemote = new LinearLayout(this); linearLayoutRemote.setOrientation(LinearLayout.HORIZONTAL); linearLayoutRemote.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); linearLayoutRemote.setGravity(Gravity.CENTER_HORIZONTAL); linearLayoutRemote.addView(tvRemote); linearLayoutRemote.addView(swDeleteRemote); linearLayoutGroup.addView(linearLayoutRemote); } AlertDialog.Builder build = new AlertDialog.Builder(ReviewMediaActivity.this).setTitle(R.string.menu_delete) .setMessage(R.string.alert_delete_media).setView(linearLayoutGroup).setCancelable(true) .setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { //do nothing } }) .setPositiveButton(R.string.dialog_ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { deleteMedia(swDeleteLocal.isChecked(), swDeleteRemote.isChecked()); finish(); } }); build.create().show(); }
From source file:fiskinfoo.no.sintef.fiskinfoo.MapFragment.java
private void createProximityAlertSetupDialog() { final Dialog dialog = dialogInterface.getDialog(getActivity(), R.layout.dialog_proximity_alert_create, R.string.create_proximity_alert); Button setProximityAlertWatcherButton = (Button) dialog .findViewById(R.id.create_proximity_alert_create_alert_watcher_button); Button stopCurrentProximityAlertWatcherButton = (Button) dialog .findViewById(R.id.create_proximity_alert_stop_existing_alert_button); Button cancelButton = (Button) dialog.findViewById(R.id.create_proximity_alert_cancel_button); SeekBar seekbar = (SeekBar) dialog.findViewById(R.id.create_proximity_alert_seekBar); final EditText radiusEditText = (EditText) dialog.findViewById(R.id.create_proximity_alert_range_edit_text); final Switch formatSwitch = (Switch) dialog.findViewById(R.id.create_proximity_alert_format_switch); final double seekBarStepSize = (double) (getResources() .getInteger(R.integer.proximity_alert_maximum_warning_range_meters) - getResources().getInteger(R.integer.proximity_alert_minimum_warning_range_meters)) / 100; radiusEditText.setText(/*from w ww.j av a2s .c o m*/ String.valueOf(getResources().getInteger(R.integer.proximity_alert_minimum_warning_range_meters))); formatSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { buttonView.setText(getString(R.string.range_format_nautical_miles)); } else { buttonView.setText(getString(R.string.range_format_meters)); } } }); seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (fromUser) { String range = String.valueOf( (int) (getResources().getInteger(R.integer.proximity_alert_minimum_warning_range_meters) + (seekBarStepSize * progress))); radiusEditText.setText(range); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); setProximityAlertWatcherButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String toastText; if (proximityAlertWatcher == null) { toastText = getString(R.string.proximity_alert_set); } else { toastText = getString(R.string.proximity_alert_replace); } if (proximityAlertWatcher != null) { proximityAlertWatcher.cancel(true); } mGpsLocationTracker = new GpsLocationTracker(getActivity()); double latitude, longitude; if (mGpsLocationTracker.canGetLocation()) { latitude = mGpsLocationTracker.getLatitude(); cachedLat = latitude; longitude = mGpsLocationTracker.getLongitude(); cachedLon = longitude; } else { mGpsLocationTracker.showSettingsAlert(); return; } if (formatSwitch.isChecked()) { cachedDistance = Double.valueOf(radiusEditText.getText().toString()) * getResources().getInteger(R.integer.meters_per_nautical_mile); } else { cachedDistance = Double.valueOf(radiusEditText.getText().toString()); } dialog.dismiss(); Response response; try { String apiName = "fishingfacility"; String format = "OLEX"; String filePath; String fileName = "collisionCheckToolsFile"; response = barentswatchApi.getApi().geoDataDownload(apiName, format); if (response == null) { Log.d(TAG, "RESPONSE == NULL"); throw new InternalError(); } if (fiskInfoUtility.isExternalStorageWritable()) { String directoryPath = Environment .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString(); String directoryName = "FiskInfo"; filePath = directoryPath + "/" + directoryName + "/"; InputStream zippedInputStream = null; try { TypedInput responseInput = response.getBody(); zippedInputStream = responseInput.in(); zippedInputStream = new GZIPInputStream(zippedInputStream); InputSource inputSource = new InputSource(zippedInputStream); InputStream input = new BufferedInputStream(inputSource.getByteStream()); byte data[]; data = FiskInfoUtility.toByteArray(input); InputStream inputStream = new ByteArrayInputStream(data); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); FiskInfoPolygon2D serializablePolygon2D = new FiskInfoPolygon2D(); String line; boolean startSet = false; String[] convertedLine; List<Point> shape = new ArrayList<>(); while ((line = reader.readLine()) != null) { Point currPoint = new Point(); if (line.length() == 0 || line.equals("")) { continue; } if (Character.isLetter(line.charAt(0))) { continue; } convertedLine = line.split("\\s+"); if (line.length() > 150) { Log.d(TAG, "line " + line); } if (convertedLine[0].startsWith("3sl")) { continue; } if (convertedLine[3].equalsIgnoreCase("Garnstart") && startSet) { if (shape.size() == 1) { // Point serializablePolygon2D.addPoint(shape.get(0)); shape = new ArrayList<>(); } else if (shape.size() == 2) { // line serializablePolygon2D.addLine(new Line(shape.get(0), shape.get(1))); shape = new ArrayList<>(); } else { serializablePolygon2D.addPolygon(new Polygon(shape)); shape = new ArrayList<>(); } startSet = false; } if (convertedLine[3].equalsIgnoreCase("Garnstart") && !startSet) { double lat = Double.parseDouble(convertedLine[0]) / 60; double lon = Double.parseDouble(convertedLine[1]) / 60; currPoint.setNewPointValues(lat, lon); shape.add(currPoint); startSet = true; } else if (convertedLine[3].equalsIgnoreCase("Brunsirkel")) { double lat = Double.parseDouble(convertedLine[0]) / 60; double lon = Double.parseDouble(convertedLine[1]) / 60; currPoint.setNewPointValues(lat, lon); shape.add(currPoint); } } reader.close(); new FiskInfoUtility().serializeFiskInfoPolygon2D(filePath + fileName + "." + format, serializablePolygon2D); tools = serializablePolygon2D; } catch (IOException e) { e.printStackTrace(); } catch (ArrayIndexOutOfBoundsException e) { Log.e(TAG, "Error when trying to serialize file."); Toast error = Toast.makeText(getActivity(), "Ingen redskaper i omrdet du definerte", Toast.LENGTH_LONG); e.printStackTrace(); error.show(); return; } finally { try { if (zippedInputStream != null) { zippedInputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } } else { Toast.makeText(v.getContext(), R.string.download_failed, Toast.LENGTH_LONG).show(); dialog.dismiss(); return; } } catch (Exception e) { Log.d(TAG, "Could not download tools file"); Toast.makeText(getActivity(), R.string.download_failed, Toast.LENGTH_LONG).show(); } runScheduledAlarm(getResources().getInteger(R.integer.zero), getResources().getInteger(R.integer.proximity_alert_interval_time_seconds)); Toast.makeText(getActivity(), toastText, Toast.LENGTH_LONG).show(); } }); if (proximityAlertWatcher != null) { TypedValue outValue = new TypedValue(); stopCurrentProximityAlertWatcherButton.setVisibility(View.VISIBLE); getResources().getValue(R.dimen.proximity_alert_dialog_button_text_size_small, outValue, true); float textSize = outValue.getFloat(); setProximityAlertWatcherButton.setTextSize(textSize); stopCurrentProximityAlertWatcherButton.setTextSize(textSize); cancelButton.setTextSize(textSize); stopCurrentProximityAlertWatcherButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { proximityAlertWatcher.cancel(true); proximityAlertWatcher = null; dialog.dismiss(); } }); } cancelButton.setOnClickListener(onClickListenerInterface.getDismissDialogListener(dialog)); dialog.show(); }
From source file:com.mantz_it.rfanalyzer.MainActivity.java
/** * Will pop up a dialog to let the user adjust gain settings *///from w ww . j av a 2 s . c om private void adjustGain() { if (source == null) return; int sourceType = Integer.valueOf(preferences.getString(getString(R.string.pref_sourceType), "1")); switch (sourceType) { case FILE_SOURCE: Toast.makeText(this, getString(R.string.filesource_doesnt_support_gain), Toast.LENGTH_LONG).show(); break; case HACKRF_SOURCE: // Prepare layout: final LinearLayout view_hackrf = (LinearLayout) this.getLayoutInflater().inflate(R.layout.hackrf_gain, null); final SeekBar sb_hackrf_vga = (SeekBar) view_hackrf.findViewById(R.id.sb_hackrf_vga_gain); final SeekBar sb_hackrf_lna = (SeekBar) view_hackrf.findViewById(R.id.sb_hackrf_lna_gain); final TextView tv_hackrf_vga = (TextView) view_hackrf.findViewById(R.id.tv_hackrf_vga_gain); final TextView tv_hackrf_lna = (TextView) view_hackrf.findViewById(R.id.tv_hackrf_lna_gain); sb_hackrf_vga.setMax(HackrfSource.MAX_VGA_RX_GAIN / HackrfSource.VGA_RX_GAIN_STEP_SIZE); sb_hackrf_lna.setMax(HackrfSource.MAX_LNA_GAIN / HackrfSource.LNA_GAIN_STEP_SIZE); sb_hackrf_vga.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { tv_hackrf_vga.setText("" + progress * HackrfSource.VGA_RX_GAIN_STEP_SIZE); ((HackrfSource) source).setVgaRxGain(progress * HackrfSource.VGA_RX_GAIN_STEP_SIZE); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); sb_hackrf_lna.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { tv_hackrf_lna.setText("" + progress * HackrfSource.LNA_GAIN_STEP_SIZE); ((HackrfSource) source).setLnaGain(progress * HackrfSource.LNA_GAIN_STEP_SIZE); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); sb_hackrf_vga.setProgress(((HackrfSource) source).getVgaRxGain() / HackrfSource.VGA_RX_GAIN_STEP_SIZE); sb_hackrf_lna.setProgress(((HackrfSource) source).getLnaGain() / HackrfSource.LNA_GAIN_STEP_SIZE); // Show dialog: AlertDialog hackrfDialog = new AlertDialog.Builder(this).setTitle("Adjust Gain Settings") .setView(view_hackrf).setPositiveButton("Set", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // safe preferences: SharedPreferences.Editor edit = preferences.edit(); edit.putInt(getString(R.string.pref_hackrf_vgaRxGain), sb_hackrf_vga.getProgress() * HackrfSource.VGA_RX_GAIN_STEP_SIZE); edit.putInt(getString(R.string.pref_hackrf_lnaGain), sb_hackrf_lna.getProgress() * HackrfSource.LNA_GAIN_STEP_SIZE); edit.apply(); } }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // do nothing } }).create(); hackrfDialog.setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { // sync source with (new/old) settings int vgaRxGain = preferences.getInt(getString(R.string.pref_hackrf_vgaRxGain), HackrfSource.MAX_VGA_RX_GAIN / 2); int lnaGain = preferences.getInt(getString(R.string.pref_hackrf_lnaGain), HackrfSource.MAX_LNA_GAIN / 2); if (((HackrfSource) source).getVgaRxGain() != vgaRxGain) ((HackrfSource) source).setVgaRxGain(vgaRxGain); if (((HackrfSource) source).getLnaGain() != lnaGain) ((HackrfSource) source).setLnaGain(lnaGain); } }); hackrfDialog.show(); hackrfDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); break; case RTLSDR_SOURCE: final int[] possibleGainValues = ((RtlsdrSource) source).getPossibleGainValues(); final int[] possibleIFGainValues = ((RtlsdrSource) source).getPossibleIFGainValues(); if (possibleGainValues.length <= 1 && possibleIFGainValues.length <= 1) { Toast.makeText(MainActivity.this, source.getName() + " does not support gain adjustment!", Toast.LENGTH_LONG).show(); } // Prepare layout: final LinearLayout view_rtlsdr = (LinearLayout) this.getLayoutInflater().inflate(R.layout.rtlsdr_gain, null); final LinearLayout ll_rtlsdr_gain = (LinearLayout) view_rtlsdr.findViewById(R.id.ll_rtlsdr_gain); final LinearLayout ll_rtlsdr_ifgain = (LinearLayout) view_rtlsdr.findViewById(R.id.ll_rtlsdr_ifgain); final Switch sw_rtlsdr_manual_gain = (Switch) view_rtlsdr.findViewById(R.id.sw_rtlsdr_manual_gain); final CheckBox cb_rtlsdr_agc = (CheckBox) view_rtlsdr.findViewById(R.id.cb_rtlsdr_agc); final SeekBar sb_rtlsdr_gain = (SeekBar) view_rtlsdr.findViewById(R.id.sb_rtlsdr_gain); final SeekBar sb_rtlsdr_ifGain = (SeekBar) view_rtlsdr.findViewById(R.id.sb_rtlsdr_ifgain); final TextView tv_rtlsdr_gain = (TextView) view_rtlsdr.findViewById(R.id.tv_rtlsdr_gain); final TextView tv_rtlsdr_ifGain = (TextView) view_rtlsdr.findViewById(R.id.tv_rtlsdr_ifgain); // Assign current gain: int gainIndex = 0; int ifGainIndex = 0; for (int i = 0; i < possibleGainValues.length; i++) { if (((RtlsdrSource) source).getGain() == possibleGainValues[i]) { gainIndex = i; break; } } for (int i = 0; i < possibleIFGainValues.length; i++) { if (((RtlsdrSource) source).getIFGain() == possibleIFGainValues[i]) { ifGainIndex = i; break; } } sb_rtlsdr_gain.setMax(possibleGainValues.length - 1); sb_rtlsdr_ifGain.setMax(possibleIFGainValues.length - 1); sb_rtlsdr_gain.setProgress(gainIndex); sb_rtlsdr_ifGain.setProgress(ifGainIndex); tv_rtlsdr_gain.setText("" + possibleGainValues[gainIndex]); tv_rtlsdr_ifGain.setText("" + possibleIFGainValues[ifGainIndex]); // Assign current manual gain and agc setting sw_rtlsdr_manual_gain.setChecked(((RtlsdrSource) source).isManualGain()); cb_rtlsdr_agc.setChecked(((RtlsdrSource) source).isAutomaticGainControl()); // Add listener to gui elements: sw_rtlsdr_manual_gain.setOnCheckedChangeListener(new Switch.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { sb_rtlsdr_gain.setEnabled(isChecked); tv_rtlsdr_gain.setEnabled(isChecked); sb_rtlsdr_ifGain.setEnabled(isChecked); tv_rtlsdr_ifGain.setEnabled(isChecked); ((RtlsdrSource) source).setManualGain(isChecked); if (isChecked) { ((RtlsdrSource) source).setGain(possibleGainValues[sb_rtlsdr_gain.getProgress()]); ((RtlsdrSource) source).setIFGain(possibleIFGainValues[sb_rtlsdr_ifGain.getProgress()]); } } }); cb_rtlsdr_agc.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { ((RtlsdrSource) source).setAutomaticGainControl(isChecked); } }); sb_rtlsdr_gain.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { tv_rtlsdr_gain.setText("" + possibleGainValues[progress]); ((RtlsdrSource) source).setGain(possibleGainValues[progress]); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); sb_rtlsdr_ifGain.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { tv_rtlsdr_ifGain.setText("" + possibleIFGainValues[progress]); ((RtlsdrSource) source).setIFGain(possibleIFGainValues[progress]); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); // Disable gui elements if gain cannot be adjusted: if (possibleGainValues.length <= 1) ll_rtlsdr_gain.setVisibility(View.GONE); if (possibleIFGainValues.length <= 1) ll_rtlsdr_ifgain.setVisibility(View.GONE); if (!sw_rtlsdr_manual_gain.isChecked()) { sb_rtlsdr_gain.setEnabled(false); tv_rtlsdr_gain.setEnabled(false); sb_rtlsdr_ifGain.setEnabled(false); tv_rtlsdr_ifGain.setEnabled(false); } // Show dialog: AlertDialog rtlsdrDialog = new AlertDialog.Builder(this).setTitle("Adjust Gain Settings") .setView(view_rtlsdr).setPositiveButton("Set", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // safe preferences: SharedPreferences.Editor edit = preferences.edit(); edit.putBoolean(getString(R.string.pref_rtlsdr_manual_gain), sw_rtlsdr_manual_gain.isChecked()); edit.putBoolean(getString(R.string.pref_rtlsdr_agc), cb_rtlsdr_agc.isChecked()); edit.putInt(getString(R.string.pref_rtlsdr_gain), possibleGainValues[sb_rtlsdr_gain.getProgress()]); edit.putInt(getString(R.string.pref_rtlsdr_ifGain), possibleIFGainValues[sb_rtlsdr_ifGain.getProgress()]); edit.apply(); } }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // do nothing } }).create(); rtlsdrDialog.setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { boolean manualGain = preferences.getBoolean(getString(R.string.pref_rtlsdr_manual_gain), false); boolean agc = preferences.getBoolean(getString(R.string.pref_rtlsdr_agc), false); int gain = preferences.getInt(getString(R.string.pref_rtlsdr_gain), 0); int ifGain = preferences.getInt(getString(R.string.pref_rtlsdr_ifGain), 0); ((RtlsdrSource) source).setGain(gain); ((RtlsdrSource) source).setIFGain(ifGain); ((RtlsdrSource) source).setManualGain(manualGain); ((RtlsdrSource) source).setAutomaticGainControl(agc); if (manualGain) { // Note: This is a workaround. After setting manual gain to true we must // rewrite the manual gain values: ((RtlsdrSource) source).setGain(gain); ((RtlsdrSource) source).setIFGain(ifGain); } } }); rtlsdrDialog.show(); rtlsdrDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); break; default: Log.e(LOGTAG, "adjustGain: Invalid source type: " + sourceType); break; } }
From source file:fiskinfoo.no.sintef.fiskinfoo.Implementation.UtilityOnClickListeners.java
@Override public OnClickListener getSubscriptionCheckBoxOnClickListener(final PropertyDescription subscription, final Subscription activeSubscription, final User user) { return new OnClickListener() { @Override/*from w w w. j a v a 2 s . co m*/ public void onClick(final View v) { UtilityRowsInterface utilityRowsInterface = new UtilityRows(); final FiskInfoUtility fiskInfoUtility = new FiskInfoUtility(); final Dialog dialog; int iconId = fiskInfoUtility.subscriptionApiNameToIconId(subscription.ApiName); if (iconId != -1) { dialog = new UtilityDialogs().getDialogWithTitleIcon(v.getContext(), R.layout.dialog_manage_subscription, subscription.Name, iconId); } else { dialog = new UtilityDialogs().getDialog(v.getContext(), R.layout.dialog_manage_subscription, subscription.Name); } final Switch subscribedSwitch = (Switch) dialog.findViewById(R.id.manage_subscription_switch); final LinearLayout formatsContainer = (LinearLayout) dialog .findViewById(R.id.manage_subscription_formats_container); final LinearLayout intervalsContainer = (LinearLayout) dialog .findViewById(R.id.manage_subscription_intervals_container); final EditText subscriptionEmailEditText = (EditText) dialog .findViewById(R.id.manage_subscription_email_edit_text); final Button subscribeButton = (Button) dialog.findViewById(R.id.manage_subscription_update_button); Button cancelButton = (Button) dialog.findViewById(R.id.manage_subscription_cancel_button); final boolean isSubscribed = activeSubscription != null; final Map<String, String> subscriptionFrequencies = new HashMap<>(); dialog.setTitle(subscription.Name); if (isSubscribed) { subscriptionEmailEditText.setText(activeSubscription.SubscriptionEmail); subscribedSwitch.setVisibility(View.VISIBLE); subscribedSwitch.setChecked(true); subscribedSwitch .setText(v.getResources().getString(R.string.manage_subscription_subscription_active)); subscribedSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { System.out.println("This is checked:" + isChecked); String switchText = isChecked ? v.getResources().getString(R.string.manage_subscription_subscription_active) : v.getResources() .getString(R.string.manage_subscription_subscription_cancellation); subscribedSwitch.setText(switchText); } }); } else { subscriptionEmailEditText.setText(user.getUsername()); } for (String format : subscription.Formats) { final RadioButtonRow row = utilityRowsInterface.getRadioButtonRow(v.getContext(), format); if (isSubscribed && activeSubscription.FileFormatType.equals(format)) { row.setSelected(true); } formatsContainer.addView(row.getView()); } for (String interval : subscription.SubscriptionInterval) { final RadioButtonRow row = utilityRowsInterface.getRadioButtonRow(v.getContext(), SubscriptionInterval.getType(interval).toString()); if (activeSubscription != null) { row.setSelected(activeSubscription.SubscriptionIntervalName.equals(interval)); } subscriptionFrequencies.put(SubscriptionInterval.getType(interval).toString(), interval); intervalsContainer.addView(row.getView()); } if (intervalsContainer.getChildCount() == 1) { ((RadioButton) intervalsContainer.getChildAt(0) .findViewById(R.id.radio_button_row_radio_button)).setChecked(true); } subscribeButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View subscribeButton) { String subscriptionFormat = null; String subscriptionInterval = null; String subscriptionEmail; BarentswatchApi barentswatchApi = new BarentswatchApi(); barentswatchApi.setAccesToken(user.getToken()); final IBarentswatchApi api = barentswatchApi.getApi(); for (int i = 0; i < formatsContainer.getChildCount(); i++) { if (((RadioButton) formatsContainer.getChildAt(i) .findViewById(R.id.radio_button_row_radio_button)).isChecked()) { subscriptionFormat = ((TextView) formatsContainer.getChildAt(i) .findViewById(R.id.radio_button_row_text_view)).getText().toString(); break; } } if (subscriptionFormat == null) { Toast.makeText(v.getContext(), v.getContext().getString(R.string.choose_subscription_format), Toast.LENGTH_LONG).show(); return; } for (int i = 0; i < intervalsContainer.getChildCount(); i++) { if (((RadioButton) intervalsContainer.getChildAt(i) .findViewById(R.id.radio_button_row_radio_button)).isChecked()) { subscriptionInterval = ((TextView) intervalsContainer.getChildAt(i) .findViewById(R.id.radio_button_row_text_view)).getText().toString(); break; } } if (subscriptionInterval == null) { Toast.makeText(v.getContext(), v.getContext().getString(R.string.choose_subscription_interval), Toast.LENGTH_LONG).show(); return; } subscriptionEmail = subscriptionEmailEditText.getText().toString(); if (!(new FiskInfoUtility().isEmailValid(subscriptionEmail))) { Toast.makeText(v.getContext(), v.getContext().getString(R.string.error_invalid_email), Toast.LENGTH_LONG).show(); return; } if (isSubscribed) { if (subscribedSwitch.isChecked()) { if (!(subscriptionFormat.equals(activeSubscription.FileFormatType) && activeSubscription.SubscriptionIntervalName .equals(subscriptionFrequencies.get(subscriptionInterval)) && user.getUsername().equals(subscriptionEmail))) { SubscriptionSubmitObject updatedSubscription = new SubscriptionSubmitObject( subscription.ApiName, subscriptionFormat, user.getUsername(), user.getUsername(), subscriptionFrequencies.get(subscriptionInterval)); Subscription newSubscriptionObject = api.updateSubscription( String.valueOf(activeSubscription.Id), updatedSubscription); if (newSubscriptionObject != null) { ((CheckBox) v).setChecked(true); } } } else { Response response = api.deleteSubscription(String.valueOf(activeSubscription.Id)); if (response.getStatus() == 204) { ((CheckBox) v).setChecked(false); Toast.makeText(v.getContext(), R.string.subscription_update_successful, Toast.LENGTH_LONG).show(); } else { Toast.makeText(v.getContext(), R.string.subscription_update_failed, Toast.LENGTH_LONG).show(); } } } else { SubscriptionSubmitObject newSubscription = new SubscriptionSubmitObject( subscription.ApiName, subscriptionFormat, user.getUsername(), user.getUsername(), subscriptionFrequencies.get(subscriptionInterval)); Subscription response = api.setSubscription(newSubscription); if (response != null) { ((CheckBox) v).setChecked(true); // TODO: add to "Mine abonnementer" Toast.makeText(v.getContext(), R.string.subscription_update_successful, Toast.LENGTH_LONG).show(); } else { Toast.makeText(v.getContext(), R.string.subscription_update_failed, Toast.LENGTH_LONG).show(); } } dialog.dismiss(); } }); cancelButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View cancelButton) { ((CheckBox) v).setChecked(isSubscribed); dialog.dismiss(); } }); dialog.show(); } }; }