List of usage examples for android.widget ArrayAdapter getPosition
public int getPosition(@Nullable T item)
From source file:joshuatee.wx.ModelInterfaceActivity.java
public void addItemsOnSpinner3HRRR() { spinner_sector = (Spinner) findViewById(R.id.spinner_sector); list_sector = new ArrayList<String>(); list_sector.add("MW"); list_sector.add("CGPsf"); list_sector.add("SGP"); list_sector.add("SL"); list_sector.add("GC"); list_sector.add("CP"); list_sector.add("SE"); list_sector.add("NEsf"); list_sector.add("SW"); list_sector.add("NW"); ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list_sector);//from w w w . java2s. c o m dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner_sector.setAdapter(dataAdapter); sector = preferences3.getString("MODEL_SECTOR_LAST_USED", "SE"); @SuppressWarnings("unchecked") ArrayAdapter<String> myAdap = (ArrayAdapter<String>) spinner_sector.getAdapter(); //cast to an ArrayAdapter spinnerPosition = myAdap.getPosition(sector); spinner_sector.setSelection(spinnerPosition); }
From source file:org.eyeseetea.malariacare.LoginActivity.java
private void initDataDownloadPeriodDropdown() { if (!BuildConfig.loginDataDownloadPeriod) { return;/* www.j ava2 s .co m*/ } ViewGroup loginViewsContainer = (ViewGroup) findViewById(R.id.login_dynamic_views_container); getLayoutInflater().inflate(R.layout.login_spinner, loginViewsContainer, true); //Add left text for the spinner "title" findViewById(R.id.date_spinner_container).setVisibility(View.VISIBLE); TextView textView = (TextView) findViewById(R.id.data_text_view); textView.setText(R.string.download); //add options ArrayList<String> dataLimitOptions = new ArrayList<>(); dataLimitOptions.add(getString(R.string.no_data)); dataLimitOptions.add(getString(R.string.last_6_days)); dataLimitOptions.add(getString(R.string.last_6_weeks)); dataLimitOptions.add(getString(R.string.last_6_months)); final ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, dataLimitOptions); spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); //add spinner Spinner spinner = (Spinner) findViewById(R.id.data_spinner); spinner.setVisibility(View.VISIBLE); spinner.setAdapter(spinnerArrayAdapter); spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { PreferencesState.getInstance().setDataLimitedByDate(spinnerArrayAdapter.getItem(pos).toString()); } public void onNothingSelected(AdapterView<?> parent) { } }); //select the selected option or default no data option String dateLimit = PreferencesState.getInstance().getDataLimitedByDate(); if (dateLimit.equals("")) { spinner.setSelection(spinnerArrayAdapter.getPosition(getString(R.string.no_data))); } else { spinner.setSelection(spinnerArrayAdapter.getPosition(dateLimit)); } }
From source file:fiskinfoo.no.sintef.fiskinfoo.Implementation.UtilityOnClickListeners.java
public OnClickListener getToolEntryEditDialogOnClickListener(final Activity activity, final FragmentManager fragmentManager, final GpsLocationTracker locationTracker, final ToolEntry toolEntry, final User user) { return new OnClickListener() { @Override//from w w w . java 2 s .c om public void onClick(final View editButton) { final DialogInterface dialogInterface = new UtilityDialogs(); final Dialog dialog = dialogInterface.getDialog(editButton.getContext(), R.layout.dialog_register_new_tool, R.string.edit_tool); ((Button) dialog.findViewById(R.id.dialog_register_tool_create_tool_button)) .setText(editButton.getContext().getString(R.string.save)); final Button updateButton = (Button) dialog .findViewById(R.id.dialog_register_tool_create_tool_button); final Button cancelButton = (Button) dialog.findViewById(R.id.dialog_register_tool_cancel_button); final LinearLayout fieldContainer = (LinearLayout) dialog .findViewById(R.id.dialog_register_tool_main_container); final DatePickerRow setupDateRow = new DatePickerRow(editButton.getContext(), editButton.getContext().getString(R.string.tool_set_date_colon), fragmentManager); final TimePickerRow setupTimeRow = new TimePickerRow(editButton.getContext(), editButton.getContext().getString(R.string.tool_set_time_colon), fragmentManager, false); final CoordinatesRow coordinatesRow = new CoordinatesRow(activity, locationTracker); final SpinnerRow toolRow = new SpinnerRow(editButton.getContext(), editButton.getContext().getString(R.string.tool_type), ToolType.getValues()); final CheckBoxRow toolRemovedRow = new CheckBoxRow(editButton.getContext(), editButton.getContext().getString(R.string.tool_removed_row_text), true); final EditTextRow commentRow = new EditTextRow(editButton.getContext(), editButton.getContext().getString(R.string.comment_field_header), editButton.getContext().getString(R.string.comment_field_hint)); final EditTextRow contactPersonNameRow = new EditTextRow(editButton.getContext(), editButton.getContext().getString(R.string.contact_person_name), editButton.getContext().getString(R.string.contact_person_name)); final EditTextRow contactPersonPhoneRow = new EditTextRow(editButton.getContext(), editButton.getContext().getString(R.string.contact_person_phone), editButton.getContext().getString(R.string.contact_person_phone)); final EditTextRow contactPersonEmailRow = new EditTextRow(editButton.getContext(), editButton.getContext().getString(R.string.contact_person_email), editButton.getContext().getString(R.string.contact_person_email)); final EditTextRow vesselNameRow = new EditTextRow(editButton.getContext(), editButton.getContext().getString(R.string.vessel_name), editButton.getContext().getString(R.string.vessel_name)); final EditTextRow vesselPhoneNumberRow = new EditTextRow(editButton.getContext(), editButton.getContext().getString(R.string.vessel_phone_number), editButton.getContext().getString(R.string.vessel_phone_number)); final EditTextRow vesselIrcsNumberRow = new EditTextRow(editButton.getContext(), editButton.getContext().getString(R.string.ircs_number), editButton.getContext().getString(R.string.ircs_number)); final EditTextRow vesselMmsiNumberRow = new EditTextRow(editButton.getContext(), editButton.getContext().getString(R.string.mmsi_number), editButton.getContext().getString(R.string.mmsi_number)); final EditTextRow vesselImoNumberRow = new EditTextRow(editButton.getContext(), editButton.getContext().getString(R.string.imo_number), editButton.getContext().getString(R.string.imo_number)); final EditTextRow vesselRegistrationNumberRow = new EditTextRow(editButton.getContext(), editButton.getContext().getString(R.string.registration_number), editButton.getContext().getString(R.string.registration_number)); final ErrorRow errorRow = new ErrorRow(editButton.getContext(), editButton.getContext().getString(R.string.error_minimum_identification_factors_not_met), false); final SimpleDateFormat sdfMilliSeconds = new SimpleDateFormat( editButton.getContext().getString(R.string.datetime_format_yyyy_mm_dd_t_hh_mm_ss_sss), Locale.getDefault()); final SimpleDateFormat sdf = new SimpleDateFormat( editButton.getContext().getString(R.string.datetime_format_yyyy_mm_dd_t_hh_mm_ss), Locale.getDefault()); View.OnClickListener deleteButtonRowOnClickListener = new OnClickListener() { @Override public void onClick(View v) { String confirmationText; switch (toolEntry.getToolStatus()) { case STATUS_RECEIVED: case STATUS_SENT_UNCONFIRMED: confirmationText = v.getContext() .getString(R.string.confirm_registered_tool_deletion_text); break; case STATUS_UNSENT: case STATUS_UNREPORTED: confirmationText = v.getContext().getString(R.string.confirm_tool_deletion_text); break; case STATUS_REMOVED_UNCONFIRMED: confirmationText = v.getContext() .getString(R.string.confirm_registered_tool_with_local_changes_deletion_text); break; default: confirmationText = v.getContext() .getString(R.string.confirm_tool_deletion_text_general); break; } final Dialog deleteToolDialog = dialogInterface.getConfirmationDialog(v.getContext(), v.getContext().getString(R.string.delete_tool), confirmationText, v.getContext().getString(R.string.delete)); Button confirmToolDeletionButton = (Button) deleteToolDialog .findViewById(R.id.dialog_bottom_confirm_bottom); confirmToolDeletionButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { View parentView = (View) ((editButton.getParent()).getParent()); ((LinearLayout) parentView).removeView(((View) (editButton.getParent()))); Toast.makeText(v.getContext(), v.getContext().getString(R.string.tool_deleted), Toast.LENGTH_LONG).show(); user.getToolLog().removeTool(toolEntry.getSetupDate(), toolEntry.getToolLogId()); user.writeToSharedPref(v.getContext()); deleteToolDialog.dismiss(); dialog.dismiss(); } }); deleteToolDialog.show(); } }; View.OnClickListener archiveToolOnClickListener = new OnClickListener() { @Override public void onClick(View v) { String confirmationText; switch (toolEntry.getToolStatus()) { case STATUS_RECEIVED: confirmationText = v.getContext().getString(R.string.confirm_registered_tool_archiving); break; case STATUS_UNSENT: if (!toolEntry.getId().isEmpty()) { confirmationText = v.getContext().getString(R.string.confirm_tool_archiving_text); } else { confirmationText = v.getContext().getString( R.string.confirm_registered_tool_with_local_changes_archiving_text); } break; default: confirmationText = v.getContext() .getString(R.string.confirm_tool_archiving_text_general); break; } final Dialog archiveDialog = dialogInterface.getConfirmationDialog(v.getContext(), v.getContext().getString(R.string.archive_tool), confirmationText, v.getContext().getString(R.string.archive)); Button confirmToolArchiveButton = (Button) archiveDialog .findViewById(R.id.dialog_bottom_confirm_bottom); confirmToolArchiveButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { View parentView = (View) ((editButton.getParent()).getParent()).getParent(); ((LinearLayout) parentView) .removeView(((View) (editButton.getParent()).getParent())); Toast.makeText(v.getContext(), v.getContext().getString(R.string.tool_archived), Toast.LENGTH_LONG).show(); toolEntry.setToolStatus(ToolEntryStatus.STATUS_REMOVED); user.writeToSharedPref(v.getContext()); archiveDialog.dismiss(); dialog.dismiss(); } }); archiveDialog.show(); } }; ActionRow archiveRow = new ActionRow(editButton.getContext(), editButton.getContext().getString(R.string.archive_tool), R.drawable.ic_archive_black_24dp, archiveToolOnClickListener); ActionRow deleteRow = new ActionRow(editButton.getContext(), editButton.getContext().getString(R.string.delete_tool), R.drawable.ic_delete_black_24dp, deleteButtonRowOnClickListener); commentRow.setInputType(InputType.TYPE_CLASS_TEXT); commentRow.setHelpText(editButton.getContext().getString(R.string.comment_help_description)); vesselNameRow.setInputType(InputType.TYPE_CLASS_TEXT); contactPersonPhoneRow .setHelpText(editButton.getContext().getString(R.string.vessel_name_help_description)); vesselPhoneNumberRow.setInputType(InputType.TYPE_CLASS_PHONE); vesselIrcsNumberRow.setInputType(InputType.TYPE_CLASS_TEXT); vesselIrcsNumberRow.setInputFilters(new InputFilter[] { new InputFilter.LengthFilter( editButton.getContext().getResources().getInteger(R.integer.input_length_ircs)), new InputFilter.AllCaps() }); vesselIrcsNumberRow.setHelpText(editButton.getContext().getString(R.string.ircs_help_description)); vesselMmsiNumberRow.setInputType(InputType.TYPE_CLASS_NUMBER); vesselMmsiNumberRow.setInputFilters(new InputFilter[] { new InputFilter.LengthFilter( editButton.getContext().getResources().getInteger(R.integer.input_length_mmsi)) }); vesselMmsiNumberRow.setHelpText(editButton.getContext().getString(R.string.mmsi_help_description)); vesselImoNumberRow.setInputType(InputType.TYPE_CLASS_NUMBER); vesselImoNumberRow.setInputFilters(new InputFilter[] { new InputFilter.LengthFilter( editButton.getContext().getResources().getInteger(R.integer.input_length_imo)) }); vesselImoNumberRow.setHelpText(editButton.getContext().getString(R.string.imo_help_description)); vesselRegistrationNumberRow.setInputType(InputType.TYPE_CLASS_TEXT); vesselRegistrationNumberRow.setInputFilters(new InputFilter[] { new InputFilter.LengthFilter(editButton.getContext().getResources() .getInteger(R.integer.input_length_registration_number)), new InputFilter.AllCaps() }); vesselRegistrationNumberRow.setHelpText( editButton.getContext().getString(R.string.registration_number_help_description)); contactPersonNameRow.setInputType(InputType.TYPE_TEXT_VARIATION_PERSON_NAME); contactPersonPhoneRow.setInputType(InputType.TYPE_CLASS_PHONE); contactPersonEmailRow.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS); contactPersonNameRow.setHelpText( editButton.getContext().getString(R.string.contact_person_name_help_description)); contactPersonPhoneRow.setHelpText( editButton.getContext().getString(R.string.contact_person_phone_help_description)); contactPersonEmailRow.setHelpText( editButton.getContext().getString(R.string.contact_person_email_help_description)); coordinatesRow.setCoordinates(activity, toolEntry.getCoordinates()); setupDateRow.setEnabled(false); /* Should these fields be editable after tools are reported? */ // vesselRegistrationNumberRow.setEnabled(toolEntry.getToolStatus() == ToolEntryStatus.STATUS_UNREPORTED); // vesselImoNumberRow.setEnabled(toolEntry.getToolStatus() == ToolEntryStatus.STATUS_UNREPORTED); // vesselMmsiNumberRow.setEnabled(toolEntry.getToolStatus() == ToolEntryStatus.STATUS_UNREPORTED); // vesselNameRow.setEnabled(toolEntry.getToolStatus() == ToolEntryStatus.STATUS_UNREPORTED); // vesselIrcsNumberRow.setEnabled(toolEntry.getToolStatus() == ToolEntryStatus.STATUS_UNREPORTED); ArrayAdapter<String> currentAdapter = toolRow.getAdapter(); toolRow.setSelectedSpinnerItem(currentAdapter.getPosition(toolEntry.getToolType().toString())); toolRemovedRow.setChecked(!toolEntry.getRemovedTime().isEmpty()); commentRow.setText(toolEntry.getComment()); contactPersonNameRow.setText(toolEntry.getContactPersonName()); contactPersonPhoneRow .setText(!toolEntry.getContactPersonPhone().equals("") ? toolEntry.getContactPersonPhone() : toolEntry.getVesselPhone()); contactPersonEmailRow .setText(!toolEntry.getContactPersonEmail().equals("") ? toolEntry.getContactPersonEmail() : toolEntry.getVesselEmail()); vesselNameRow.setText(toolEntry.getVesselName()); vesselPhoneNumberRow.setText(toolEntry.getVesselPhone()); vesselIrcsNumberRow.setText(toolEntry.getIRCS()); vesselMmsiNumberRow.setText(toolEntry.getMMSI()); vesselImoNumberRow.setText(toolEntry.getIMO()); vesselRegistrationNumberRow.setText(toolEntry.getRegNum()); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); Date setupDate = null; String toolSetupDateTime; try { setupDate = sdf.parse(toolEntry.getSetupDateTime()); } catch (ParseException e) { e.printStackTrace(); } sdfMilliSeconds.setTimeZone(TimeZone.getDefault()); toolSetupDateTime = sdfMilliSeconds.format(setupDate); setupDateRow.setDate(toolSetupDateTime.substring(0, 10)); setupTimeRow.setTime(toolSetupDateTime.substring(toolEntry.getSetupDateTime().indexOf('T') + 1, toolEntry.getSetupDateTime().indexOf('T') + 6)); fieldContainer.addView(coordinatesRow.getView()); fieldContainer.addView(setupDateRow.getView()); fieldContainer.addView(setupTimeRow.getView()); fieldContainer.addView(toolRow.getView()); fieldContainer.addView(toolRemovedRow.getView()); fieldContainer.addView(commentRow.getView()); fieldContainer.addView(contactPersonNameRow.getView()); fieldContainer.addView(contactPersonPhoneRow.getView()); fieldContainer.addView(contactPersonEmailRow.getView()); fieldContainer.addView(vesselNameRow.getView()); fieldContainer.addView(vesselPhoneNumberRow.getView()); fieldContainer.addView(vesselIrcsNumberRow.getView()); fieldContainer.addView(vesselMmsiNumberRow.getView()); fieldContainer.addView(vesselImoNumberRow.getView()); fieldContainer.addView(vesselRegistrationNumberRow.getView()); fieldContainer.addView(errorRow.getView()); if (toolEntry.getToolStatus() != ToolEntryStatus.STATUS_UNREPORTED) { fieldContainer.addView(archiveRow.getView()); } fieldContainer.addView(deleteRow.getView()); updateButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View updateButton) { List<Point> coordinates = coordinatesRow.getCoordinates(); ToolType toolType = ToolType.createFromValue(toolRow.getCurrentSpinnerItem()); boolean toolRemoved = toolRemovedRow.isChecked(); String vesselName = vesselNameRow.getFieldText(); String vesselPhoneNumber = vesselPhoneNumberRow.getFieldText(); String toolSetupDate = setupDateRow.getDate(); String toolSetupTime = setupTimeRow.getTime(); String toolSetupDateTime; String commentString = commentRow.getFieldText(); String vesselIrcsNumber = vesselIrcsNumberRow.getFieldText(); String vesselMmsiNumber = vesselMmsiNumberRow.getFieldText(); String vesselImoNumber = vesselImoNumberRow.getFieldText(); String registrationNumber = vesselRegistrationNumberRow.getFieldText(); String contactPersonName = contactPersonNameRow.getFieldText(); String contactPersonPhone = contactPersonPhoneRow.getFieldText(); String contactPersonEmail = contactPersonEmailRow.getFieldText(); FiskInfoUtility utility = new FiskInfoUtility(); boolean validated; boolean edited = false; boolean ircsValidated; boolean mmsiValidated; boolean imoValidated; boolean regNumValidated; boolean minimumIdentificationFactorsMet; validated = coordinates != null; if (!validated) { return; } validated = utility.validateName(contactPersonNameRow.getFieldText().trim()); contactPersonNameRow.setError(validated ? null : updateButton.getContext().getString(R.string.error_invalid_name)); if (!validated) { ((ScrollView) fieldContainer.getParent()).post(new Runnable() { @Override public void run() { ((ScrollView) fieldContainer.getParent()).scrollTo(0, contactPersonNameRow.getView().getBottom()); contactPersonNameRow.requestFocus(); } }); return; } validated = utility.validatePhoneNumber(contactPersonPhoneRow.getFieldText().trim()); contactPersonPhoneRow.setError(validated ? null : updateButton.getContext().getString(R.string.error_invalid_phone_number)); if (!validated) { ((ScrollView) fieldContainer.getParent()).post(new Runnable() { @Override public void run() { ((ScrollView) fieldContainer.getParent()).scrollTo(0, contactPersonPhoneRow.getView().getBottom()); contactPersonPhoneRow.requestFocus(); } }); return; } validated = utility.isEmailValid(contactPersonEmailRow.getFieldText().trim()); contactPersonEmailRow.setError(validated ? null : updateButton.getContext().getString(R.string.error_invalid_email)); if (!validated) { ((ScrollView) fieldContainer.getParent()).post(new Runnable() { @Override public void run() { ((ScrollView) fieldContainer.getParent()).scrollTo(0, contactPersonEmailRow.getView().getBottom()); contactPersonEmailRow.requestFocus(); } }); return; } validated = vesselNameRow.getFieldText().trim() != null && !vesselNameRow.getFieldText().isEmpty(); vesselNameRow.setError(validated ? null : updateButton.getContext().getString(R.string.error_invalid_vessel_name)); if (!validated) { ((ScrollView) fieldContainer.getParent()).post(new Runnable() { @Override public void run() { ((ScrollView) fieldContainer.getParent()).scrollTo(0, vesselNameRow.getView().getBottom()); vesselNameRow.requestFocus(); } }); return; } validated = vesselPhoneNumberRow.getFieldText().trim() != null && !vesselPhoneNumberRow.getFieldText().isEmpty(); vesselPhoneNumberRow.setError(validated ? null : updateButton.getContext().getString(R.string.error_invalid_phone_number)); if (!validated) { ((ScrollView) fieldContainer.getParent()).post(new Runnable() { @Override public void run() { ((ScrollView) fieldContainer.getParent()).scrollTo(0, vesselPhoneNumberRow.getView().getBottom()); vesselPhoneNumberRow.requestFocus(); } }); return; } validated = (ircsValidated = utility.validateIRCS(vesselIrcsNumber)) || vesselIrcsNumber.isEmpty(); vesselIrcsNumberRow.setError(validated ? null : updateButton.getContext().getString(R.string.error_invalid_ircs)); if (!validated) { ((ScrollView) fieldContainer.getParent()).post(new Runnable() { @Override public void run() { ((ScrollView) fieldContainer.getParent()).scrollTo(0, vesselIrcsNumberRow.getView().getBottom()); vesselIrcsNumberRow.requestFocus(); } }); return; } validated = (mmsiValidated = utility.validateMMSI(vesselMmsiNumber)) || vesselMmsiNumber.isEmpty(); vesselMmsiNumberRow.setError(validated ? null : updateButton.getContext().getString(R.string.error_invalid_mmsi)); if (!validated) { ((ScrollView) fieldContainer.getParent()).post(new Runnable() { @Override public void run() { ((ScrollView) fieldContainer.getParent()).scrollTo(0, vesselMmsiNumberRow.getView().getBottom()); vesselMmsiNumberRow.requestFocus(); } }); return; } validated = (imoValidated = utility.validateIMO(vesselImoNumber)) || vesselImoNumber.isEmpty(); vesselImoNumberRow.setError( validated ? null : updateButton.getContext().getString(R.string.error_invalid_imo)); if (!validated) { ((ScrollView) fieldContainer.getParent()).post(new Runnable() { @Override public void run() { ((ScrollView) fieldContainer.getParent()).scrollTo(0, vesselImoNumberRow.getView().getBottom()); vesselImoNumberRow.requestFocus(); } }); return; } validated = (regNumValidated = utility.validateRegistrationNumber(registrationNumber)) || registrationNumber.isEmpty(); vesselRegistrationNumberRow.setError(validated ? null : editButton.getContext().getString(R.string.error_invalid_registration_number)); if (!validated) { ((ScrollView) fieldContainer.getParent().getParent()).post(new Runnable() { @Override public void run() { ((ScrollView) fieldContainer.getParent().getParent()).scrollTo(0, vesselRegistrationNumberRow.getView().getBottom()); vesselRegistrationNumberRow.requestFocus(); } }); return; } sdf.setTimeZone(TimeZone.getDefault()); Date setupDate = null; String setupDateString = toolSetupDate + "T" + toolSetupTime + ":00Z"; try { setupDate = sdf.parse(setupDateString); } catch (ParseException e) { e.printStackTrace(); } sdfMilliSeconds.setTimeZone(TimeZone.getTimeZone("UTC")); setupDateString = sdfMilliSeconds.format(setupDate); toolSetupDateTime = setupDateString.substring(0, setupDateString.indexOf('.')).concat("Z"); minimumIdentificationFactorsMet = !vesselName.isEmpty() && (ircsValidated || mmsiValidated || imoValidated || regNumValidated); if ((coordinates != null && coordinates.size() != toolEntry.getCoordinates().size()) || toolType != toolEntry.getToolType() || (toolRemoved) == (toolEntry.getRemovedTime().isEmpty()) || (vesselName != null && !vesselName.equals(toolEntry.getVesselName())) || (vesselPhoneNumber != null && !vesselPhoneNumber.equals(toolEntry.getVesselPhone())) || (toolSetupDateTime != null && !toolSetupDateTime.equals(toolEntry.getSetupDateTime())) || (vesselIrcsNumber != null && !vesselIrcsNumber.equals(toolEntry.getIRCS())) || (vesselMmsiNumber != null && !vesselMmsiNumber.equals(toolEntry.getMMSI())) || (vesselImoNumber != null && !vesselImoNumber.equals(toolEntry.getIMO())) || (registrationNumber != null && !registrationNumber.equals(toolEntry.getRegNum())) || (contactPersonName != null && !contactPersonName.equals(toolEntry.getContactPersonName())) || (contactPersonPhone != null && !contactPersonPhone.equals(toolEntry.getContactPersonPhone())) || (contactPersonEmail != null && !contactPersonEmail.equals(toolEntry.getContactPersonEmail())) || (commentString != null && !commentString.equals(toolEntry.getComment()))) { edited = true; } else { List<Point> points = toolEntry.getCoordinates(); for (int i = 0; i < coordinates.size(); i++) { if (coordinates.get(i).getLatitude() != points.get(i).getLatitude() || coordinates.get(i).getLongitude() != points.get(i).getLongitude()) { edited = true; break; } } } if (edited) { if (!minimumIdentificationFactorsMet) { errorRow.setVisibility(!minimumIdentificationFactorsMet); return; } Date lastChangedDate = new Date(); Date previousSetupDate = null; SimpleDateFormat sdfSetupCompare = new SimpleDateFormat("yyyyMMdd", Locale.getDefault()); String lastChangedDateString = sdfMilliSeconds.format(lastChangedDate).concat("Z"); sdfSetupCompare.setTimeZone(TimeZone.getTimeZone("UTC")); try { previousSetupDate = sdf.parse(toolEntry.getSetupDateTime() .substring(0, toolEntry.getSetupDateTime().length() - 1).concat(".000")); } catch (ParseException e) { e.printStackTrace(); } if (!sdfSetupCompare.format(previousSetupDate) .equals(sdfSetupCompare.format(setupDate))) { // TODO: setup date is changed, tool needs to be moved in log so the app does not crash when trying to delete tool. // user.getToolLog().removeTool(toolEntry.getSetupDate(), toolEntry.getToolLogId()); // user.getToolLog().addTool(toolEntry, toolEntry.getSetupDateTime().substring(0, 10)); // user.writeToSharedPref(editButton.getContext()); } ToolEntryStatus toolStatus = (toolRemoved ? ToolEntryStatus.STATUS_REMOVED_UNCONFIRMED : (toolEntry.getToolStatus() == ToolEntryStatus.STATUS_UNREPORTED ? ToolEntryStatus.STATUS_UNREPORTED : ToolEntryStatus.STATUS_UNSENT)); toolEntry.setToolStatus(toolStatus); toolEntry.setCoordinates(coordinates); toolEntry.setToolType(toolType); toolEntry.setVesselName(vesselName); toolEntry.setVesselPhone(vesselPhoneNumber); toolEntry.setSetupDateTime(toolSetupDateTime); toolEntry.setRemovedTime(toolRemoved ? lastChangedDateString : null); toolEntry.setComment(commentString); toolEntry.setIRCS(vesselIrcsNumber); toolEntry.setMMSI(vesselMmsiNumber); toolEntry.setIMO(vesselImoNumber); toolEntry.setRegNum(registrationNumber); toolEntry.setLastChangedDateTime(lastChangedDateString); toolEntry.setLastChangedBySource(lastChangedDateString); toolEntry.setContactPersonName(contactPersonName); toolEntry.setContactPersonPhone(contactPersonPhone); toolEntry.setContactPersonEmail(contactPersonEmail); try { ImageView notificationView = (ImageView) ((View) editButton.getParent()) .findViewById(R.id.tool_log_row_reported_image_view); if (notificationView != null) { notificationView.setVisibility(View.VISIBLE); notificationView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Toast.makeText(v.getContext(), R.string.notification_tool_unreported_changes, Toast.LENGTH_LONG).show(); } }); } TextView dateTimeTextView = (TextView) ((View) editButton.getParent()) .findViewById(R.id.tool_log_row_latest_date_text_view); TextView toolTypeTextView = (TextView) ((View) editButton.getParent()) .findViewById(R.id.tool_log_row_tool_type_text_view); TextView positionTextView = (TextView) ((View) editButton.getParent()) .findViewById(R.id.tool_log_row_tool_position_text_view); StringBuilder sb = new StringBuilder(); sb.append(FiskInfoUtility .decimalToDMS((toolEntry.getCoordinates().get(0).getLatitude()))); sb.append(", "); sb.append(FiskInfoUtility .decimalToDMS((toolEntry.getCoordinates().get(0).getLongitude()))); String coordinateString = sb.toString(); coordinateString = toolEntry.getCoordinates().size() < 2 ? coordinateString : coordinateString + "\n.."; sdfMilliSeconds.setTimeZone(TimeZone.getTimeZone("GMT+1")); setupDateString = sdfMilliSeconds.format(setupDate); dateTimeTextView.setText(setupDateString.substring(0, 16).replace("T", " ")); toolTypeTextView.setText(toolEntry.getToolType().toString()); positionTextView.setText(coordinateString); Date toolDate; Date currentDate = new Date(); try { toolDate = sdf.parse(toolEntry.getSetupDateTime() .substring(0, toolEntry.getSetupDateTime().length() - 1) .concat(".000")); long diff = currentDate.getTime() - toolDate.getTime(); double days = diff / updateButton.getContext().getResources() .getInteger(R.integer.milliseconds_in_a_day); if (days > 14) { dateTimeTextView.setTextColor(ContextCompat .getColor(updateButton.getContext(), (R.color.error_red))); } else { dateTimeTextView.setTextColor(toolTypeTextView.getCurrentTextColor()); } } catch (ParseException e) { e.printStackTrace(); return; } } catch (ClassCastException e) { e.printStackTrace(); } user.writeToSharedPref(updateButton.getContext()); } else { Toast.makeText(editButton.getContext(), R.string.no_changes_made, Toast.LENGTH_LONG) .show(); } dialog.dismiss(); } }); cancelButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); dialog.show(); } }; }
From source file:org.de.jmg.learn.SettingsActivity.java
private void initSpinners(boolean blnRestart) { libLearn.gStatus = "initSpinners"; try {//www . j a v a 2 s .co m spnAbfragebereich = (Spinner) findViewById(R.id.spnAbfragebereich); spnASCII = (Spinner) findViewById(R.id.spnASCII); spnStep = (Spinner) findViewById(R.id.spnStep); spnDisplayDurationWord = (Spinner) findViewById(R.id.spnAnzeigedauerWord); spnDisplayDurationBed = (Spinner) findViewById(R.id.spnAnzeigedauerBed); spnPaukRepetitions = (Spinner) findViewById(R.id.spnRepetitions); spnProbabilityFactor = (Spinner) findViewById(R.id.spnProbabilityFactor); spnRestartInterval = (Spinner) findViewById(R.id.spnRestartInterval); spnLanguages = (Spinner) findViewById(R.id.spnLanguages); spnColors = (org.de.jmg.lib.NoClickSpinner) findViewById(R.id.spnColors); spnSounds = (org.de.jmg.lib.NoClickSpinner) findViewById(R.id.spnSounds); spnLangWord = (Spinner) findViewById(R.id.spnLangWord); spnLangMeaning = (Spinner) findViewById(R.id.spnLangMeaning); if (!blnRestart) langinitialized = 0; else langinitialized = 0; if (spnAbfragebereich.getAdapter() != null && spnAbfragebereich.getAdapter().getCount() > 0) return; if (Colors == null || Colors != null) { Colors = new ColorsArrayAdapter(_main, R.layout.spinnerrow); Colors.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); Sounds = new SoundsArrayAdapter(_main, R.layout.soundsspinnerrow); Sounds.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); } spnASCII.getBackground().setColorFilter(Color.BLACK, PorterDuff.Mode.SRC_ATOP); spnStep.getBackground().setColorFilter(Color.BLACK, PorterDuff.Mode.SRC_ATOP); spnDisplayDurationBed.getBackground().setColorFilter(Color.BLACK, PorterDuff.Mode.SRC_ATOP); spnDisplayDurationWord.getBackground().setColorFilter(Color.BLACK, PorterDuff.Mode.SRC_ATOP); spnAbfragebereich.getBackground().setColorFilter(Color.BLACK, PorterDuff.Mode.SRC_ATOP); spnPaukRepetitions.getBackground().setColorFilter(Color.BLACK, PorterDuff.Mode.SRC_ATOP); spnProbabilityFactor.getBackground().setColorFilter(Color.BLACK, PorterDuff.Mode.SRC_ATOP); spnRestartInterval.getBackground().setColorFilter(Color.BLACK, PorterDuff.Mode.SRC_ATOP); spnLanguages.getBackground().setColorFilter(Color.BLACK, PorterDuff.Mode.SRC_ATOP); //spnColors.getBackground().setColorFilter(Color.BLACK, PorterDuff.Mode.SRC_ATOP); //spnSounds.getBackground().setColorFilter(Color.BLACK, PorterDuff.Mode.SRC_ATOP); // Create an ArrayAdapter using the string array and a default // spinner layout ScaledArrayAdapter<CharSequence> adapter = ScaledArrayAdapter.createFromResource(_main, R.array.spnAbfragebereichEntries, 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); if (lib.NookSimpleTouch() && mScale == 1) adapter.Scale = 1.8f; // Apply the adapter to the spinner spnAbfragebereich.setAdapter(adapter); spnAbfragebereich.setSelection(getIntent().getShortExtra("Abfragebereich", (short) -1) + 1); spnAbfragebereich.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { intent.putExtra("Abfragebereich", (short) (position - 1)); intent.putExtra("OK", "OK"); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); ScaledArrayAdapter<CharSequence> adapterStep = ScaledArrayAdapter.createFromResource(_main, R.array.spnStepEntries, android.R.layout.simple_spinner_item); // Specify the layout to use when the list of choices appears adapterStep.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // Apply the adapter to the spinner if (lib.NookSimpleTouch() && mScale == 1) adapterStep.Scale = 1.8f; spnStep.setAdapter(adapterStep); spnStep.setSelection(adapterStep.getPosition("" + getIntent().getShortExtra("Step", (short) 5))); spnStep.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { intent.putExtra("Step", (short) (Integer.parseInt((String) parent.getItemAtPosition(position)))); intent.putExtra("OK", "OK"); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); ScaledArrayAdapter<String> adapterASCII = new ScaledArrayAdapter<String>(_main, android.R.layout.simple_spinner_item); // adapterASCII.addAll(Charset.availableCharsets().values()); ArrayList<String> charsets = new ArrayList<String>(); for (Charset c : Charset.availableCharsets().values()) { charsets.add(c.name()); } adapterASCII.addAll(charsets); // Specify the layout to use when the list of choices appears adapterASCII.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // Apply the adapter to the spinner if (lib.NookSimpleTouch() && mScale == 1) adapterASCII.Scale = 1.8f; spnASCII.setAdapter(adapterASCII); String CharsetASCII = getIntent().getStringExtra("CharsetASCII"); if (!libString.IsNullOrEmpty(CharsetASCII)) { int i = 0; for (Charset c : Charset.availableCharsets().values()) { if (c.name().equalsIgnoreCase(CharsetASCII)) { break; } i++; } if (i < adapterASCII.getCount()) { spnASCII.setSelection(i); } } spnASCII.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { intent.putExtra("CharsetASCII", ((String) (parent.getSelectedItem()))); intent.putExtra("OK", "OK"); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); final ScaledArrayAdapter<CharSequence> adapterDDWord = ScaledArrayAdapter.createFromResource(_main, R.array.spnDurations, android.R.layout.simple_spinner_item); // Specify the layout to use when the list of choices appears adapterDDWord.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); if (lib.NookSimpleTouch() && mScale == 1) adapterDDWord.Scale = 1.8f; // Apply the adapter to the spinner spnDisplayDurationWord.setAdapter(adapterDDWord); String strDD = "" + getIntent().getFloatExtra("DisplayDurationWord", 1.5f); strDD = strDD.replace(".0", ""); int Pos = adapterDDWord.getPosition(strDD); spnDisplayDurationWord.setSelection(Pos); spnDisplayDurationWord.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { intent.putExtra("DisplayDurationWord", (Float.parseFloat((String) parent.getItemAtPosition(position)))); intent.putExtra("OK", "OK"); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); ScaledArrayAdapter<CharSequence> adapterDDBed = ScaledArrayAdapter.createFromResource(_main, R.array.spnDurations, android.R.layout.simple_spinner_item); // Specify the layout to use when the list of choices appears adapterDDBed.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); if (lib.NookSimpleTouch() && mScale == 1) adapterDDBed.Scale = 1.8f; // Apply the adapter to the spinner spnDisplayDurationBed.setAdapter(adapterDDBed); strDD = "" + getIntent().getFloatExtra("DisplayDurationBed", 2.5f); strDD = strDD.replace(".0", ""); Pos = adapterDDBed.getPosition(strDD); spnDisplayDurationBed.setSelection(Pos); spnDisplayDurationBed.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { intent.putExtra("DisplayDurationBed", (Float.parseFloat((String) parent.getItemAtPosition(position)))); intent.putExtra("OK", "OK"); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); ScaledArrayAdapter<CharSequence> adapterPaukRepetitions = ScaledArrayAdapter.createFromResource(_main, R.array.spnRepetitions, android.R.layout.simple_spinner_item); // Specify the layout to use when the list of choices appears adapterPaukRepetitions.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); if (lib.NookSimpleTouch() && mScale == 1) adapterPaukRepetitions.Scale = 1.8f; spnPaukRepetitions.setAdapter(adapterPaukRepetitions); Pos = getIntent().getIntExtra("PaukRepetitions", 3) - 1; spnPaukRepetitions.setSelection(Pos); spnPaukRepetitions.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { intent.putExtra("PaukRepetitions", (Integer.parseInt((String) parent.getItemAtPosition(position)))); intent.putExtra("OK", "OK"); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); ScaledArrayAdapter<CharSequence> adapterProbabilityFactor = ScaledArrayAdapter.createFromResource(_main, R.array.spnProbabilityFactors, android.R.layout.simple_spinner_item); // Specify the layout to use when the list of choices appears adapterProbabilityFactor.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); if (lib.NookSimpleTouch() && mScale == 1) adapterProbabilityFactor.Scale = 1.8f; spnProbabilityFactor.setAdapter(adapterProbabilityFactor); float ProbabilityFactor = getIntent().getFloatExtra("ProbabilityFactor", -1f); if (ProbabilityFactor == -1) { strDD = _main.getString((R.string.auto)); } else { strDD = "" + ProbabilityFactor; strDD = strDD.replace(".0", ""); } ArrayAdapter<CharSequence> a1 = adapterProbabilityFactor; if (a1 != null) { try { libLearn.gStatus = "get Spinneradapter ProbabilityFactor"; Pos = (a1.getPosition(strDD)); spnProbabilityFactor.setSelection(Pos); } catch (Exception ex) { lib.ShowException(_main, ex); } } spnProbabilityFactor.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { String strDD = (String) parent.getItemAtPosition(position); if (strDD.equalsIgnoreCase(_main.getString(R.string.auto))) strDD = "-1"; intent.putExtra("ProbabilityFactor", (Float.parseFloat(strDD))); intent.putExtra("OK", "OK"); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); ScaledArrayAdapter<CharSequence> adapterRestartInterval = ScaledArrayAdapter.createFromResource(_main, R.array.spnRestartInterval, android.R.layout.simple_spinner_item); // Specify the layout to use when the list of choices appears adapterRestartInterval.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); if (lib.NookSimpleTouch() && mScale == 1) adapterRestartInterval.Scale = 1.8f; spnRestartInterval.setAdapter(adapterRestartInterval); int RestartInterval = getIntent().getIntExtra("RestartInterval", -1); if (RestartInterval == -1) { strDD = _main.getString(R.string.off); } else { strDD = "" + RestartInterval; } a1 = adapterRestartInterval; if (a1 != null) { try { libLearn.gStatus = "get Spinneradapter ProbabilityFactor"; Pos = (a1.getPosition(strDD)); spnRestartInterval.setSelection(Pos); } catch (Exception ex) { lib.ShowException(_main, ex); } } spnRestartInterval.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { String strDD = (String) parent.getItemAtPosition(position); if (strDD.equalsIgnoreCase(_main.getString(R.string.off))) strDD = "-1"; intent.putExtra("RestartInterval", (Integer.parseInt(strDD))); intent.putExtra("OK", "OK"); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); ScaledArrayAdapter<CharSequence> adapterLanguages = ScaledArrayAdapter.createFromResource(_main, R.array.spnLanguages, android.R.layout.simple_spinner_item); // Specify the layout to use when the list of choices appears adapterLanguages.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); if (lib.NookSimpleTouch() && mScale == 1) adapterLanguages.Scale = 1.8f; spnLanguages.setAdapter(adapterLanguages); int Language = getIntent().getIntExtra("Language", org.de.jmg.learn.vok.Vokabel.EnumSprachen.undefiniert.ordinal()); spnLanguages.setSelection(Language); spnLanguages.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { intent.putExtra("Language", position); intent.putExtra("OK", "OK"); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); adapterLangWord = new ScaledArrayAdapter<>(_main, android.R.layout.simple_spinner_item); // Specify the layout to use when the list of choices appears adapterLangWord.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); if (lib.NookSimpleTouch() && mScale == 1) adapterLangWord.Scale = 1.8f; adapterLangWord.add(new DisplayLocale(new Locale("", ""))); adapterLangWord.add(new DisplayLocale(new Locale("_off"))); for (Locale l : Locale.getAvailableLocales()) { DisplayLocale dl = new DisplayLocale(l); adapterLangWord.add(dl); } sortLangWord(); spnLangWord.setAdapter(adapterLangWord); /* if (selectedLocale != null) { int pos = adapterLangWord.getPosition(selectedLocale); spnLangWord.setSelection (-1); spnLangWord.setSelection(pos); }*/ spnLangWord.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if (position <= 0 || langinitialized == 0) { langinitialized += 1; return; } Locale l = adapterLangWord.getItem(position).locale; int res = 0; if (_main.tts.isLanguageAvailable(Locale.US) >= 0) { res = _main.tts.setLanguage(l); } if (!chkTextToSpeech.isChecked() || res >= 0 || l.toString().equalsIgnoreCase("_off") || !_main.blnTextToSpeech || lib.ShowMessageYesNo(_main, String.format(_main.getString(R.string.msgLanguageNotavailable), l.getDisplayLanguage() + " " + l.getDisplayCountry()), "") == yesnoundefined.yes) { intent.putExtra("langword", lib.toLanguageTag(l)); intent.putExtra("OK", "OK"); } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); adapterLangMeaning = new ScaledArrayAdapter<>(_main, android.R.layout.simple_spinner_item); // Specify the layout to use when the list of choices appears adapterLangMeaning.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); if (lib.NookSimpleTouch() && mScale == 1) adapterLangMeaning.Scale = 1.8f; adapterLangMeaning.add(new DisplayLocale(new Locale("", ""))); adapterLangMeaning.add(new DisplayLocale(new Locale("_off"))); for (Locale l : Locale.getAvailableLocales()) { DisplayLocale dl = new DisplayLocale((l)); adapterLangMeaning.add(dl); } sortLangMeaning(); spnLangMeaning.setAdapter(adapterLangMeaning); /* if (selectedLocale != null) { int pos = adapterLangMeaning.getPosition(selectedLocale); spnLangMeaning.setSelection(-1); spnLangMeaning.setSelection(pos); } */ spnLangMeaning.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if (position <= 0 || langinitialized < 2) { langinitialized += 1; return; } Locale l = adapterLangMeaning.getItem(position).locale; int res = 0; if (_main.tts.isLanguageAvailable(Locale.US) >= 0) { res = _main.tts.setLanguage(l); } if (!chkTextToSpeech.isChecked() || res >= 0 || l.toString().equalsIgnoreCase("_off") || !_main.blnTextToSpeech || lib.ShowMessageYesNo(_main, String.format(_main.getString(R.string.msgLanguageNotavailable), l.getDisplayLanguage() + " " + l.getDisplayCountry()), "") == yesnoundefined.yes) { intent.putExtra("langmeaning", lib.toLanguageTag(l)); intent.putExtra("OK", "OK"); } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); if (lib.NookSimpleTouch() && mScale == 1) Colors.Scale = 1.8f; spnColors.setAdapter(Colors); spnColors.setOnLongClickListener(new android.widget.AdapterView.OnLongClickListener() { @Override public boolean onLongClick(View v) { spnColors.blnDontCallOnClick = true; ShowColorDialog(); return false; } }); spnColors.setOnItemLongClickListener(new android.widget.AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { spnColors.blnDontCallOnClick = true; ShowColorDialog(); return false; } }); if (lib.NookSimpleTouch() && mScale == 1) Sounds.Scale = 1.8f; spnSounds.setAdapter(Sounds); spnSounds.setOnLongClickListener(new android.widget.AdapterView.OnLongClickListener() { @Override public boolean onLongClick(View v) { spnSounds.blnDontCallOnClick = true; ShowSoundsDialog(); return false; } }); spnSounds.setOnItemLongClickListener(new android.widget.AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { spnSounds.blnDontCallOnClick = true; ShowSoundsDialog(); return false; } }); spnSounds.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { SoundSetting item = (SoundSetting) parent.getItemAtPosition(position); File F = new File(item.SoundPath); try { if (F.exists()) lib.playSound(F); else lib.playSound(_main.getAssets(), item.SoundPath); } catch (Exception e) { e.printStackTrace(); } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } catch (Exception ex) { lib.ShowException(_main, ex); } }
From source file:com.ze.client.projecto.dialog.ProjectorDialog.java
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_dialog_projector, container); mSchemes.add("http"); mSchemes.add("https"); mProjectorHost = ((TextInputLayout) view.findViewById(R.id.edit_host)).getEditText(); mPort = ((TextInputLayout) view.findViewById(R.id.edit_port)).getEditText(); mName = ((TextInputLayout) view.findViewById(R.id.edit_name)).getEditText(); mTypeSpinner = (Spinner) view.findViewById(R.id.type_spinner); mSchemeSpinner = (Spinner) view.findViewById(R.id.scheme_spinner); TextView dialogTitle = (TextView) view.findViewById(R.id.dialog_title); mProjectorTypes = ProjectorDbHelper.getProjectorTypeList(getContext()); ArrayAdapter<ProjectorType> adapter = new ArrayAdapter<>(this.getContext(), R.layout.dropdown_type, mProjectorTypes);//from www . j a va 2 s. com adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mTypeSpinner.setAdapter(adapter); ArrayAdapter<String> schemeAdapter = new ArrayAdapter<>(this.getContext(), R.layout.dropdown_type, mSchemes); schemeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mSchemeSpinner.setAdapter(schemeAdapter); if (savedInstanceState != null) { mProjectorHost.setText(savedInstanceState.getCharSequence(TEXT_HOST)); mPort.setText(savedInstanceState.getCharSequence(TEXT_PORT)); mName.setText(savedInstanceState.getCharSequence(TEXT_NAME)); mTypeSpinner.setSelection(savedInstanceState.getInt(ITEM_TYPE)); mSchemeSpinner.setSelection(savedInstanceState.getInt(ITEM_SCHEME)); } mTypeSpinner.setOnItemSelectedListener(this); view.findViewById(R.id.button_ok).setOnClickListener(v -> { URI projectorUri = null; try { projectorUri = new URI(mSchemeSpinner.getSelectedItem().toString() + "://" + mProjectorHost.getText().toString() + ":" + mPort.getText().toString()); } catch (URISyntaxException e) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setMessage(R.string.dialog_uri_not_well_formed).setTitle(R.string.dialog_title_error) .create().show(); return; } Projector projector = new Projector(mProjectorId, mName.getText().toString(), projectorUri, ProjectorDbHelper.getProjectorType(getContext(), mTypeId)); if (projector.getId() == Projector.NO_ID) ProjectorDbHelper.insertProjector(getContext(), projector); else ProjectorDbHelper.updateProjector(getContext(), projector); dismiss(); }); view.findViewById(R.id.button_cancel).setOnClickListener(v -> dismiss()); if (mProjector != null) { mProjectorHost.setText(mProjector.getUri().getHost()); mPort.setText(String.valueOf(mProjector.getUri().getPort())); mName.setText(mProjector.getName()); mTypeSpinner.setSelection(getProjectorTypePosition(mProjector.getProjectorType().getId())); mSchemeSpinner.setSelection(schemeAdapter.getPosition(mProjector.getUri().getScheme())); } else { mTypeSpinner.setSelection(0); } if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.LOLLIPOP) { dialogTitle.setVisibility(View.GONE); } getDialog().setTitle(R.string.mode_projector); return view; }
From source file:com.google.android.apps.flexbox.FlexItemEditFragment.java
@Nullable @Override//from w w w. j a v a 2s . c o m public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { final View view = inflater.inflate(R.layout.fragment_flex_item_edit, container, false); getDialog().setTitle(String.valueOf(mFlexItem.index + 1)); final TextInputLayout orderTextInput = (TextInputLayout) view.findViewById(R.id.input_layout_order); EditText orderEdit = (EditText) view.findViewById(R.id.edit_text_order); orderEdit.setText(String.valueOf(mFlexItem.order)); orderEdit.addTextChangedListener( new FlexEditTextWatcher(orderTextInput, new IntegerInputValidator(), R.string.must_be_integer)); final TextInputLayout flexGrowInput = (TextInputLayout) view.findViewById(R.id.input_layout_flex_grow); final EditText flexGrowEdit = (EditText) view.findViewById(R.id.edit_text_flex_grow); flexGrowEdit.setText(String.valueOf(mFlexItem.flexGrow)); flexGrowEdit.addTextChangedListener(new FlexEditTextWatcher(flexGrowInput, new NonNegativeDecimalInputValidator(), R.string.must_be_non_negative_float)); final TextInputLayout flexShrinkInput = (TextInputLayout) view.findViewById(R.id.input_layout_flex_shrink); EditText flexShrinkEdit = (EditText) view.findViewById(R.id.edit_text_flex_shrink); flexShrinkEdit.setText(String.valueOf(mFlexItem.flexShrink)); flexShrinkEdit.addTextChangedListener(new FlexEditTextWatcher(flexShrinkInput, new NonNegativeDecimalInputValidator(), R.string.must_be_non_negative_float)); final TextInputLayout flexBasisPercentInput = (TextInputLayout) view .findViewById(R.id.input_layout_flex_basis_percent); EditText flexBasisPercentEdit = (EditText) view.findViewById(R.id.edit_text_flex_basis_percent); if (mFlexItem.flexBasisPercent != FlexboxLayout.LayoutParams.FLEX_BASIS_PERCENT_DEFAULT) { flexBasisPercentEdit.setText(String.valueOf(Math.round(mFlexItem.flexBasisPercent * 100))); } else { flexBasisPercentEdit.setText(String.valueOf((int) mFlexItem.flexBasisPercent)); } flexBasisPercentEdit.addTextChangedListener(new FlexEditTextWatcher(flexBasisPercentInput, new FlexBasisPercentInputValidator(), R.string.must_be_minus_one_or_non_negative_integer)); final TextInputLayout widthInput = (TextInputLayout) view.findViewById(R.id.input_layout_width); EditText widthEdit = (EditText) view.findViewById(R.id.edit_text_width); widthEdit.setText(String.valueOf(mFlexItem.width)); widthEdit.addTextChangedListener(new FlexEditTextWatcher(widthInput, new DimensionInputValidator(), R.string.must_be_minus_one_or_minus_two_or_non_negative_integer)); final TextInputLayout heightInput = (TextInputLayout) view.findViewById(R.id.input_layout_height); EditText heightEdit = (EditText) view.findViewById(R.id.edit_text_height); heightEdit.setText(String.valueOf(mFlexItem.height)); heightEdit.addTextChangedListener(new FlexEditTextWatcher(heightInput, new DimensionInputValidator(), R.string.must_be_minus_one_or_minus_two_or_non_negative_integer)); final TextInputLayout minWidthInput = (TextInputLayout) view.findViewById(R.id.input_layout_min_width); EditText minWidthEdit = (EditText) view.findViewById(R.id.edit_text_min_width); minWidthEdit.setText(String.valueOf(mFlexItem.minWidth)); minWidthEdit.addTextChangedListener(new FlexEditTextWatcher(minWidthInput, new FixedDimensionInputValidator(), R.string.must_be_non_negative_integer)); final TextInputLayout minHeightInput = (TextInputLayout) view.findViewById(R.id.input_layout_min_height); EditText minHeightEdit = (EditText) view.findViewById(R.id.edit_text_min_height); minHeightEdit.setText(String.valueOf(mFlexItem.minHeight)); minHeightEdit.addTextChangedListener(new FlexEditTextWatcher(minHeightInput, new FixedDimensionInputValidator(), R.string.must_be_non_negative_integer)); final TextInputLayout maxWidthInput = (TextInputLayout) view.findViewById(R.id.input_layout_max_width); EditText maxWidthEdit = (EditText) view.findViewById(R.id.edit_text_max_width); maxWidthEdit.setText(String.valueOf(mFlexItem.maxWidth)); maxWidthEdit.addTextChangedListener(new FlexEditTextWatcher(maxWidthInput, new FixedDimensionInputValidator(), R.string.must_be_non_negative_integer)); final TextInputLayout maxHeightInput = (TextInputLayout) view.findViewById(R.id.input_layout_max_height); EditText maxHeightEdit = (EditText) view.findViewById(R.id.edit_text_max_height); maxHeightEdit.setText(String.valueOf(mFlexItem.maxHeight)); maxHeightEdit.addTextChangedListener(new FlexEditTextWatcher(maxHeightInput, new FixedDimensionInputValidator(), R.string.must_be_non_negative_integer)); setNextFocusesOnEnterDown(orderEdit, flexGrowEdit, flexShrinkEdit, flexBasisPercentEdit, widthEdit, heightEdit, minWidthEdit, minHeightEdit, maxWidthEdit, maxHeightEdit); Spinner alignSelfSpinner = (Spinner) view.findViewById(R.id.spinner_align_self); ArrayAdapter<CharSequence> arrayAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.array_align_self, R.layout.spinner_item); alignSelfSpinner.setAdapter(arrayAdapter); alignSelfSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { String selected = parent.getItemAtPosition(position).toString(); if (selected.equals(ALIGN_SELF_AUTO)) { mFlexItem.alignSelf = FlexboxLayout.LayoutParams.ALIGN_SELF_AUTO; } else if (selected.equals(ALIGN_SELF_FLEX_START)) { mFlexItem.alignSelf = FlexboxLayout.LayoutParams.ALIGN_SELF_FLEX_START; } else if (selected.equals(ALIGN_SELF_FLEX_END)) { mFlexItem.alignSelf = FlexboxLayout.LayoutParams.ALIGN_SELF_FLEX_END; } else if (selected.equals(ALIGN_SELF_CENTER)) { mFlexItem.alignSelf = FlexboxLayout.LayoutParams.ALIGN_SELF_CENTER; } else if (selected.equals(ALIGN_SELF_BASELINE)) { mFlexItem.alignSelf = FlexboxLayout.LayoutParams.ALIGN_SELF_BASELINE; } else if (selected.equals(ALIGN_SELF_STRETCH)) { mFlexItem.alignSelf = FlexboxLayout.LayoutParams.ALIGN_SELF_STRETCH; } } @Override public void onNothingSelected(AdapterView<?> parent) { // No op } }); CheckBox wrapBeforeCheckBox = (CheckBox) view.findViewById(R.id.checkbox_wrap_before); wrapBeforeCheckBox.setChecked(mFlexItem.wrapBefore); wrapBeforeCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { mFlexItem.wrapBefore = isChecked; } }); int alignSelfPosition = arrayAdapter.getPosition(alignSelfAsString(mFlexItem.alignSelf)); alignSelfSpinner.setSelection(alignSelfPosition); view.findViewById(R.id.button_cancel).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dismiss(); } }); final Button okButton = (Button) view.findViewById(R.id.button_ok); okButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (orderTextInput.isErrorEnabled() || flexGrowInput.isErrorEnabled() || flexBasisPercentInput.isErrorEnabled() || widthInput.isErrorEnabled() || heightInput.isErrorEnabled() || minWidthInput.isErrorEnabled() || minHeightInput.isErrorEnabled() || maxWidthInput.isErrorEnabled() || maxHeightInput.isErrorEnabled()) { Toast.makeText(getActivity(), R.string.invalid_values_exist, Toast.LENGTH_SHORT).show(); return; } if (mFlexItemChangedListener != null) { mFlexItemChangedListener.onFlexItemChanged(mFlexItem); } dismiss(); } }); return view; }
From source file:org.tvheadend.tvhclient.fragments.TimerRecordingAddFragment.java
@Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (channelName != null) { TVHClientApplication app = (TVHClientApplication) activity.getApplication(); List<String> channels = new ArrayList<String>(); for (Channel c : app.getChannels()) { channels.add(c.name);// w w w. j a v a 2 s . c o m } ArrayAdapter<String> adapter = new ArrayAdapter<String>(activity, android.R.layout.simple_spinner_item, channels); channelName.setAdapter(adapter); channelName.setSelection(channelSelectionValue); } if (priority != null) { ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(activity, R.array.dvr_priorities, android.R.layout.simple_spinner_item); priority.setAdapter(adapter); priority.setSelection((int) priorityValue); } if (daysOfWeek != null) { MultiSpinnerListener msl = new MultiSpinnerListener() { @Override public void onItemsSelected(boolean[] checked) { daysOfWeekValue = daysOfWeek.getSpinnerValue(); } }; List<String> items = new ArrayList<String>( Arrays.asList(getResources().getStringArray(R.array.day_long_names))); List<String> textItems = new ArrayList<String>( Arrays.asList(getResources().getStringArray(R.array.day_short_names))); daysOfWeek.setItems(items, textItems, daysOfWeekValue, msl); } if (startTime != null && stopTime != null) { // Converts the value in minutes into a time format SimpleDateFormat formatter = new SimpleDateFormat("HH:mm", Locale.US); // Fill the list with the time values from 0:00 to 23:50 List<String> timeList = new ArrayList<String>(); for (int i = 0; i <= 1430; i += 10) { String time = formatter.format(new Date(i * 60L * 1000L)); timeList.add(time); } ArrayAdapter<String> adapter = new ArrayAdapter<String>(activity, android.R.layout.simple_spinner_item, timeList); startTime.setAdapter(adapter); stopTime.setAdapter(adapter); String start = formatter.format(new Date(startTimeValue * 60L * 1000L)); String stop = formatter.format(new Date(stopTimeValue * 60L * 1000L)); startTime.setSelection(adapter.getPosition(start)); stopTime.setSelection(adapter.getPosition(stop)); } if (title != null) { title.setText(titleValue); } if (name != null) { name.setText(nameValue); } if (directory != null) { directory.setText(directoryValue); } if (retention != null) { retention.setText(String.valueOf(retentionValue)); } if (isEnabled != null) { isEnabled.setChecked(enabledValue); } if (toolbar != null) { if (rec != null) { toolbar.setTitle((rec.name.length() > 0) ? rec.name : rec.title); } toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { return onToolbarItemSelected(item); } }); // Inflate a menu to be displayed in the toolbar toolbar.inflateMenu(R.menu.save_cancel_menu); toolbar.setTitle(R.string.add_recording); } }
From source file:uk.org.ngo.squeezer.NowPlayingFragment.java
/** * Manages the list of connected players in the action bar. * * @param players A list of players to show. May be empty (use {@code * Collections.<Player>emptyList()}) but not null. * @param activePlayer The currently active player. May be null. *///from w ww . j av a 2 s . c om @UiThread private void updatePlayerDropDown(@NonNull Collection<Player> players, @Nullable Player activePlayer) { if (!isAdded()) { return; } // Only include players that are connected to the server. ArrayList<Player> connectedPlayers = new ArrayList<Player>(); for (Player player : players) { if (player.getConnected()) { connectedPlayers.add(player); } } ActionBar actionBar = mActivity.getSupportActionBar(); // If there are multiple players connected then show a spinner allowing the user to // choose between them. if (connectedPlayers.size() > 1) { actionBar.setDisplayShowTitleEnabled(false); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST); final ArrayAdapter<Player> playerAdapter = new ArrayAdapter<Player>(actionBar.getThemedContext(), android.R.layout.simple_spinner_dropdown_item, connectedPlayers) { @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { return Util.getActionBarSpinnerItemView(getContext(), convertView, parent, getItem(position).getName()); } @Override public View getView(int position, View convertView, ViewGroup parent) { return Util.getActionBarSpinnerItemView(getContext(), convertView, parent, getItem(position).getName()); } }; actionBar.setListNavigationCallbacks(playerAdapter, new ActionBar.OnNavigationListener() { @Override public boolean onNavigationItemSelected(int position, long id) { if (!playerAdapter.getItem(position).equals(mService.getActivePlayer())) { Log.i(TAG, "onNavigationItemSelected.setActivePlayer(" + playerAdapter.getItem(position) + ")"); mService.setActivePlayer(playerAdapter.getItem(position)); updateUiFromPlayerState(mService.getActivePlayerState()); } return true; } }); if (activePlayer != null) { actionBar.setSelectedNavigationItem(playerAdapter.getPosition(activePlayer)); } } else { // 0 or 1 players, disable the spinner, and either show the sole player in the // action bar, or the app name if there are no players. actionBar.setDisplayShowTitleEnabled(true); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); if (connectedPlayers.size() == 1) { actionBar.setTitle(connectedPlayers.get(0).getName()); } else { // TODO: Alert the user if there are no connected players. actionBar.setTitle(R.string.app_name); } } }
From source file:au.com.wallaceit.reddinator.SubredditSelectActivity.java
private void showMultiEditDialog(final String multiPath) { JSONObject multiObj = global.getSubredditManager().getMultiData(multiPath); @SuppressLint("InflateParams") LinearLayout dialogView = (LinearLayout) getLayoutInflater().inflate(R.layout.dialog_multi_edit, null); // passing null okay for dialog final Button saveButton = (Button) dialogView.findViewById(R.id.multi_save_button); final Button renameButton = (Button) dialogView.findViewById(R.id.multi_rename_button); multiName = (TextView) dialogView.findViewById(R.id.multi_pname); final EditText displayName = (EditText) dialogView.findViewById(R.id.multi_name); final EditText description = (EditText) dialogView.findViewById(R.id.multi_description); final EditText color = (EditText) dialogView.findViewById(R.id.multi_color); final Spinner icon = (Spinner) dialogView.findViewById(R.id.multi_icon); final Spinner visibility = (Spinner) dialogView.findViewById(R.id.multi_visibility); final Spinner weighting = (Spinner) dialogView.findViewById(R.id.multi_weighting); ArrayAdapter<CharSequence> iconAdapter = ArrayAdapter.createFromResource(SubredditSelectActivity.this, R.array.multi_icons, android.R.layout.simple_spinner_item); iconAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); icon.setAdapter(iconAdapter);/*w w w . j a v a 2 s . c o m*/ ArrayAdapter<CharSequence> visibilityAdapter = ArrayAdapter.createFromResource(SubredditSelectActivity.this, R.array.multi_visibility, android.R.layout.simple_spinner_item); visibilityAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); visibility.setAdapter(visibilityAdapter); ArrayAdapter<CharSequence> weightsAdapter = ArrayAdapter.createFromResource(SubredditSelectActivity.this, R.array.multi_weights, android.R.layout.simple_spinner_item); weightsAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); weighting.setAdapter(weightsAdapter); try { multiName.setText(multiObj.getString("name")); displayName.setText(multiObj.getString("display_name")); description.setText(multiObj.getString("description_md")); color.setText(multiObj.getString("key_color")); String iconName = multiObj.getString("icon_name"); icon.setSelection(iconAdapter.getPosition(iconName.equals("") ? "none" : iconName)); visibility.setSelection(iconAdapter.getPosition(multiObj.getString("visibility"))); weighting.setSelection(iconAdapter.getPosition(multiObj.getString("weighting_scheme"))); } catch (JSONException e) { e.printStackTrace(); } ViewPager pager = (ViewPager) dialogView.findViewById(R.id.multi_pager); LinearLayout tabsWidget = (LinearLayout) dialogView.findViewById(R.id.multi_tab_widget); pager.setAdapter(new SimpleTabsAdapter(new String[] { "Subreddits", "Settings" }, new int[] { R.id.multi_subreddits, R.id.multi_settings }, SubredditSelectActivity.this, dialogView)); SimpleTabsWidget simpleTabsWidget = new SimpleTabsWidget(SubredditSelectActivity.this, tabsWidget); simpleTabsWidget.setViewPager(pager); ThemeManager.Theme theme = global.mThemeManager.getActiveTheme("appthemepref"); int headerColor = Color.parseColor(theme.getValue("header_color")); int headerText = Color.parseColor(theme.getValue("header_text")); simpleTabsWidget.setBackgroundColor(headerColor); simpleTabsWidget.setTextColor(headerText); simpleTabsWidget.setInidicatorColor(Color.parseColor(theme.getValue("tab_indicator"))); ListView subList = (ListView) dialogView.findViewById(R.id.multi_subredditList); multiSubsAdapter = new SubsListAdapter(SubredditSelectActivity.this, multiPath); subList.setAdapter(multiSubsAdapter); renameButton.getBackground().setColorFilter(headerColor, PorterDuff.Mode.MULTIPLY); renameButton.setTextColor(headerText); renameButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { showMultiRenameDialog(multiPath); } }); saveButton.getBackground().setColorFilter(headerColor, PorterDuff.Mode.MULTIPLY); saveButton.setTextColor(headerText); saveButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { System.out.println("Save multi"); JSONObject multiObj = new JSONObject(); try { multiObj.put("decription_md", description.getText().toString()); multiObj.put("display_name", displayName.getText().toString()); multiObj.put("icon_name", icon.getSelectedItem().toString().equals("none") ? "" : icon.getSelectedItem().toString()); multiObj.put("key_color", color.getText().toString()); multiObj.put("subreddits", global.getSubredditManager().getMultiData(multiPath).getJSONArray("subreddits")); multiObj.put("visibility", visibility.getSelectedItem().toString()); multiObj.put("weighting_scheme", weighting.getSelectedItem().toString()); new SubscriptionEditTask(SubscriptionEditTask.ACTION_MULTI_EDIT).execute(multiPath, multiObj); } catch (JSONException e) { e.printStackTrace(); } } }); AlertDialog.Builder builder = new AlertDialog.Builder(SubredditSelectActivity.this); multiDialog = builder.setView(dialogView).show(); }
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;/* w w w.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); }